這個問題在這里已經有了答案: 如何將多個引數傳遞給 PowerShell 中的函式? (15 個回答) 昨天關門。
我有一個包含以下日志記錄功能的 PowerShell 腳本:
function LogError([string] $message, $exception = $null) {…}
在 try-catch 塊中,當發生例外時,我呼叫該日志記錄函式,如下所示:
catch { LogError("…", $_.Exception) }
在LogError函式中,第二個引數總是$null. 為什么?
我找不到任何可以解釋為什么我不能$_.Exception在函式呼叫中使用或我應該使用的檔案。
uj5u.com熱心網友回復:
Powershell 函式引數不使用括號/逗號格式傳遞。
那很不好
LogError("…", $_.Exception)
Powershell 將其作為單個陣列引數。這實際上是一樣的LogError -Message ("...",$_.Exception)
那沒問題
LogError '…' $_.Exception
那是最好的
LogError -message '...' -exception $_.Exception
完整的作業示例
function LogError([string] $message, $exception = $null) {
Write-Host $message
$exception | Out-String | Write-Host -ForegroundColor red
}
try {
throw 'Noooo !!!!'
}
catch {
LogError -message 'oops' -exception $_.Exception
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/495217.html
標籤:电源外壳 powershell-7.0 PowerShell-7.2
