How can I write to standard error from PowerShell, or trap errors such that:
The best way in my opinion to trap errors in PowerShell would be to use the following:
$Error[0].Exception.GetType().FullName
Here is an example of how to use this properly. Basically test what you are trying to do in PowerShell with different scenarios in which your script will fail.
Here is a typical PowerShell error message:
PS C:\> Stop-Process -Name 'FakeProcess'
Stop-Process : Cannot find a process with the name "FakeProcess". Verify the process name and call the cmdlet again.
At line:1 char:1
+ Stop-Process -Name 'FakeProcess'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (FakeProcess:String) [Stop-Process], ProcessCommandException
+ FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.StopProcessCommand
Next you would get the exception of the error message:
PS C:\> $Error[0].Exception.GetType().FullName
Microsoft.PowerShell.Commands.ProcessCommandException
You would setup your code to catch the error message as follows:
Try
{
#-ErrorAction Stop is needed to go to catch statement on error
Get-Process -Name 'FakeProcess' -ErrorAction Stop
}
Catch [Microsoft.PowerShell.Commands.ProcessCommandException]
{
Write-Host "ERROR: Process Does Not Exist. Please Check Process Name"
}
Output would look like the following instead of the Powershell standard error in above example:
ERROR: Process Does Not Exist. Please Check Process Name
Lastly, you can also use multiple catch blocks to handle multiple errors in your code. You can also include a "blanket" catch block to catch all errors you haven't handled. Example:
Try
{
Get-Process -Name 'FakeProcess' -ErrorAction Stop
}
Catch [Microsoft.PowerShell.Commands.ProcessCommandException]
{
Write-Host "ERROR: Process Does Not Exist. Please Check Process Name"
}
Catch [System.Exception]
{
Write-Host "ERROR: Some Error Message Here!"
}
Catch
{
Write-Host "ERROR: I am a blanket catch to handle all unspecified errors you aren't handling yet!"
}