# How Can I Determine Whether or Not a Group Has Any Members?

ScriptingGuy1

Hey, Scripting Guy! How can I check a computer and find out whether the Remote Desktop Users group has any members?

— ET

Hey, ET. Somewhat surprisingly, ADSI doesnâ€™t have any sort of NumberOfMembers property, a property that could tell you – at a glance – how many members are in a group. But thatâ€™s all right, because we can simply iterate through the groupâ€™s membership and count the members as we go. Hereâ€™s a script that binds to the Remote Desktop Users group on the computer atl-ws-01 and then counts the number of users in that group:

strComputer = “atl-ws-01”

Set objGroup = GetObject(“WinNT://” & strComputer & “/Remote Desktop Users”) i = 0 For Each objUser in objGroup.Members i = i + 1 Next

Wscript.Echo “Number of users in group: ” & i

If itâ€™s not immediately clear to you, hereâ€™s how we count the number of members. We begin by setting a counter variable (i) to 0. We then use a For-Each loop to loop through the group membership. Each time we run through the loop, we increment the value of i by 1. Suppose we have 23 members in the group. In that case, weâ€™ll run through the loop 23 times and – thatâ€™s right, at the end i will be equal to 23. We then echo the value of i (and, by extension, the number of members in the group).

But what if the group doesnâ€™t have any members? In that case, weâ€™ll never run through the For-Each loop, and the value of i will remain at 0. Thus weâ€™ll end up echoing this message at the end of the script:

Number of users in group: 0

Of course, you didnâ€™t necessarily want to know the exact number of members in the Remote Desktop Users group; you just wanted to know if the group had any members. So hereâ€™s a variation of the script. In this script, if we enter the For-Each loop (which weâ€™ll enter only if the group has at least one member) we echo the fact that the group has at least one member and then quit. If we donâ€™t enter the For-Each loop, then we echo the fact that the group doesnâ€™t have any members. In other words:

strComputer = “atl-ws-01”

Set objGroup = GetObject(“WinNT://” & strComputer & “/Remote Desktop Users”)

For Each objUser in objGroup.Members Wscript.Echo “Remote Desktop Users has at least one member.” Wscript.Quit Next

Wscript.Echo “Remote Desktop Users does not have any members.”