PS Tip: PowerShell Catches

In this example I want to check if a list of users samAccountNames returns a list of matching displaynames. In the event that the user is not found I don’t want a system error displayed, I want a custom error message. This is done using a Try & Catch statement, the Try element being the test and the Catch element what I want the custom error to be.

$users = get-content C:\team-members.txt
Foreach ($user in $users) {
try {
(get-aduser $user).Name
}
catch {“$user not found in AD!” #this text will replace the system error output
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s