I know I said I was going to do more C# stuff but this powershell stuff is so cool
. If you ever have to do a massive task like set security across multiple servers on a particular Folder or Files you certainly do not want to do this manually . You can do this in a lot languages . In regular batch scripting using calcs.exe or vbcript . Today I’m going to give a powershell example using 2 cmdlets get-acl and set-acl.
So for example you had to set security on a folder c:\temp (not sure why you would want to but its just an example ) .
what you first have to do is get the ACL list from the folder like so :
$acl = Get-Acl c:\temp
next you can setup your account name that you want to add , Set the permission level (i.e. FullControl) and lastly set the allow permission or deny permission set .Lets take a look .
$permission = "domainName\Username","FullControl","Allow"
So now we use $permission in our .net class FileSystemAccessRule like so :
$accessRule = new-object System.Security.AccessControl.FileSystemAccessRule $permission
We instantiated to use the .net class and passed our variable to set our permisson but we have not set it yet .
$acl.SetAccessRule($accessRule)
$acl | Set-Acl c:\temp
Now we did . Now check your folder and it should show full control for the username you specified .
Cool huh ?
I know this may not replace a cacls.exe but it will do the job also this cmdlet (set-acl) will work on the registry provider too which calcs.exe doesn’t do .
Full program
$acl = Get-Acl c:\temp
$permission = "domain\user","FullControl","Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
$acl.SetAccessRule($accessRule)
$acl | Set-Acl c:\temp
Hope this helps .
Chris
Mark 9:00 am on July 21, 2008 Permalink
I tried this but I’m getting an “Access is denied” exception (after removing the trycatch). Any ideas?
Chris 10:22 am on July 21, 2008 Permalink
Mark ,
Can you tell me which line is the the one giving the error ? Does it work with the Try and Catch ?
I think you do need Admin rights to the target machine .
Chris
paul grosjean 6:33 pm on January 19, 2009 Permalink
I can add the administrator username and password and this code works fine. How can I get the instances of only those shares that have the “Everyone” account?
Chris 6:11 pm on January 20, 2009 Permalink
Hi Paul ,
I believe you would add code to the foreach loop . In there before adding the share to the listbox you can place code that checks to see if the everyone group is present and if so then add the share to the lisbox . I will try and look into doing that .
Chris