PowerShell脚本报错:[PSObject]不含'op_Addition'方法,求排查
问题原因
错误出在递归函数Get-DirectoriesToDepth中对$results变量的作用域处理。PowerShell默认函数内的变量为局部作用域,你在函数外初始化的$results = @()是全局变量,但函数里直接写$results += ...时,PowerShell会创建一个同名的局部变量,初始值为$null。当尝试对$null执行+=操作添加[pscustomobject]时,就会抛出[System.Management.Automation.PSObject] doesn't contain a method named 'op_Addition'错误——因为$null没有加法操作方法。
另外原脚本的权限判断逻辑存在漏洞:仅通过正则匹配SID前缀无法准确区分AD用户和组(两者SID均以S-1-5-21开头),可能导致误判。
修复方案
推荐采用函数返回结果的方式(符合PowerShell最佳实践,避免全局变量依赖),同时优化权限判断逻辑:
修改后的完整脚本
# 目标根目录 $basePath = "C:\PfadZuIhremVerzeichnis" # CSV导出路径 $csvExportPath = "C:\PfadZumSpeichern\DirectoriesWithGroupOnlyPermissions.csv" # 判断目录是否仅包含组权限 function HasOnlyGroupPermissions { param ([string]$path) $acl = Get-Acl -Path $path foreach ($access in $acl.Access) { # 仅检查非继承的直接权限 if (-not $access.IsInherited) { # 解析SID并判断账户类型 $sid = [System.Security.Principal.SecurityIdentifier]$access.IdentityReference.Value $accountType = $sid.AccountType # 存在用户/机器账户权限则返回false if ($accountType -eq 'User' -or $accountType -eq 'Machine') { return $false } } } return $true } # 递归获取指定深度内的目录 function Get-DirectoriesToDepth { param ( [string]$rootPath, [int]$maxDepth, [int]$currentDepth = 0 ) # 达到最大深度时停止递归 if ($currentDepth -ge $maxDepth) { return } # 获取当前目录下的子目录 $childDirs = Get-ChildItem -Path $rootPath -Directory -ErrorAction SilentlyContinue foreach ($dir in $childDirs) { # 符合条件则输出对象 if (HasOnlyGroupPermissions -path $dir.FullName) { [pscustomobject]@{ Path = $dir.FullName } } # 递归处理下一级目录 Get-DirectoriesToDepth -rootPath $dir.FullName -maxDepth $maxDepth -currentDepth ($currentDepth + 1) } } # 收集结果并导出CSV $results = Get-DirectoriesToDepth -rootPath $basePath -maxDepth 2 $results | Export-Csv -Path $csvExportPath -NoTypeInformation -Encoding UTF8 Write-Host "仅含组权限的目录已导出至:$csvExportPath"
关键修改点
- 作用域优化:让递归函数直接输出符合条件的对象,最后统一收集结果,彻底避免全局变量的作用域问题。
- 权限判断优化:通过
SecurityIdentifier的AccountType属性准确区分用户/组账户,替代原有的正则匹配逻辑,避免误判。
内容的提问来源于stack exchange,提问作者Luke Bro
相关产品推荐
相关产品推荐

