PowerShell调用Get-Process获取进程版本信息无法捕获异常问题
问题根源
PowerShell 的 try/catch 逻辑默认仅能捕获终止错误(Terminating Error),而Get-Process -FileVersionInfo获取受保护进程(比如csrss、Idle等系统进程)属性失败时抛出的是非终止错误(Non-terminating Error),这类错误默认仅会输出到错误流,不会中断管道执行,也不会触发catch块的逻辑,因此控制台仍然会输出红色错误提示。
解决方法
方案1:需要捕获异常做后续处理
给Get-Process命令加上-ErrorAction Stop参数,将该命令抛出的所有错误提升为终止错误,即可被对应的catch块捕获,修改后的代码如下:
try { Get-Process -FileVersionInfo -ErrorAction Stop | select -Unique | Select-Object * | Format-Table -Property OriginalFilename, FileName, InternalName, ProductName, CompanyName, FileVersion -Wrap > C:\Users\user\OneDrive\Desktop\final.txt } catch [Microsoft.PowerShell.Commands.ProcessCommandException] { Write-Verbose "Catch all" -Verbose }
方案2:无需处理异常,仅屏蔽错误输出
如果这类获取失败属于预期内的情况,不需要额外处理,直接给Get-Process加上-ErrorAction SilentlyContinue参数即可屏蔽所有错误输出,不需要写catch块:
Get-Process -FileVersionInfo -ErrorAction SilentlyContinue | select -Unique | Select-Object * | Format-Table -Property OriginalFilename, FileName, InternalName, ProductName, CompanyName, FileVersion -Wrap > C:\Users\user\OneDrive\Desktop\final.txt
内容的提问来源于stack exchange,提问作者Nikolay Totev Kolev
相关产品推荐
相关产品推荐

