IoanPopovici
5/17/2016 - 8:05 AM

Powershell Error Handling without Try/Catch

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!"
    }