PowerShell: New-PSDrive error handling

Posted by mazebuhu on Server Fault See other posts from Server Fault or by mazebuhu
Published on 2011-02-25T14:18:48Z Indexed on 2011/02/25 15:27 UTC
Read the original article Hit count: 848

Hello,

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

© Server Fault or respective owner

Related posts about powershell

Related posts about newbie