我使用的是由别人编写的Weird-Cmd。此命令在数据库中搜索things,并接受其-Filter的某些参数。
如果我传递一个假的过滤器参数,它会返回一条消息,告诉我没有这样的过滤器参数。
该消息在信息流(6)上报告。如何在try/catch中调用此cmdlet并捕获信息流中报告的此错误。
我尝试重定向流,但结果是PowerShell除了输出/成功之外没有重定向。
我没有访问Weird-Cmd的权限,所以无法更改它。我只限于PowerShell 5.1。
这是我得到的信息:
System.Management.Automation.ParentContainsErrorRecordException: Cannot bind parameter 'Filter' to the target. Exception setting "Filter": ""BogusProp" is not a recognized filterable property. Valid property names are: Prop1, Prop2,...."发布于 2022-06-17 22:32:15
假设Weird-Cmd是cmdlet或https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Functions_Advanced函数或脚本,则使用参数捕获信息流的输出:
try {
Weird-Cmd -InformationVariable inf # Note: NO "$" before "inf"
if ($inf) { throw $inf }
} catch {
# ... handle the exception.
}否则--包括通过脚本块({ ... })调用{ ... },使用重定向6>将信息流重定向到临时文件
try {
Weird-Cmd 6>($tempFile = New-TemporaryFile)
$inf = (Get-Content -ErrorAction Ignore -Raw $tempFile)
$tempFile | Remove-Item -ErrorAction Ignore
if ($inf) { throw $inf }
} catch {
# ... handle the exception.
}注意:如果您只是想将信息流内容中继为一个不终止的错误,请使用Write-Error cmdlet,而不是使用带有catch的throw或从catch块内部:
Write-Error $infzett42指出,在内存中有一种替代6>$someFile的方法,即将信息流(6)与6>&1合并到成功输出流(1)中,并过滤出信息流输出对象的类型System.Management.Automation.InformationRecord --这是假定Weird-Cmd没有报告终止错误:
$inf = Weird-Cmd 6>&1 |
Where-Object { $_ -is [System.Management.Automation.InformationRecord] }尽管如此,如果有一种方法可以直接在变量中捕获特定流的输出,而不是按照:6>variable:inf这样的方式使用文件,那就更好了。
这一潜在的未来增强是GitHub问题#4332的主题。
https://stackoverflow.com/questions/72665307
复制相似问题