# This is a near linear conversion of the C# example. Some changes were made to be more PowerShell-like.
# The Try/Catch is primitive but does work and show that exceptions are fully available with PowerShell V2
# and the Security classes.
#Adds an ACL entry on the specified directory for the specified account.
function AddDirectorySecurity([string]$FileName, [string]$Account, [string]$Rights,[string]$ControlType)
{
#Create a new DirectoryInfo object.
$dInfo = New-Object System.IO.DirectoryInfo($FileName)
#Get a DirectorySecurity object that represents the current security settings.
$dSecurity = $dInfo.GetAccessControl()
#Add the FileSystemAccessRule to the security settings.
$ace = New-Object System.Security.AccessControl.FileSystemAccessRule($Account,$Rights,$ControlType)
$dSecurity.AddAccessRule( $ace)
#Set the new access settings.
$dInfo.SetAccessControl($dSecurity);
}
#Removes an ACL entry on the specified directory for the specified account.
function RemoveDirectorySecurity([string]$FileName, [string]$Account, [string]$Rights, [string]$ControlType)
{
#Create a new DirectoryInfo object.
$dInfo = New-Object System.IO.DirectoryInfo($FileName)
#Get a DirectorySecurity object that represents the current security settings.
$dSecurity = $dInfo.GetAccessControl();
#Add the FileSystemAccessRule to the security settings.
$dSecurity.RemoveAccessRule( $(New-Object System.Security.AccessControl.FileSystemAccessRule($Account,
$Rights,
$ControlType)) )
#Set the new access settings.
$dInfo.SetAccessControl($dSecurity);
}
[string]$DirectoryName = "e:\Test";
[string]$ntaccount='Guest'
#Add the access control entry to the directory.
try{
Write-Host "Adding access control entry for " + $DirectoryName -ForegroundColor green
AddDirectorySecurity $DirectoryName $ntaccount "ReadData" "Allow"
Write-Host "Removing access control entry from " + $DirectoryName -ForegroundColor green
#Remove the access control entry from the directory.
RemoveDirectorySecurity $DirectoryName $ntaccount "ReadData" "Allow"
}
catch [System.SystemException]{
Write-Host "An error occured for " + $DirectoryName -ForegroundColor red
}
Write-Host "Done." -ForegroundColor green