8

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?

3 Answers 3

8

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
Sign up to request clarification or add additional context in comments.

Comments

1

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'"

Comments

0

None of the answers above worked, below is what worked for me. The syntax is very finicky and the colon cannot be in the same string as the group or user and the permissions. The directory name does need to be in quotes

    $directory = "C:\Program Files (x86)\Tenacity";
    $group = "Everyone";
    $permissions = "(F) /T /C";
    $icaclsCommand = "icacls `"$($directory)`" /grant $($group):$($permissions)"
    cmd /c $icaclsCommand;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.