PowerShell: Set or Remove Permission from A Folder

This script is to search through the parent folder for the name of the folder that you want to set or remove permissions.

Let’s say that you want to add the username Trainer_1 to all the folders named Training Class under the parent folder D:\School

# Give full permission for a user or a computer to all the folders named "Training Class"

$parentPath = D:\School 
$folderName = Training Class

"`n"

$found = Get-ChildItem -Recurse -Force $parentPath -ErrorAction SilentlyContinue | Where-Object { ($_.PSIsContainer -eq $true) -and  ( $_.Name -like "*$folderName*") } | Select-Object FullName | foreach {$_.FullName}

for ($i =0; $i -le $found.Count; $i++){
      $myGroup = "Trainer_1"
      $acl = Get-Acl $found[i]
      $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$myGroup", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
      $acl.AddAccessRule($rule)
      Set-Acl $found[i] $acl
}

Now, you want to remove the username Trainer_2 from all the folder Training Class.

# Give full permission for a user or a computer to all the folders named "Training Class"

$parentPath = D:\School 
$folderName = Training Class

"`n"

$found = Get-ChildItem -Recurse -Force $parentPath -ErrorAction SilentlyContinue | Where-Object { ($_.PSIsContainer -eq $true) -and  ( $_.Name -like "*$folderName*") } | Select-Object FullName | foreach {$_.FullName}

for ($i =0; $i -le $found.Count; $i++){
      $myGroup = "Trainer_2"
      $acl = Get-Acl $found[i]
      $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$myGroup", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
      $acl.RemoveAccessRuleAll($rule)
      Set-Acl $found[i] $acl
}

You can also give end users more flexibility by allowing to enter path and folder name on the screen

write-Host "---------------------------------------------" -ForegroundColor Yellow
$filePath = Read-Host "Please Enter Folder Path to Search"
write-Host "---------------------------------------------" -ForegroundColor Green
$fileName = Read-Host "Please Enter Folder Name to Search"
write-Host "---------------------------------------------" -ForegroundColor Yellow

 

Comments are closed