Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Combine ContainerInherit and ObjectInherit in FileSystemAccessRule?

I'm writing a script that should set filesystem access rights for a folder and all of it's contents.

To affect all content, both subfolders and files, one should combine ContainerInherit and ObjectInherit according to the .NET documentation. But I can't get that to work and I'm not sure about the syntax.

Sample code:

$ar = new-object System.Security.AccessControl.FileSystemAccessRule(New-Object System.Security.Principal.NTAccount($user),FullControl,ContainerInherit,InheritOnly,Allow)

That'll work and so would using ObjectInherit only, but how can I combine them? Using quotation marks and a comma, like this "ContainerInherit,ObjectInherit" won't work, since it's appearantly not allowed to mix string and non-string argument.

I've also tried using the -and operator, but that just gives me an error. Assigning the enums to a variable ($inherit = ContainerInherit,ObjectInherit) won't work either.

So, any tips on how to do this?

like image 840
Mikael Grönfelt Avatar asked Dec 21 '22 22:12

Mikael Grönfelt


1 Answers

You can merge them using -bor (analogous to | in other languages). Parsing it from a string using a comma as shown in the other answer also works.

I also corrected your sample syntax and this sample should work.

$if=[Security.AccessControl.InheritanceFlags]
$fsr=[Security.AccessControl.FileSystemRights]
$pf=[Security.AccessControl.PropagationFlags]
$flags = [Security.AccessControl.InheritanceFlags]($if::ContainerInherit -bor $if::ObjectInherit)

$ar = new-object Security.AccessControl.FileSystemAccessRule ((New-Object System.Security.Principal.NTAccount($user)),$fsr::FullControl, $flags, $pf::InheritOnly, "Allow")

But even simpler is to use strings only:

new-object Security.AccessControl.FileSystemAccessRule ($user, "FullControl", "ContainerInherit,ObjectInherit", "InheritOnly", "Allow")
like image 168
VoidStar Avatar answered May 12 '23 08:05

VoidStar