Execute icacls in PowerShell to grant access to a file share for domain computer

Ulrich Trentowski picture Ulrich Trentowski · Oct 30, 2014 · Viewed 27.4k times · Source

I wonder how to uses icacls within a PowerShell script for setting up permissions on a fileshare for a computeraccount for e.g. Domain\myServer$.

This is what I'm trying:

$ComputerAccount = "domain\myServer$"
$Folder = "\\TestServer\TestShare\folder1"
$rule = $ComputerAccount+':(M),(OI),(CI)'
$resICacls = Invoke-Expression "icacls $folder /grant $rule"

I got this error message:

Invoke-Expression : At line:1 char:83
+ ... ant Domain\myServer$:(M),(OI),(CI)
+                    ~~

Variable reference is not valid. '$' was not followed by a valid variable name
character. Consider using ${} to delimit the name.
At c:\Binary\testacl.ps1:12 char:26
+             $resICacls = Invoke-Expression "icacls $folder /grant $rule"
+                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Invoke-Expression], ParseException
    + FullyQualifiedErrorId : InvalidVariableReference,Microsoft.PowerShell.Commands.InvokeExpressionCommand

I tried different variants of escaping the $ but found no solution. Anyone haves a hint how to do this?

Answer

Ansgar Wiechers picture Ansgar Wiechers · Oct 30, 2014

Try using the call operator (&) or cmd /c instead of Invoke-Expression:

& icacls $folder /grant $rule
cmd /c icacls $folder /grant $rule

or use Get-Acl/Set-Acl for changing permissions:

$permissions = 'Modify'
$inheritance = 'ContainerInherit, ObjectInherit'

$acl = Get-Acl -Path $folder
$ace = New-Object Security.AccessControl.FileSystemAccessRule ($ComputerAccount, $permissions, $inheritance, 'InheritOnly', 'Allow')
$acl.AddAccessRule($ace)
Set-Acl -AclObject $acl -Path $folder