$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 ?
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
}
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.
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'
$player.PlaySync()on acatchstatement.