1

I have a script which are going to run on several local computers, but I haven't done any errorhandling in it. I have not done any errorhandling in powershell at all, so i'm a total noob here. I read something about it, but honestly I am just looking for an quick and easy answer..

Q: Is there something like a try/catch, as little code as possible to not make the script heavy weight?

2 Answers 2

2

Yes, try/catch/finally is available in Powershell v2:

Try{
<main code here>
}
Catch{
write-host $_ #Using the reserved $_ variable which should contain the error string
}
Finally{
<clean up code here - will execute regardless>
}

If you're constrained to use Powershell v1 then you will have to use the trap construct.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm using powershell v2. What I did with this code was paste all my script into the Try{}, and leave the catch unspecified so that it would catch all exceptions,(I thought), when I on purpose wrote a new line in the try{} "sdgsf" I got the error message specified in the catch{}, but when I do something like: "$username = gc env:usernamejghc" (I wrote jiberish at the end of the command) I get error: Get-Content : Cannot find path 'Env:\usernamejghc' because it does not exist. I'm going to read some more on the subject, meanwhile: Any suggestions that will handle this error?
You mean $env:usernamejghc, I guess. The message exactly tells you what happens.
Yes, but why won't the catch block "catch" it? If this error escape it, I suppose other can too?
0

Powershell 2.0 has try, catch and finally. See http://technet.microsoft.com/en-us/library/dd315350.aspx You can also do a more command-line oriented variation of error handling with error trapping like here: http://www.informit.com/articles/article.aspx?p=729515&seqNum=5

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.