PS: Error Handling

PS: Error Handling

Error handling is important when making a script that will be handed over to end users who do not need to know the mechanics of the code. This is a rather simple explanation on how to go about it in your Power Shell scripts.

So we are going to use the following structure

$ErrorActionPreference = "Stop"
Try # Execute the command
{
Restart-Computer
}
Catch # Catch the error
{
# Display an error message
Write-Host 'Unable to Run Command Due to Error' # Output error string to console
write-host ($_.Exception.Message | Out-String) -ForegroundColor Red
}

 

Advertisements