Tuesday, March 5, 2013

PowerShell AD User Search

Had a buddy ask me for a quick PowerShell script the other day and I was happy to oblige, as I rarely get to write PowerShell these days and I really enjoy it. So without further adieu, here is a quick and dirty script that takes a CSV file with first names, middle initials, and last names, then spits out a simple text file of exact matches in AD. Great for environments where only a few users had accounts in the past and now for whatever reason you want to give everyone an account or something. It's not the most efficient or flexible script, but it might come in handy for someone.


#Bill Gurling
#March 2013
#http://blog.bill-gurling.com
#@onethirtyone

#######IMPORTANT########################################################################################
#users.csv must be in the same directory as this file and must be in the following format:
#fn,mi,ln
#Bill,E,Gurling
#John,F,Bob
#Chris,L,Chisman
#Jimmy,E,Smith
#
#Also, you must have the active directory module for windows powershell installed, instructions 
#here: http://blogs.technet.com/b/heyscriptingguy/archive/2011/08/29/use-active-directory-cmdlets-with-powershell-to-find-users.aspx



Import-Module activedirectory
$users = Import-Csv users.csv
$notfound = @()
if (test-path user_lookup_results.txt)
{
remove-item user_lookup_results.txt
New-Item user_lookup_results.txt -type file
}
else {New-Item user_lookup_results.txt -type file}
add-content user_lookup_results.txt "Users Found"
add-content user_lookup_results.txt "------------"
add-content user_lookup_results.txt ""
foreach ($user in $users)
{
$firstname = $user.fn
$initial = $user.mi
$lastname = $user.ln
$command = "Get-ADuser -filter {GivenName -eq `"$firstname`" -and Surname -eq `"$lastname`" -and initials -eq `"$initial`"}"
$adacct = iex $command
if ($adacct -ne $null)
{
$username = $adacct.samaccountname
add-content user_lookup_results.txt "Username: $username"
add-content user_lookup_results.txt "Name: $firstname $initial $lastname"
add-content user_lookup_results.txt ""
}
else {$notfound += "$firstname $initial $lastname"}
}

add-content user_lookup_results.txt ""
add-content user_lookup_results.txt "Names Not Found"
add-content user_lookup_results.txt "------------"
add-content user_lookup_results.txt ""

foreach ($name in $notfound) {add-content user_lookup_results.txt $name}