2
$player = New-Object System.Media.SoundPlayer "C:\Error-Sound.wav"
$ErrorActionPreference = "$player.Play()"

my code is not working i want this when it face any error in the whole Powershell Script to call function any help ?

1
  • You are probably looking for $player.PlaySync() on a catch statement. Commented Jan 4, 2022 at 19:08

3 Answers 3

4

You're probably looking to play a sound whenever the script fails, if that's the case then:

$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
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is Excellent 👏👏
3

For script-wide error handling, use the trap statement, as described in the conceptual about_Trap help topic.

Note that a trap only traps terminating errors by default, so that a non-terminating error such as Get-ChildItem NoSuchir would not be caught.

To also trap non-terminating errors, set $ErrorActionPreference = 'Stop' (the $ErrorActionPreference preference variable only accepts predefined values denoting an abstract action to perform, such as Stop). This promotes non-terminating to (script-)terminating errors, which trap then traps.

For more fine-grained handling of terminating errors, consider use of try / catch/ finally statements, discussed in about_Try_Catch_Finally.

See this answer for examples of both.

A simple example for your use case:

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

Santiago's helpful answer shows you an equivalent try / catch solution.

Comments

0

The $ErrorActionPreference variable takes one of the ActionPreference enumeration values: SilentlyContinue, Stop, Continue, Inquire, Ignore, Suspend, or Break.

Post some of your code but unless your $player.play is one of the above actions then you're not using this correctly.

# 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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.