显然,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
尽管这可能会因为在某些情况下可能有效的事实而变得复杂。 - 使用自定义对象而不是计算属性。但这不是很好。
有什么想法吗?