Skip to content

Instantly share code, notes, and snippets.

@Ioan-Popovici
Created May 17, 2016 08:05
Show Gist options
  • Save Ioan-Popovici/0fd3b48df71effc4e1850098ed0fce93 to your computer and use it in GitHub Desktop.
Save Ioan-Popovici/0fd3b48df71effc4e1850098ed0fce93 to your computer and use it in GitHub Desktop.
Powershell Error Handling without Try/Catch
## Powershell Error Handling without Try/Catch
# Declaring module Paths
$OSDScriptsPath1 = "C:\Windows\System32\WindowsPowerShell\v1.0\Modules\OSDScripts"
$OSDScriptsPath2 = "C:\Program Files\WindowsPowerShell\Modules\OSDScripts"
# Removing module using SilentlyContinue parameter and Err variable to store execution errors
Remove-Item -Path $OSDScriptsPath1 -Recurse -Force -ErrorAction SilentlyContinue -ErrorVariable +Err
Remove-Item -Path $OSDScriptsPath2 -Recurse -Force -ErrorAction SilentlyContinue -ErrorVariable +Err
# Check if first error does not contain "Cannot find path" write error to console ​
If ($Err[0] -and $Err[0].Exception -notmatch "Cannot find path"){
Write-Host "Delete $OSDScriptsPath1 -Failed with Error: $Err[0].Exception"
# If no errors occured (except the "Cannot find path") write that the delete operation was succesful
} Else {
Write-Host "Delete $OSDScriptsPath1 - Successful!"
}
# Check if second error does not contain "Cannot find path" write error to console ​
If ($Err[1] -and $Err[1].Exception -notmatch "Cannot find path"){
Write-Host "Delete $OSDScriptsPath2 -Failed with Error: $Err[1].Exception"
# If no errors occured (except the "Cannot find path") write that the delete operation was succesful
} Else {
Write-Host "Delete $OSDScriptsPath2 - Successful!"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment