How to Take Ownership of Files and Folders Using PowerShell
Ever had to take ownership of a bunch of files and folders? It’s a pain, right? Well, not anymore!
The Problem
Picture this: You’ve just gotten an external hard drive from a dead computer and need to access the files. But wait! You don’t have the correct permissions. I had to do this, and setting the file permissions through Explorer was failing randomly. It appears that the folders all had different permissions, and the propagation was failing.
The Solution
I’ve got a PowerShell script that’ll save you time. It does two things:
- Takes ownership of a folder and all its subdirectories and files (recursively) and sets the owner to the current logged-in user
- Adds the current user to the permissions with full control
The Script
First, here’s the script. Don’t worry, I’ll break it down for you:
# Ensure the script is running with administrator privileges
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Warning "You do not have Administrator rights to run this script!`nPlease re-run this script as an Administrator!"
Break
}
# Get the current user
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
# Function to take ownership and set permissions
function Set-OwnershipAndPermissions {
param (
[string]$path
)
try {
# Take ownership
$acl = Get-Acl $path
$owner = New-Object System.Security.Principal.NTAccount($currentUser)
$acl.SetOwner($owner)
Set-Acl -Path $path -AclObject $acl -ErrorAction Stop
# Set permissions
$acl = Get-Acl $path
if (Test-Path -Path $path -PathType Container) {
# It's a directory
$permission = $currentUser, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"
} else {
# It's a file
$permission = $currentUser, "FullControl", "None", "None", "Allow"
}
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
$acl.SetAccessRule($accessRule)
Set-Acl -Path $path -AclObject $acl -ErrorAction Stop
Write-Host "Successfully processed: $path"
}
catch {
Write-Warning "Failed to process $path. Error: $_"
}
# Process subdirectories and files if it's a directory
if (Test-Path -Path $path -PathType Container) {
try {
Get-ChildItem $path -Force -ErrorAction Stop | ForEach-Object {
Set-OwnershipAndPermissions $_.FullName
}
}
catch {
Write-Warning "Failed to access contents of $path. Error: $_"
}
}
}
# Prompt for the folder path
$folderPath = Read-Host "Enter the full path of the folder"
# Check if the folder exists
if (Test-Path $folderPath) {
# Run the function
Set-OwnershipAndPermissions $folderPath
Write-Host "Process completed for $folderPath and all accessible contents."
} else {
Write-Host "The specified folder does not exist."
}
How to Use It
- Copy this script and save it as a
.ps1
file (liketake_ownership.ps1
). - Right-click on PowerShell and select “Run as administrator” (this is crucial!).
- Navigate to where you saved the script.
- Run it by typing
.\take_ownership.ps1
. - When prompted, enter the full path of the folder you want to process.
What’s Going On Here?
Let’s break this down a bit:
- Admin Check: The script starts by ensuring you run it as an admin. No admin rights? No dice.
- Current User: It grabs the current user’s name. This is who’s going to own everything.
- The Magic Function:
Set-OwnershipAndPermissions
is where the real magic happens. It:- Takes ownership of the item (file or folder)
- Sets the current user as the owner
- Gives the current user full control
- If it’s a folder, it does all this recursively for everything inside
- Error Handling: The script’s got your back with some neat error handling. It’ll let you know if it can’t process something and keep on truckin’.
- File vs. Folder: It’s smart enough to know the difference between files and folders and set the right permissions for each.
Why This is Awesome
- Time Saver: Imagine doing all this manually. Yikes!
- Consistency: It applies the same permissions everywhere, no mistakes.
- Flexibility: Works on any folder you point it to.
Wrapping Up
There you have it, folks! A powerful little script to take control of your files and folders. No more permission headaches, no more “access denied” nightmares — just pure, unadulterated file access bliss.
Got questions? Hit me up in the comments. And don’t forget to share this with your IT buddies – they’ll thank you later!
Happy scripting!
Windows 7 & 10 How to Bulk Unblock Blocked Files
While setting up a new computer, Windows was throwing up warnings that files transferred from a backup drive might be unsafe. The files were text and images, so the warnings were safe to ignore but the directory had over one thousand files. Rather than unblocking each file manually, Windows PowerShell makes it easy to unblock files in bulk.
Load up Windows Powershell:
- Press Win + R on the keyboard to open the Run dialog.
- In the Run box, type powershell
For one folder without subdirectories, this snippet will do the trick.“$env:userprofile\Downloads“ tells PowerShell to use the Download folder for the logged in user and unblocks all files in it. Change this to the folder path you need if it’s not the Downloads folder.
get-childitem “$env:userprofile\Downloads“ | unblock-file
If you have sub-directories and need to unblock everything, use the -Recurse flag:
dir “$env:userprofile\Downloads“ -Recurse | Unblock-File
Want to see a report of files to be unblocked before running it? The -WhatIf flag will show you without executing.
dir “$env:userprofile\Downloads“ -Recurse | Unblock-File -WhatIf