Ulrich Trentowski
Ulrich Trentowski

Reputation: 81

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

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?

Upvotes: 8

Views: 41390

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200483

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

Upvotes: 9

Maciej
Maciej

Reputation: 31

Invoke-Expression -Command:icacls foldername /grant groupName:"(CI)(OI)M"

This works fine. So I guess that if you will put the command into single quote (i.e. '') it will work. For example:

$ComputerAccount = "domain\myServer$"
Invoke-Expression -Command:"icacls $ComputerAccount /grant GroupName:'(CI)(OI)M'"

Upvotes: 1

Related Questions