Posted On March 29, 2019

Set Permissions of NTFS/SMB Directories Recursively

kimconnect 0 comments
blog.KimConnect.com >> Codes >> 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 *

Related Post

PowerShell: Process Watcher

# processWatcher.ps1 # User Input $serviceName='MSCRMAsyncService$maintenance' # Semi-autogen variables $desiredStatus='Running' $environment=($env:computername).substring(0,$env:computername.IndexOf('-')) $reportServer="$environment-SQL01" function checkService($computername=$env:computername,$serviceName,$status='Running'){ #…

Front End Web Development Menu 2019

Deployment Register a domain name: Google Domains, GodaddyManaged or Shared hosting: AWS, Hostgator, InmotionFTP/SFTP: Filezilla,…

Check a List of Servers to Find Currently Stopped Autorun Services

$username = (Get-ADDomain).name+'\USERNAME' $Password = 'PASSWORD' $pass = ConvertTo-SecureString -AsPlainText $Password -Force $cred = New-Object…