3

显然,Powershell 中有一个设计怪癖,可以防止在计算属性表达式中引发的异常冒泡。所发生的只是计算属性的值最终为空。

function Get-KBValue() {
    # Some Logic here that can throw an exception
}

....

Get-ChildItem C:\Test | 
    Select-Object Name, CreationTime,  @{Name="Kbytes"; Expression={ Get-KBValue }}

如果Get-KBValue函数抛出异常,则Kbytes属性的值被设置为$null并且脚本继续。

可能的解决方法:

  • 在表达式中使用try/catch{break}(@CB 建议)
  • 之后进行验证。$null尽管这可能会因为在某些情况下可能有效的事实而变得复杂。
  • 使用自定义对象而不是计算属性。但这不是很好。

有什么想法吗?

4

1 回答 1

5

在表达式中使用 try/cacth 可以帮助您吗?

10..0 | SELECT @{n="Value";e={ try { 10/$_ } catch { "error: $_" }}}
于 2013-05-10T12:37:17.363 回答