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

Wednesday, March 19, 2008

2008-03-19 PowerShell Exercise

Today's script is a very useful one. It is always frustrating to see groups as members of groups without being able to easily see group membership.

THE QUESTION:

Hey, Scripting Guy! I manage over 300 servers in our environment. For each server I need to determine the members of the local Administrators account. It’s easy to get a list of local users and domain users that belong to the Admin account; it’s also easy to get a list of any domain groups that belong to the Administrators account. However, what I’d really like to do is take each of those domain groups and then get a list of their members. In other words, I don’t want to know just that the Finance Managers group has local Administrator rights; I’d like to know who belongs to the Finance Managers group (and thus has local Admin rights). Can you help?

 SCRIPTING GUYS' SOLUTION:

strComputer = "atl-fs-001"
strTestString = "/" & strComputer & "/"

Set objGroup = GetObject("WinNT://" & strComputer & "/Administrators")

For Each objMember In objGroup.Members
    If objMember.Class = "Group" Then
        If Not InStr(objMember.AdsPath, strTestString) Then
            Set objDomainGroup = GetObject(objMember.AdsPath)
            Wscript.Echo objDomainGroup.Name
            For Each objDomainMember in objDomainGroup.Members
                Wscript.Echo objDomainMember.FullName & " (" & objDomainMember.Name & ")"
            Next
            Wscript.Echo
        End If
    End If
Next

MY SOLUTION:

cls
$ErrorActionPreference = "SilentlyContinue"

$adminsGroup = [ADSI]"WinNT://derekm-vpc01/Administrators,group"
$groupMembers = $adminsGroup.PSBase.Invoke("Members") | %{$_.GetType().InvokeMember("Name",'GetProperty', $null, $_, $null)}
foreach ($groupMember in $groupMembers) {
    $gm = $gmMembers = $null
    $gm = Get-QADGroup $groupMember
    if ($gm -ne $null) {
        $gmMembers = Get-QADGroupMember $gm
        $gm.Name
        Write-Host "---------------"
        $gmMembers
    }
}

This one took some research. I got the $groupMembers code from here. I was not really able to find a good 'pure PowerShell' solution to this problem. This script is no cleaner, shorter, or "PowerShell-er' than the VB solution. This script is quick, brute-force, dismissive of errors... in a word... UGLY! But, I am pretty sure it produces the same output.

No comments:

Additional Info

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