Set Permissions of NTFS/SMB Directories Recursively

# Set variables here
$proxy="http://proxy:80"
$directories="\\FILESERVER01\dept01$","\\FILESERVER01\dept02$"
$grantAccess="KIMCONNECT\SysAdmins"
$access="Full"

# Run as
$username = "kimconnect\kim"
$password = "PASSWORD"
#$username = "kimconnect\"+(Read-Host -Prompt 'Input the Admin Username: ')
#$password = Read-Host -Prompt "Input the password for account $username"
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,$pass
$elevate = New-PSSession -ComputerName "FILESERVER01" -Credential $cred

Invoke-Command -Session $elevate -ScriptBlock $Args $proxy,$directories,$grantAccess,$access {
$thisProxy=$Args[0];
$theseDirectories=$Args[1];
$thisIdentity=$Args[2];
$thisAccess=$Args[3]
$count=$theseDirectories.count;
$i=0;

"Running as "+ (whoami)
# Check if proxy is enabled, then assign the proper proxy server

if((Get-ItemProperty -Path "Registry::HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings").ProxyEnable) {
   $PSDefaultParameterValues = @{"*:Proxy"=$thisProxy}
    }

# Include the required NTFSSecurity library from the PowerShell Gallery
if (!(Get-InstalledModule -Name NTFSSecurity)) {Install-Module -Name NTFSSecurity -Force}

$theseDirectories | foreach {
try{
   foreach ($directory in $theseDirectories){
       $i++;
       "Setting permissions on directory $i of $count`: $directory ...";
       Add-NTFSAccess –Path $directory –Account $thisIdentity –AccessRights $thisAccess -ErrorAction Stop;
       }
   }
catch{
   (Get-Date -Format g)+": "+ $_.Exception.Message
   continue;
   }
finally{   
   "$directory processed."
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *