You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell脚本导出共享驱动器权限报错:op_Addition方法不存在

解决PowerShell脚本导出文件夹权限时的'op_Addition'方法错误

错误原因

你遇到的[System.Management.Automation.PSObject] does not contain a method named 'op_Addition'错误,核心原因有两个:

  1. 变量作用域问题:递归函数内部未明确引用全局定义的$permissionsData数组,导致PowerShell可能将其视为局部变量,首次赋值后变成单个PSObject而非数组。
  2. 低效的数组拼接:使用+=操作数组时,PowerShell会每次创建新数组,递归场景下不仅性能差,还可能触发类型转换异常。

修复方案(推荐高效写法)

放弃全局数组,改用PowerShell的管道式对象返回,既解决作用域问题,又提升性能。以下是修正后的完整脚本:

# 定义根文件夹路径
$rootFolder = "C:\Path\To\Your\Folder"
# 定义输出CSV路径
$outputFile = "C:\Path\To\Output\permissions.csv"

# 递归获取文件夹权限的函数(返回权限对象)
function Get-FolderPermissions {
    param (
        [string]$folderPath
    )
    # 处理当前文件夹的权限
    $acl = Get-Acl -Path $folderPath
    foreach ($permission in $acl.Access) {
        [PSCustomObject]@{
            FolderPath          = $folderPath
            IdentityReference   = $permission.IdentityReference
            AccessControlType   = $permission.AccessControlType
            InheritanceFlags    = $permission.InheritanceFlags
            PropagationFlags    = $permission.PropagationFlags
            FileSystemRights    = $permission.FileSystemRights
        }
    }
    # 递归处理子文件夹(仅遍历文件夹,排除文件)
    foreach ($subFolder in Get-ChildItem -Path $folderPath -Directory) {
        Get-FolderPermissions -folderPath $subFolder.FullName
    }
}

# 收集所有权限并导出到CSV
Get-FolderPermissions -folderPath $rootFolder | Export-Csv -Path $outputFile -NoTypeInformation
Write-Host "权限已导出到 $outputFile"

关键改进点

  • 避免全局变量:函数直接返回每个权限对象,通过管道一次性收集,彻底解决作用域问题。
  • 高效对象创建:使用[PSCustomObject]替代New-Object PSObject,是PowerShell 3.0+更简洁、性能更好的写法。
  • 精准遍历:添加-Directory参数仅处理文件夹,避免原脚本中递归处理文件导致的潜在错误(若需要包含文件权限,可移除该参数)。
  • 性能优化:去掉+=数组拼接,避免频繁创建新数组的开销,尤其适合大量文件夹的场景。

备选修复方案(针对原脚本的最小修改)

如果你想保留原脚本结构,只需在函数内部明确引用全局数组,修改第24行:

$global:permissionsData += $permissionData

但这种写法仍存在数组拼接的性能问题,不推荐用于大规模文件夹场景。

内容的提问来源于stack exchange,提问作者Jovanni Orosco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 19:47:42