Powershell Set-Acl - 错误新对象:找不到 "FileSystemAccessRule" 和参数计数的重载:“1”

Powershell Set-Acl - Error New-Object : Cannot find an overload for "FileSystemAccessRule" and the argument count: "1"

我正在使用以下数组对目录应用权限但出现错误:

New-Object:找不到 "FileSystemAccessRule" 的重载和参数计数:“1”。

$psarray = @(
    ('xppusers', 'D:\XPP\xz\bin', 'Read'),
    ('xppusers', 'D:\XPP\xz\sys\config', 'Read'),
    ('xppusers', 'D:\XPP\sd_liz', 'Read'),
    ('xppusers', 'D:\XPP\xz\help', 'Read')
)


foreach($item in $psarray)
{
    $permission = "'" + $item[0] + "', '" + $item[2] + "', 'ContainerInherit, ObjectInherit', 'None', 'Allow'"
    $rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission
    $acl.SetAccessRule($rule)
    $acl | Set-Acl -Path $item[1]
}

完整的错误是:

New-Object : Cannot find an overload for "FileSystemAccessRule" and the argument count: "1".
At C:\GPO-Installers\permissions-array.ps1:20 char:13
+     $rule = New-Object -TypeName System.Security.AccessControl.FileSy ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

如果我手动创建 $permission,它工作正常。

例如:

$permission = 'xppusers', 'read', 'ContainerInherit, ObjectInherit', 'None', 'Allow'

不确定哪里出了问题,非常感谢您的帮助。

谢谢。

编辑:

感谢@mklement0,我已经解决了这个问题并让它工作了。在压力消失的某个阶段,我会回去正确理解这一点,而不仅仅是 copy/pasta 我解决问题的方式。

我通过在 foreach 循环中创建所需的变量然后在 New-Object 中使用这些变量来完成这项工作。

foreach($item in $UserGroupPermissionArray)
    {     
        $UserGroup = $item[0]
        $Path = $item[1]
        $acl = Get-Acl -Path $Path
        $FileSystemRights = $item[2]
        $InheritanceFlag = "ContainerInherit"
        $PropagationFlag = "None"
        $AccessControlType = "Allow"
        $rule = New-Object System.Security.AccessControl.FileSystemAccessRule ($UserGroup, $FileSystemRights, $InheritanceFlag, $PropagationFlag, $AccessControlType)
        $acl.SetAccessRule($rule)
        $acl | Set-Acl -Path $Path
    }

您错误地将 单个字符串 传递给 System.Security.AccessControl.FileSystemAccessRule 构造函数(通过 New-Object -ArgumentList);该错误意味着没有构造函数(重载)采用 单个 类型的参数 [string].[1]

相反,您必须单独传递构造函数参数,这在New-Object的上下文中意味着作为数组-Args-ArgumentList 的别名,您甚至可以省略 -Args):

$rule = New-Object System.Security.AccessControl.FileSystemAccessRule `
          -Args ($item + 'ContainerInherit, ObjectInherit', 'None', 'Allow')

因为 $item 是一个包含前 2 个构造函数参数的数组,您可以简单地使用数组连接 (+) 来附加 [2]不变参数。


[1] 错误消息在某些情况下可能会产生误导,因为它没有明确说明它不是 重要的参数计数,还有参数的数据类型。例如,如果 一个单参数构造函数,您会看到相同的消息,但它的参数类型是 other 而不是 [string].

[2] 从技术上讲,创建了一个 new 数组,它是输入数组中元素的串联。