0
參照當前對象我希望能夠提及$_
對象在catch塊從我在catch塊調用這樣的功能:來自不同範圍
function foo
{
$something = ((Get-Variable -Name "_" -Scope 1).Value).Exception.Message
Write-Host $something
}
我想在這樣的情況下使用此:
foo #write-host should print empty line
try {
throw
} catch {
foo #write-host should print $_.Exception.Message from this catch block
}
如何正確地做到這一點? 我的目標是避免每次在catch塊中使用它時將$_
作爲參數傳遞給foo
,並且當我調用foo
而不是在catch塊中時不打印任何內容。
我也試過這樣:
function foo
{
$something = (($ExecutionContext.SessionState.PSVariable.Get("_")).Value).Exception.Message
Write-Host $something
}
這似乎產生交互工作時,但不能啓動腳本時,我想要的結果。
有一個全局'$ error'變量。 '$ error [0]'保存遇到的最後一個錯誤。 –
它是全局的事實在調用「foo」不在catch塊中時會產生不想要的結果,在這種情況下,我不希望它返回它從上一個catch塊中保存的最後一個錯誤。 –
坦率地說,我會給'foo()'一個默認值爲'$ null'的參數,並在catch塊中調用'foo $ _'。僅當參數的類型爲[[Management.Automation.ErrorRecord]'時才輸出異常消息。 –