复杂PowerShell命令中ErrorAction参数的正确放置位置咨询
PowerShell管道命令中-ErrorAction参数的正确放置位置
你的问题核心是:这条管道命令里有三个可能抛出错误的cmdlet——Get-ChildItem、Set-ItemProperty,还有嵌套在Set-ItemProperty参数里的Get-ItemProperty,只在某一个位置加参数没用,得给每个可能报错的cmdlet单独添加-ErrorAction 'SilentlyContinue'(可简写为-EA 0)。
从错误日志能明确看到三类报错场景:
Get-ChildItem访问系统目录(如System Volume Information)时被拒绝Set-ItemProperty修改被占用文件(如pagefile.sys)或无权限文件时报错- 嵌套的
Get-ItemProperty读取无法访问的文件属性时也会抛出错误
正确的参数添加位置
- 给
Get-ChildItem添加:直接追加在它的参数列表末尾,跳过无权限访问的目录/文件,避免遍历阶段就报错 - 给嵌套的
Get-ItemProperty添加:在它的参数里加入,避免读取属性时报错导致整个表达式中断 - 给
Set-ItemProperty添加:追加在它的参数列表末尾,跳过无法修改属性的文件
修改后的完整脚本
param($Computer, $Drive) $DrivePath = $Drive + ":\" Get-ChildItem $DrivePath -Recurse -Force -ErrorAction SilentlyContinue | ForEach-Object { $currentAttrs = Get-ItemProperty $_.FullName -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Attributes -ErrorAction SilentlyContinue if ($null -ne $currentAttrs) { $newAttrs = ($currentAttrs -band ([io.fileattributes]::Hidden + [io.fileattributes]::ReadOnly)) + [io.fileattributes]::Normal + [io.fileattributes]::System Set-ItemProperty -Path $_.FullName -Name Attributes -Value $newAttrs -ErrorAction SilentlyContinue } }
额外说明
- 把单行命令拆成多行是为了提升可读性,不影响功能执行
- 增加了
$null判断,避免Get-ItemProperty返回空值时后续属性计算报错 -ErrorAction SilentlyContinue会屏蔽错误输出,但不会中断脚本的遍历流程
内容的提问来源于stack exchange,提问作者CityguyUSA
相关产品推荐
相关产品推荐

