Powershell: Get-ADUser Without Errors…

I do a lot of scripting of mass-user searches, server and Home Folder validations, etc., where I rely on the Powershell command “Get-ADUser” in my loops.  And this is one of those cases where Powershell is very forgiving; and as such, things like this can be done a handful of different ways.  Of course, some are better than others…

The shortest and easiest form of the command is often fine enough to get the job done, but not always the best in certain situations.  For instance, if you have an IF loop where you are going through an expected list of users (perhaps from an input file) and trying to retrieve a certain attribute for each, you might be inclined to initially write the loop line something like this:

Get-ADUser -Identity $loopUserId

…and this is fairly standard, of course.  In the resulting loop, it would return something like the standard set of attributes in this capture (using a manual query in my lab for this example)

 However, if you are like me, you might occasionally want to watch the output of your scripts while they run; and you prefer to send nice results to screen (as well as to the output logs) for easy debugging and, well, entertainment. 

And this is where the problem arises with the simple format of the command; you soon become annoyed by all the red error messages for the users that have gone missing since your input file was created, as in the case of this intentional search for a non-existent user:

…this is because by default, the Get-ADUser command will give you a nice set of results when it succeeds, but an ugly red message when there is no result.  Yuck.  This simply won’t do; we don’t want to have to panic as if there were an actual *error* every time we get an empty result on each query in the loop!

Instead, we wish to just get a silent, non-return when there are no results.  So, another way to write the same command so that you don’t get any error messages is by using the -Filter option, like this:

Get-ADUser -Filter {SamAccountName -eq $loopUserId}

In this manual example, you can see that the results are the same as if using the earlier format of the command when successful:

…But this time, we get a nice, quiet, non-result in the event of an empty response; as in the case of the same failed search:

Much better!

Now, you can watch your loop output while having a nice… calm… lunch….

 

 

2017-07-27T00:01:04+00:00 January 2nd, 2013|Uncategorized|

About the Author:

Jeremy is just a regular guy that likes to occasionally tell the world about stuff.