Search code examples
powershellwindows-server-2012powershell-4.0

temporarily take ownership of a folder


I need to temporarily take ownership of a profilefolder, in order to add permissions(ReadOnly) to members of a securitygroup. I would like to know how to achieve this in powershell.

I have before used TakeOwn.exe, but since it can't give ownership back to the original owner, I can't use it for this.

I tried using a module called PowerShellAccessControl, which I found on technet.

Import-Module $PSScriptRoot\modules\PowerShellAccessControl\PowerShellAccessControl.psd1

$path = "$PSScriptRoot\profileFolders\profile"

$AddAceParams = @{
    Principal = "SecurityGroup"
    FolderRights = "Read"
}

Get-SecurityDescriptor $path -PacSDOption (New-PacCommandOption -BypassAclCheck) | ForEach-Object {
    $OriginalOwner = $_.Owner

    $_ | Set-Owner -PassThru -Apply | 
        Add-AccessControlEntry @AddAceParams -PassThru |
        Set-Owner -Principal $OriginalOwner -Apply 
}

But this code only resultet in the following error:

New-PacCommandOption : The term 'New-PacCommandOption' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

I dont know if i should continue with this module or if there is a better way.


Solution

  • I tend to use the NTFSSecurity module when dealing with filesystem permissions, it's well written and I've had good success with it so far.

    $path = "C:\folder"
    $OriginalPermissions = Get-NTFSOwner $path
    
    Set-NTFSOwner -Path $path -Account $env:USERNAME
    Add-NTFSAccess -Path $path -Account 'DOMAIN\SecurityGroup' -AccessRights Read
    Set-NTFSOwner -Path $path -Account $OriginalPermissions.Owner
    

    Note: You do need to install the module, if you're using a modern version of Powershell this is easy as you can just use Install-Module -Name NTFSSecurity. If it's an older version you will need download and install the module manually.


    EDIT:

    The other option is to use Enable-Privileges to grant your account the privileges for Backup, Restore, and Security.

    With these you will be able to edit the permissions without your own account having explicit permissions to the data. Use of these command is covered in the documentation in the link above. Be sure to Disable-Privileges after enabling them as it's not good practice to run with these all the time.