如何在 PowerShell 中使用 ErrorAction 引數?
與 ErrorActionPreference 變數類似,ErrorAction 引數的工作方式也類似。ErrorAction 引數在高階函式和 PowerShell 中的大多數內建 cmdlet 中都受支援。它用於將非終止錯誤轉換為終止錯誤,然後您可以使用 try/catch 塊來處理它們。
支援的值和示例:
Continue - 這是 ErrorAction 引數的預設值,將顯示錯誤,並且管道中列出的命令將繼續執行。
Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist -ErrorAction Continue Write-Host "`nHello World" -BackgroundColor DarkGreen
輸出
Get-WmiObject : The RPC server is unavailable. At line:1 char:1 + Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist -ErrorA ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMExcept ion + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands .GetWmiObjectCommand Hello World
Stop - 錯誤訊息將停止顯示,並且管道中用於執行的命令將不會執行。以下示例將沒有輸出。
示例
PS C:\WINDOWS\system32>>> Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist -ErrorAction Stop Write-Host "`nHello World" -BackgroundColor DarkGreen
SilentlyContinue - 不會顯示錯誤訊息,指令碼將執行管道命令。
示例
Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist - ErrorAction SilentlyContinue Write-Host "`nHello World" -BackgroundColor DarkGreen
輸出
PS C:\WINDOWS\system32>>> Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist -ErrorAction SilentlyContinue Write-Host "`nHello World" -BackgroundColor DarkGreen Hello World
Ignore - Ignore 值與 Silentlycontinue 相同,除了錯誤輸出不會儲存到 $Error 變數中。
Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist -ErrorAction Ignore Write-Host "`nHello World" -BackgroundColor DarkGreen Hello World
現在檢查錯誤變數。您在以下示例中可以看到,它不包含任何錯誤資料,而在 SilentlyContinue 值中,它儲存了錯誤輸出。
PS C:\WINDOWS\system32>>> $Error
Inquire - 當由於 cmdlet 發生錯誤時,此選項會為使用者提供以下選擇並提示採取適當的操作。
Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist - ErrorAction Inquire Write-Host "`nHello World" -BackgroundColor DarkGreen
輸出
Confirm The RPC server is unavailable. [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is " Y"):
如果您選擇 Yes/YestoAll,則會顯示錯誤訊息,對於 Halt 和 suspend,則不會顯示錯誤。
Suspend - 此值用於 PowerShell 工作流。工作流將暫停以調查錯誤,然後可以恢復工作流。
廣告