PowerShell: New-PSDrive error handling

powershell

I have a script where I mount with the command "New-PSDrive" a network drive. Now, since the script is running as a "cronjob" on a server I want to have some error detection. If for any reason the command New-PSDrive fails the script should stop executing and notify that something went wrong. I have the following code:

Try {
    New-PSDrive -Name A -PSProvider FileSystem -Root \\server\share
} Catch {
    ... handle error case ...
}
... other code ...

For testing reasons I specified a wrong server name and I get the following error "New-PSDrive : Drive root "\wrongserver\share" does not exist or it's not a folder". Which is OK since the server does not exists. But the script does not go into the Catch clause and stop. It happily continues to run and ends up in a mess since no drive is mounted 🙂

So my question, why? Is there any difference in Exception handling in PowerShell? I should also note that I'm a noob in PowerShell scripting.

Bye,
Martin

Best Answer

There are two types of errors in Powershell, terminating errors and non-terminating errors. Check out the help for about_try_catch_finally for more info.

If I try this

try
{
jimjim-cmdlet
}
catch
{
"It's a jimjim error!"
}

the nonsense cmdlet will generate a terminating error which will be caught by the catch block.

The code you are running is not throwing a terminating error, so execution throws the non-terminating error and continues after the catch block.

Also see this page, http://powershell.com/cs/forums/p/521/703.aspx, for more information.

I am still a little fuzzy on when exactly a terminating error is thrown as opposed to a non-terminating error (perhaps more knowledgable folks can help out).