Setting file ACLs with PowerShell part 3

Security Briefs

Syndication

In my last post, I showed how to retrieve a file system ACL (well, technically a security descriptor) via PowerShell. Today I'll show you how to tweak that ACL using System.Security.AccessControl.

$newRule = New-Object Security.AccessControl.FileSystemAccessRule "keith", Modify, Allow

This next line of code in my example creates an "access rule". This is a lot like an Access Control Entry (ACE) in the Win32 API, if you happen to be familiar with that. A rule has several parts that describe a permission that you want to grant or deny:

  • an IdentityReference (the user/group you're talking about)
  • an AccessMask (a bitmask describing which permissions you're talking about)
  • a flag that indicates whether this is a grant or a denial of the permissions
  • a set of flags that determine how this rule should be inherited by child items

Note how I created this object in PowerShell. The New-Object cmdlet allows you to specify a .NET type that you want to instantiate. In this case, I'm creating an instance of System.AccessControl.FileSystemAccessRule, although I've saved some space by omitting "System." since PowerShell searches that namespace by default.

Following the type name is an array that contains the ctor arguments. Constructing an access rule is pretty easy since you can pass strings that represent the user or group accounts, and the framework will happily look up the Security Identifier (SID) on your behalf. Little features like this are one reason working with System.Security.AccessControl is so much more pleasant than the underlying Win32 interface! Note that here I'm just using the account name, "Keith", but I could have been more specific and used the fully-qualified MACHINE\ACCOUNT or DOMAIN\ACCOUNT syntax, such as, "MyDomain\Keith". And in practice I'd be using a group instead of an individual user to grant permissions (for this example I decided to stick with something really concrete and easy).

The second and third ctor arguments show off one of my favorite features of PowerShell. I hate typing any more than I have to, and it's great to have context-sensitive evaluation of enumerations like this. By simply passing in the symbol, Modify, PowerShell knows that I mean FileSystemRights.Modify. The same goes for AccessControlType.Allow. This can make your code more readable than even the equivalent C# code because it eliminates so much clutter.

I'll have more to say about enumerations and PowerShell in my next post.

Navigate posts in this series: prev next


Posted Oct 31 2007, 04:12 AM by keith-brown

Add a Comment

(required)  
(optional)
(required)  
Remember Me?