Setting file ACLs with PowerShell part 4

Security Briefs

Syndication

In part 3, I walked through the following line of code:

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

I pointed out how the "Modify" was automatically converted into an enumeration value, promising that I'd talk more about enumerations later. Well, this value comes from the System.Security.AccessControl.FileSystemRights enumeration. And there's a cool way you can abuse PowerShell to get a quick and dirty listing of an enumeration's values. But to understand how it works, you'll have to bear with me and learn about type-constrained variables in PowerShell, which is a really cool feature unto itself, and one that I use all the time.

While PowerShell doesn't support strong typing in the classic sense of a compiler, it does have a feature that allows you to constrain the type of a variable whenever it's assigned a value. Here's an example:

$a = 42
[Int32] $b = 42
$a = "this works just fine"
$b = "this generates an invalid cast exception"

This syntax allows you to create type-constrained variables. Now when I assign an object to $b, PowerShell will first try to cast that object to System.Int32 (you could also have used "int", by the way). The last line of code above will throw an invalid cast exception. This is a very useful feature, allowing you to get some helpful type checking in your scripts. But this feature also has a nifty side effect that Bruce describes in his book. You can use this to get a quick listing of enumeration values:

$ [Security.AccessControl.FileSystemRights] "foo"
Cannot convert value "foo" to type "System.Security.AccessControl.FileSystemRights"
due to invalid enumeration values. Specify one of the following enumeration values
and try again. The possible enumeration values are "ListDirectory, ReadData,
WriteData, CreateFiles, CreateDirectories, AppendData, ReadExtendedAttributes,
WriteExtendedAttributes, Traverse, ExecuteFile, DeleteSubdirectoriesAndFiles,
ReadAttributes, WriteAttributes, Write, Delete, ReadPermissions, Read,
ReadAndExecute, Modify, ChangePermissions, TakeOwnership, Synchronize, FullControl"
At line:1 char:42
+ [Security.AccessControl.FileSystemRights]  <<<< "foo"

Stay tuned for more!

Navigate posts in this series: prev next


Posted Nov 29 2007, 09:34 AM by keith-brown

Add a Comment

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