Flexing your Powershell: Getting a count of computer by OU

Today I needed to determine the number of computers in active directory for a client based on their location. Luckily, this client has their OU’s structured to Region\Country\City, but all I had was a list of the computers and their Distinguished Names. Since this puts the workstation name first, then goes city/country/region, this was challenging to split in excel and group up.

I spent awhile drafting the below script, which will enumerate the OU’s, then go into each and count the total number of computers, the number of disabled computer, the number of disabled computers, then export it to a csv. In my case, I scoped it specifically to the OU that contained only computers, but this can be expanded as needed.

##define csv to export to
$csvfile = "C:\temp\exports\pc-count-by-ou.csv"


##get all OU's under specified OU
$OUlist = get-adorganizationalunit -filter * -searchbase "OU= Computers,DC=yourdomain,DC=com" -Properties canonicalname | select distinguishedname, canonicalname 

##iterate through each OU
foreach ($ou in $oulist){

##get OU CN
$readableOU = $ou.canonicalname
##get OU DN
$scriptOU = $ou.distinguishedname

##Count all pc's in OU and store in a variable
$totalOUPCcount = get-adcomputer -filter * -searchbase "$scriptou" -searchscope OneLevel| measure-object
$totaloupccountnumber = $totalOUPCcount.Count

##Count all disabled pc's in OU and store in a variable
$disabledpccount = get-adcomputer -filter {enabled -eq $False} -searchbase "$scriptou" -searchscope OneLevel | measure-object
$disabledpccountnumber = $disabledpccount.Count

##Count all enabled pc's in OU and store in a variable
$enabledpccount = get-adcomputer -filter {enabled -eq $True} -searchbase "$scriptou" -searchscope OneLevel | measure-object
$enabledpccountnumber = $enabledpccount.Count

##line to write with results 
$csvlog = "$readableOU; $scriptOU; $totaloupccountnumber; $disabledpccountnumber; $enabledpccountnumber"
##print to working window
write-host "$csvlog"
##append to csv
$csvlog | out-file $csvfile -append 
}

Note, this does not put headers in, which I may go back and update later, but the csv can then be opened with excel, and using the “text to columns” feature with semicolon as the delimiter, gives us some usable results. (I’ve added the headers manually in my excel, and since the DN is not very useful in my current case, just squished that down to get it out of my view).

I can also further use text to columns on the “CN” field using the “/” as the delimiter since it is in a better order, as desired.

I now have a much more useful list to group these up with a pivot table and get the summaries I need, and get as detailed as I wish.

I’ll probably also adjust the script to return the actual computers in the script so that I can have a list by location, but that is for another time. Happy Powershelling!