Your basic ITPro blog... What's going on at work, what I'm interested in.

Monday, March 31, 2008

2008-03-31 PowerShell Exercise

I just have to share this one. I know PowerShell isn't the be-all and end-all when it comes to Windows Management, but there are definitely times when it is the best tool. This is one of those times.


Hey, Scripting Guy! How can I get a list of all the computers in my domain, grouping those computers by the OU in which the computer account resides?
-- TA


"Interestingly enough, this is a trickier problem than you might expect it to be. At first glance you might think, “Well, that should be easy enough: I just get back a list of all the computers and the OUs they belong to, then sort that list by OU.” That’s actually a pretty good idea, except for one thing: there is no Active Directory property that tells you which OU an object resides in. (No really; take a peek at this column for information on the roundabout method you need to use to determine the OU an object belongs to.)

"But that’s OK. The logical way to attack this problem is to retrieve a list of all the computers and then determine which OU they belong to. In this case, however, the logical way doesn’t do us any good. Therefore, we need to do things the illogical (i.e., the Scripting Guys) way; we’ll get back a list of all the OUs, and then determine which computer accounts can be found in each OU.

"In other words, we’re going to use the following script:

On Error Resume Next Const ADS_SCOPE_SUBTREE = 2 Set objConnection = CreateObject("ADODB.Connection") Set objCommand = CreateObject("ADODB.Command") objConnection.Provider = "ADsDSOObject" objConnection.Open "Active Directory Provider" Set objCommand.ActiveConnection = objConnection objCommand.Properties("Page Size") = 1000 objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE objCommand.CommandText = _ "SELECT ADsPath FROM 'LDAP://dc=fabrikam,dc=com' WHERE " & _ "objectCategory='organizationalUnit'" Set objRecordSet = objCommand.Execute objRecordSet.MoveFirst Do Until objRecordSet.EOF Set objOU = GetObject(objRecordSet.Fields("ADsPath").Value) Wscript.Echo objOU.distinguishedName objOU.Filter = Array("Computer") For Each objItem in objOU Wscript.Echo " " & objItem.CN Next Wscript.Echo Wscript.Echo objRecordSet.MoveNext Loop


Get-QADComputer | Sort-Object -Property ParentContainer | Select-Object Name, ParentContainer

No comments:

Additional Info

My photo
email: support (AT) mangrumtech (DOT) com
mobile: 480-270-4332