Last active
May 24, 2016 08:02
-
-
Save Ioan-Popovici/72331a4b78a9873573bbb79d194124e7 to your computer and use it in GitHub Desktop.
Powershell Error Handling with Try/Catch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Powershell Error Handling with Try/Catch | |
| |
# Declaring module Paths | |
$OSDScriptsPath1 = "C:\Windows\System32\WindowsPowerShell\v1.0\Modules\OSDScripts" | |
$OSDScriptsPath2 = "C:\Program Files\WindowsPowerShell\Modules\OSDScripts" | |
| |
# Removing module using -ErrorAction Stop parameter and Err variable to store execution errors | |
# We use -ErrorAction Stop in order to treat all errors as Terminating Errors | |
Try { | |
Remove-Item -Path $OSDScriptsPath1 -Recurse -Force -ErrorAction Stop -ErrorVariable +Err | |
Write-Host "Delete $OSDScriptsPath1 - Successful!" | |
} | |
# Catch Item Not Found Exception error | |
Catch [System.Management.Automation.ItemNotFoundException] | |
{ | |
Write-Host "$OSDScriptsPath1 - Not Found!" -ForegroundColor Green | |
} | |
# Catch all other errors | |
Catch { | |
Write-Host "Delete $OSDScriptsPath1 - Failed!" | |
Write-Host "Failed with Error: "$Err | |
} | |
# Removing module using -ErrorAction Stop parameter and Err variable to store execution errors | |
# We use -ErrorAction Stop in order to treat all errors as Terminating Errors | |
Try { | |
Remove-Item -Path $OSDScriptsPath2 -Recurse -Force -ErrorAction Stop -ErrorVariable +Err | |
Write-Host "Delete $OSDScriptsPath2 - Successful!" | |
} | |
# Catch Item Not Found Exception error | |
Catch [System.Management.Automation.ItemNotFoundException] | |
{ | |
Write-Host "$OSDScriptsPath2 - Not Found!" -ForegroundColor Green | |
} | |
# Catch all other errors | |
Catch { | |
Write-Host "Delete $OSDScriptsPath2 - Failed!" | |
Write-Host "Failed with Error: "$Err | |
} | |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment