Powershell Error recovery

2

First a confession, I am still quite green with powershell. Anyway I have a powershell script, very similar to PowerShell Script to Loop Over All Users in a Group

It has been working fine (the script looks for members of a group and sets an AD attribute etc. It has been working fine for some time and about 2500 users processed but recently it failed) format-default : The following exception occurred while retrieving member "PSComputerName": "Unknown error (0x80005000)"

There is one user which causes the error. My question is how do I get powershell to trap this error\ignore it and carry on working?

Thanks

powershell
asked on Server Fault Aug 15, 2012 by Alistair • edited Apr 13, 2017 by Community

1 Answer

2

No sin in being green in a technology!

If you just want to completely ignore the error and move on you can add this at the top of your code:

$ErrorActionPreference = SilentlyContinue

No exceptions will be thrown and execution will continue at the next statement. It can, however, be fraught with peril. In simple scripts with few statements it can suffice. In larger contexts is can have detrimental results.

It's usually better to trap the exception and handle it, in which case you will want to look into using a try / catch block. This will allow you to try a bit of code and if an exception is thrown catch it and do something about the error.

The Scripting Guy has pretty good posts for Powershell:

Try / Catch / Finally in Powershell

Use $ErrorActionPreference in Powershell

answered on Server Fault Aug 15, 2012 by squillman

User contributions licensed under CC BY-SA 3.0