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:

  1. Takes ownership of a folder and all its subdirectories and files (recursively) and sets the owner to the current logged-in user
  2. 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

  1. Copy this script and save it as a .ps1 file (like take_ownership.ps1).
  2. Right-click on PowerShell and select “Run as administrator” (this is crucial!).
  3. Navigate to where you saved the script.
  4. Run it by typing .\take_ownership.ps1.
  5. 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:

  1. Admin Check: The script starts by ensuring you run it as an admin. No admin rights? No dice.
  2. Current User: It grabs the current user’s name. This is who’s going to own everything.
  3. 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
  4. 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’.
  5. 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

  1. Time Saver: Imagine doing all this manually. Yikes!
  2. Consistency: It applies the same permissions everywhere, no mistakes.
  3. 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!

How to Fix ‘Converter Failed to Save File’ with Excel 2016 How to Prevent Raspberry Pi Zero from Blanking or Sleeping
View Comments
There are currently no comments.