Hi!
Today’s post will continue series of PowerShell tips for automation. Today’s subject is about adding permissions for user/group to the certain folder.
Here is a function to do that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
function addPermissionsToFolder([string]$folder, $account){ Write-Host "Adding permissions to folder '$folder'" $Acl = (Get-Item $folder).GetAccessControl('Access') $hasPermissionsAlready = ($Acl.Access | where {($_.IdentityReference.Value.Contains($account.ToUpperInvariant()) -or $_.IdentityReference.Value.Contains($account)) -and $_.FileSystemRights -eq [System.Security.AccessControl.FileSystemRights]::FullControl}).Count -eq 1 if ($hasPermissionsAlready){ Write-Host "Folder '$folder' already has the full permissions to account $account." -ForegroundColor Green return $true } else { Write-Host "Folder '$folder' doesn't have the full permissions to account $account" -ForegroundColor Yellow $Ar = New-Object System.Security.AccessControl.FileSystemAccessRule($account, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow") $Acl.SetAccessRule($Ar) Set-Acl $folder $Acl Write-Host "Permissions were added" } } |
Let’s break it into the parts.
The first step is to get current security settings of the folder:
1 |
$Acl = (Get-Item $folder).GetAccessControl('Access') |
Using $Acl variable, we can check if we already have needed permissions (FullControl in our example):
1 |
$hasPermissionsAlready = ($Acl.Access | where {($_.IdentityReference.Value.Contains($account.ToUpperInvariant()) -or $_.IdentityReference.Value.Contains($account)) -and $_.FileSystemRights -eq [System.Security.AccessControl.FileSystemRights]::FullControl}).Count -eq 1 |
If not, we should create a new object with a needed rule, add it to the existing rules and rewrite settings:
1 2 3 |
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule($account, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow") $Acl.SetAccessRule($Ar) Set-Acl $folder $Acl |
That’s it! 🙂