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?
ICACLS is just an .exe, so you run it in PowerShell the same way that you run any other program, by typing its name at the PowerShell prompt.
Use iCACLS to Set Folder's or File's PermissionsWith the icacls command, you can change the access lists for the folder. To change an object's DACL, the user must have write DAC permission (WRITE_DAC — WDAC). At least one user (the owner of the object) has the permission to modify the DACL.
To use Set-Acl , use the Path or InputObject parameter to identify the item whose security descriptor you want to change. Then, use the AclObject or SecurityDescriptor parameters to supply a security descriptor that has the values you want to apply. Set-Acl applies the security descriptor that is supplied.
icacls is a command-line utility that can be used to modify NTFS file system permissions in Windows Server 2003 SP2, Windows Server 2008, Windows Vista and Windows 7. It builds on the functionality of similar previous utilities, including cacls, Xcacls.exe, Cacls.exe, and Xcacls.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With