Tuesday, November 19, 2019

Try Catch Errors with PowerShell

TRY AND CATCH BLOCK


With PowerShell when using <TRY> block to define a section of the script, it will store error within $error default variable. In  the example below, we will take advantage of default behavior to capture the error. after intentionally generating it.

# Try Catch Errors


Try {

   $user = "Rambo"
   get-adUser $user -ea stop

}

Catch {

    Write-Host 'Error FOUND:'`n -f white -b blue
    Write-Host "Message: ($($_.Exception.Message))" -f Cyan -b DarkBlue

}


Here is template for same
try
{
      Do Something  
}
Catch
{
      Write-Warning 'Error has occoured'
      Write-host 'Problem FOUND: $($PSItem.ToString())' -f red -b White
      Write-Host $_.Exception.Message -ForegroundColor red
     
}




Casey DeDeal
Azure Certified Solutions Architect
AWS Certified Cloud Practitioner

https://msazure365.blogspot.com
https://simplepowershell.blogspot.com
https://twitter.com/Message_Talk






Connect-Azure-PowerShell if there is no existing Connection.

By Using MsolService to connect to Azure PowerShell, could be annoying time to time if unable to validate existing connection. The simpl...