Last active
May 24, 2016 08:01
-
-
Save Ioan-Popovici/276d86847568a1d91e5cce7164fcd66e to your computer and use it in GitHub Desktop.
Powershell Error Handling with Try/Catch, using multiple commands or variables
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, using multiple commands or variables | |
| |
# Declaring module Paths as array | |
$OSDScriptsPaths =@( | |
"C:\Windows\System32\WindowsPowerShell\v1.0\Modules\OSDScripts", | |
"C:\Program Files\WindowsPowerShell\Modules\OSDScripts" | |
) | |
# Parse OSDScriptsPaths array and for each item try to remove the 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 | |
ForEach ($Path in $OSDScriptsPaths) { | |
Try { | |
Remove-Item -Path $Path -Recurse -Force -ErrorAction Stop -ErrorVariable +Err | |
Write-Host "Delete $Path - Successful!" | |
} | |
# Catch Item Not Found Exception error | |
Catch [System.Management.Automation.ItemNotFoundException] | |
{ | |
Write-Host "$Path - Not Found!" -ForegroundColor Green | |
} | |
# Catch all other errors | |
Catch { | |
Write-Host "Delete $Path - 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