在Powershell中执行icacls以授予对域计算机的文件共享的访问权限

时间:2014-10-30 08:56:56

标签: powershell permissions share icacls

我想知道如何在powershell脚本中使用icacls来为例如一个computeraccount设置文件共享的权限。域\ myServer上$

这就是我正在尝试的:

$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

我尝试了逃避$的不同变体,但没有找到解决方案。 任何人都有提示如何做到这一点?

谢谢!

2 个答案:

答案 0 :(得分:4)

尝试使用调用运算符(&)或cmd /c代替Invoke-Expression

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

或使用Get-Acl / Set-Acl更改权限:

$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

答案 1 :(得分:0)

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

这很好用。所以我想如果你将命令放入单引号(即''),它将起作用。例如:

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