Ying Li at myITforum.com

PowerShell & System Center

PowerShell script to query ADSI and get user object propertites

Here is a PowerShell script to query ADSI and to get user account properties and report the results in excel. When I wrote this script, there are three huddles(trial and errors) I had to overcome which I added notes here to save you time.

$erroractionpreference = "SilentlyContinue"

$a = New-Object -comobject Excel.Application
$a.visible = $True

$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)

$c.Cells.Item(1,1) = "User"
$c.Cells.Item(1,2) = "UserName"
$c.Cells.Item(1,3) = "Home Directory"
$c.Cells.Item(1,4) = "Home Drive"
$c.Cells.Item(1,5) = "Membership"
$c.Cells.Item(1,6) = "Mail"
$c.Cells.Item(1,7) = "Account Disabled"
$c.Cells.Item(1,8) = "Report Time Stamp"

$d = $c.UsedRange
$d.Interior.ColorIndex = 19
$d.Font.ColorIndex = 11
$d.Font.Bold = $True

$intRow = 2

#You need to pay very close attention to the CN format(or syntax) and it has to be exact especially if you have a , in the cn, and if you are not sure, you could find them in ADSI veiwer (adsiedit.msc) or by doing this: $user=$ou.psbase.children | where {$_.givenname -like “bgates”}

($CNs = get-content C:\Myworkplace\CNs.txt

foreach ($cn in $CNs)
{
Function GetUserInfo
{
# Use DirectoryEntry object from .NET to bind to your AD, Replace with your exact Path here

$ou=new-object directoryservices.directoryentry("LDAP://ou=x,ou=y,dc=whatever1,dc=whatever2,dc=com")

# get the user object and since I am using PowerShell RC2 and I have to use psbase here – MOW has a blog # on this http://mow001.blogspot.com/2006/09/powershell-rc2-and-active-directory.html

$user=$ou.psbase.children.find("cn=$cn")

# Notice here I have to add .Tostring – I believe this has something to do with how the object in ADSI handled

$c.Cells.Item($intRow,1) = $user.name.Tostring()
$c.Cells.Item($intRow,2)  = $user.sAMAccountname.Tostring()
$c.Cells.Item($intRow,3)  = $user.homeDirectory.Tostring()
$c.Cells.Item($intRow,4)  = $user.homedrive.Tostring()
$c.Cells.Item($intRow,5)  = $user.memberof.Tostring()
$c.Cells.Item($intRow,6)  = $user.mail.Tostring()


if($user.psbase.invokeget('AccountDisabled') -eq $True)
{
$c.Cells.Item($intRow,7).Interior.ColorIndex = 3
$c.Cells.Item($intRow,7)  = "Disabled"
}
Else
{
$c.Cells.Item($intRow,7) = "Enabled"
}
}

GetUserInfo

$c.Cells.Item($intRow,8) = Get-date
 
$intRow = $intRow + 1
}
$d.EntireColumn.AutoFit()
cls

Posted: Aug 20 2007, 01:58 PM by yli628 | with 2 comment(s)
Filed under:

Comments

schmeckendeugler said:

Great Script. ..However, you've got a type-o there on the line ($CNs = get-content C:\Myworkplace\CNs.txt.

The leading Parenthesis I believe does not belong.

FYI I'm trying to hack this script to loop through an LDAP search of an OU (Rather than a txt file). I'll let you know how it goes... ;)

# November 7, 2008 10:37 AM

yli628 said:

Thanks!

# November 7, 2008 11:54 AM