我有多個try catch塊,它們都使用同一個catch塊。
try {
invoke-command -cn $host -Credential $cred -ScriptBlock {
param($name)
statement...
} -ArgumentList $name
} catch {
$formatstring = "{0} : {1}`n{2}`n"
" CategoryInfo : {3}`n"
" FullyQualifiedErrorId : {4}`n"
write-host ($formatstring)
exit 1
}
...
try {
another statement...
} catch {
$formatstring = "{0} : {1}`n{2}`n"
" CategoryInfo : {3}`n"
" FullyQualifiedErrorId : {4}`n"
write-host ($formatstring)
exit 1
}
我想問是否可以創建一個具有該catch塊的函式,以便我可以呼叫和使用該函式,而不是catch block多次撰寫相同的函式。
我在用poweshell 5
uj5u.com熱心網友回復:
catch需要一個文字 { ... }塊來跟隨它,但是在該塊內部,您可以自由呼叫可重用代碼,例如函式,或者在最簡單的情況下是腳本塊:
# Define a script block to use in multiple `catch` blocks.
$sb = {
"[$_]" # echo the error message
}
# Two simple sample try / catch statements:
try {
1 / 0
}
catch {
. $sb # `. <script-block>` invokes the block directly in the current scope
}
try {
Get-Item -NoSuchParam
}
catch {
. $sb
}
注意:.,點源運算子,用于直接在當前范圍內呼叫腳本塊,允許您直接修改該范圍的變數。這使得腳本塊的行為就好像它被直接用作catch黑色一樣。
相反,如果您想在子范圍內&執行腳本塊,請使用呼叫運算子。
uj5u.com熱心網友回復:
您可以創建一個可以使用Invocation ( call - &) Operator呼叫的ScriptBlock。
$callMe = {
$formatstring = "{0} : {1}`n{2}`n"
" CategoryInfo : {3}`n"
" FullyQualifiedErrorId : {4}`n"
Write-Host -Object $formatstring
exit 1
}
try {
Invoke-Command -ComputerName $host -Credential $cred -ScriptBlock {
param($name)
# statement...
} -ArgumentList $name -ErrorAction "Stop"
}
catch {
& $callMe
}
附帶說明一下,如果您發現自己重復代碼,您可能可以采取一些措施。我建議將$ErrorActionPreference設定為停止,或者添加一個-ErrorAction "Stop"以Invoke-Command確保引發終止錯誤。
- 最佳做法是在使用時
$ErrorActionPreference回退"Continue"。 - 我也相信您正在尋找使用
-f( format ) 運算子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/444131.html
標籤:视窗 电源外壳 powershell 远程处理
