$player = New-Object System.Media.SoundPlayer "C:\Error-Sound.wav"
$ErrorActionPreference = "$player.Play()"
我的代碼不起作用我想要這個當它在整個 Powershell 腳本中遇到任何錯誤來呼叫函式時有什么幫助?
uj5u.com熱心網友回復:
您可能希望在腳本失敗時播放聲音,如果是這樣的話:
$ErrorActionPreference = 'Stop'
$player = New-Object System.Media.SoundPlayer "C:\Error-Sound.wav"
try
{
# Script do something here
}
catch
{
$player.PlaySync() # Play a sound if Error
Write-Warning $_.Exception.Message # Display exception in the console
}
uj5u.com熱心網友回復:
對于腳本范圍的錯誤處理,請使用trap陳述句,如概念about_Trap幫助主題中所述。
需要注意的是一個trap只有陷阱終止錯誤的默認,因此如非終止錯誤Get-ChildItem NoSuchir就不會被抓到。
要同時捕獲非終止錯誤,請設定$ErrorActionPreference = 'Stop'($ErrorActionPreference首選項變數僅接受表示要執行的抽象操作的預定義值,例如Stop)。這將非終止錯誤提升為(腳本)終止錯誤,trap然后陷阱。
欲了解更多細粒度終止錯誤的處理,應考慮使用 try/ catch/finally報表,討論about_Try_Catch_Finally。
有關兩者的示例,請參見此答案。
您的用例的一個簡單示例:
trap {
(New-Object System.Media.SoundPlayer "C:\Error-Sound.wav").PlaySync()
# `break` causes the script to abort.
# `continue` does too, but without issuing the error
# Using neither continues execution.
break
}
$ErrorActionPreference = 'Stop'
# Provoke an error
Get-ChildItem NoSuchDir
圣地亞哥的有用答案向您展示了一個等效try/catch解決方案。
uj5u.com熱心網友回復:
$ ErrorActionPreference變數采用 ActionPreference 列舉值之一:SilentlyContinue、Stop、Continue、Inquire、Ignore、Suspend 或 Break。
發布您的一些代碼,但除非您的 $player.play 是上述操作之一,否則您沒有正確使用它。
# Change the ErrorActionPreference to 'Continue'
$ErrorActionPreference = 'Continue'
# Generate a non-terminating error and continue processing the script.
Write-Error -Message 'Test Error' ; Write-Host 'Hello World'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/405524.html
標籤:
上一篇:了解Powershell:示例-將JSON轉換為CSV
下一篇:AD用戶腳本沒有輸出
