Skip to content

Instantly share code, notes, and snippets.

@ayoubzulfiqar
Created July 11, 2025 07:21
Show Gist options
  • Save ayoubzulfiqar/4752e6072c931827e296f7e841bd0b71 to your computer and use it in GitHub Desktop.
Save ayoubzulfiqar/4752e6072c931827e296f7e841bd0b71 to your computer and use it in GitHub Desktop.
Make Error When Script Run To Error
# Function to play a sound file
function Play-ErrorSound {
param (
[Parameter(Mandatory=$true)]
[string]$SoundFilePath
)
# Check if the sound file exists
if (-not (Test-Path $SoundFilePath -PathType Leaf)) {
Write-Warning "Sound file not found: $SoundFilePath. Cannot play alert."
return # Exit the function gracefully
}
try {
# Create a Windows Media Player object
$wmp = New-Object -ComObject WMPlayer.OCX.7
$wmp.URL = $SoundFilePath
# Wait for the sound to load and play
# This will block the console until the sound finishes.
# For non-blocking, you'd need a separate thread or background job, which is more complex.
while ($wmp.playState -ne 1) { # 1 means stopped
Start-Sleep -Milliseconds 100
}
$wmp.controls.play()
# Wait for the sound to finish playing
while ($wmp.playState -ne 1) { # 1 means stopped
Start-Sleep -Milliseconds 100
}
# Release the COM object
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($wmp) | Out-Null
Remove-Variable wmp -ErrorAction SilentlyContinue # Use SilentlyContinue in case it's already removed
}
catch {
Write-Error "An error occurred while playing the sound: $($_.Exception.Message)"
}
}
# Function to run a command/script with an error alert
function Invoke-WithErrorAlert {
param (
[Parameter(Mandatory=$false)]
[string]$Command,
[Parameter(Mandatory=$false)]
[string]$ScriptToRun,
[Parameter(Mandatory=$true)]
[string]$SoundFilePath # Path to your custom error sound MP3
)
# Validate that either Command or ScriptToRun is provided
if ([string]::IsNullOrEmpty($Command) -and [string]::IsNullOrEmpty($ScriptToRun)) {
Write-Error "Either -Command or -ScriptToRun must be provided."
return
}
if (-not ([string]::IsNullOrEmpty($Command)) -and -not ([string]::IsNullOrEmpty($ScriptToRun))) {
Write-Error "Only one of -Command or -ScriptToRun can be provided."
return
}
Write-Host "Starting execution with error alert..."
$errorOccurred = $false
$exitCode = 0
$initialErrorCount = $Error.Count # Capture current error count
try {
if (-not ([string]::IsNullOrEmpty($Command))) {
# Execute the command
# Using Invoke-Expression for simplicity, but for complex commands or security,
# consider using Start-Process or direct execution with arguments.
Invoke-Expression $Command 2>$null # Redirect stderr to $null to avoid polluting output
$exitCode = $LASTEXITCODE
} elseif (-not ([string]::IsNullOrEmpty($ScriptToRun))) {
# Execute the PowerShell script
# Using '&' operator to run the script directly.
& $ScriptToRun
}
# Check for non-zero exit code (common for external executables indicating error)
if ($exitCode -ne 0) {
Write-Warning "Command exited with code: $exitCode. Assuming error."
$errorOccurred = $true
}
# Check for new PowerShell specific errors if a script was run
# Compare current error count to initial count
if ($Error.Count -gt $initialErrorCount) {
Write-Warning "PowerShell errors detected during script execution."
$errorOccurred = $true
}
# Also check $? for last command success/failure
if (-not $?) {
Write-Warning "`$? indicates last command failed."
$errorOccurred = $true
}
}
catch {
# Catch any terminating errors from the executed command/script
Write-Error "A terminating error occurred during execution: $($_.Exception.Message)"
$errorOccurred = $true
}
if ($errorOccurred) {
Write-Host "Error detected! Playing sound alert..."
# Call the sound playing function defined above
Play-ErrorSound -SoundFilePath $SoundFilePath
} else {
Write-Host "Script/Command completed successfully."
}
Write-Host "Execution finished."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment