问题
Apparently there is a by design quirk in Powershell that prevents exceptions that are thrown inside a Calculated Property Expression from bubbling up. All that happens is the value of the Calculated Property ends up being null.
function Get-KBValue() {
# Some Logic here that can throw an exception
}
....
Get-ChildItem C:\Test |
Select-Object Name, CreationTime, @{Name="Kbytes"; Expression={ Get-KBValue }}
If the Get-KBValue
function throws an exception then the value of the Kbytes
property is set to $null
and the script continues.
Possible workarounds:
- Use
try/catch{break}
within the Expression (Suggested by @C.B.) - Validate afterwards. Although this might be complicated by the fact that
$null
could be valid in some cases. - Use a custom object instead of a calculated property. But this is not as nice.
Any thoughts?
回答1:
Use a try/cacth in expression can help you?
10..0 | SELECT @{n="Value";e={ try { 10/$_ } catch { "error: $_" }}}
来源:https://stackoverflow.com/questions/16482316/calculated-properties-do-not-throw-exceptions-in-powershell-what-are-the-workar