Search code examples
powershellpowershell-3.0powershell-4.0

Modifying folder permissions


Need a little help. The script is not changing the permissions at all.

I want to make the name of the folder be the owner of the folder with full rights.

$foldernames = (Get-ChildItem \\knesmbmdc001\profiles).Name
$user = "$foldernames"
$usercount = 0
foreach($name in $foldernames)
{
If ($usercount -le 5)
{
    Try
    {

        $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($user,"FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
        $acl = get-acl $name
        $acl.AddAccessRule($rule)
        Set-acl $name $acl
    }
    catch
    {
    Add-Content C:\user_done.txt $name
    }
}
} 

Solution

  • The immediate problems with your script:

    • The first argument passed to New-Object System.Security.AccessControl.FileSystemAccessRule should be $name, not $user.

    • Your Add-Content call to write to a log file should not be in the catch clause, as it will then only log if the ACL operation did not succeed.

    • By having no other statements in your catch clause, exceptions are effectively ignored.

    • You're passing mere folder names to cmdlets that expect paths (Get-Acl, Set-Acl), which only works if the current location happens to be the folder's parent location.

    Here's a reformulation of your script that should work as intended:

    $dir = '\\knesmbmdc001\profiles'
    $logFile = 'C:\user_done.txt'
    Get-ChildItem -Directory $dir | % {
        $user = $_.Name
        $acl = Get-Acl -LiteralPath $_
        $rule = New-Object System.Security.AccessControl.FileSystemAccessRule $user, FullControl, "ContainerInherit, ObjectInherit", None, Allow
        $acl.AddAccessRule($rule)
        Set-Acl -LiteralPath $_ -AclObject $acl
        Add-Content $logFile $user
     }
    

    Note, however, that while this will give full control to the target user, it does not make them the owner of the folder.

    To actually change ownership, try the following (replace the $rule=... and $acl.AddAccessRule... commands):

    $userIdentity = New-Object System.Security.Principal.NTAccount $user
    $acl.SetOwner($userIdentity)
    

    This worked for me with a local user account while running with elevated privileges, but YMMV.