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

Monday, March 17, 2008

2008-03-17 PowerShell Exercise

WOW! Do I love PowerShell?! You bet I do. Today's Scripting Guys question is a perfect example of why PowerShell is so powerful and so great.

THE QUESTION:
I’ve been asked to come up with a list of all the groups that have just 1 member or fewer. How can I write a script that will return this information for me?

THE SCRIPTING GUYS ANSWER:

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, Name FROM 'LDAP://dc=fabrikam,dc=com' WHERE objectCategory='group'"

Set objRecordSet = objCommand.Execute

objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Set objGroup = GetObject(objRecordSet.Fields("ADsPath").Value)

    i = 0

    For Each strUser in objGroup.Member
        i = i + 1
        If i > 1 Then
            Exit For
        End If
    Next

    If i <= 1 Then
    Wscript.Echo objRecordSet.Fields("Name").Value & " -- " & i
    End If

    objRecordSet.MoveNext
Loop

MY POWERSHELL ANSWER:

foreach ($group in Get-QADGroup) {if ($group.Members.Count -le 1) {Write-Host $group.Name "--" $group.Members.Count}}

This script should be entered on one line. Pretty amazing, huh? In this one-liner, I am using the Quest AD Commandlets, which are fantastic. They make AD work in PowerShell so much easier.

See you again tomorrow.

No comments:

Additional Info

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