Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Looping through an array to find a string

Status
Not open for further replies.

ErrolDC

MIS
May 26, 2004
72
US
Hi folks. There is something I need to understand how to do properly and I was hoping to get some insight.

Suppose I want to loop through an array. I am looking for specific text string. If the string is found, I want to stop searching the array and perform some other action. If it is not found, I just want to exit or go on to something else. What is the best way to do this?

A script that I wrote loops through the AD groups a user is a member of, looking for a specific group name. If the group name is found, it increments a counter. After looping through the entire array, I then examine the counter. If it is greater than 0, I move along to the next block of code.
IMO, i think this is inefficient. What if the number of groups I need to search through is extremely large? But I can't figure out how to properly break the loop if I find what I'm looking for. Here is my code.

Code:
set objNet = CreateObject("Wscript.NetWork")
dim username
dim domainname
dim counter
TargetGroup = "SAV Install"
username = objNet.UserName
domainname = objNet.UserDomain
computername = objNet.ComputerName
Set User = GetObject("WinNT://" & domainname & "/" & username & ",user")
counter = 0 ' set count to 0 initially. 
For Each Group in User.Groups
If Group.Name = TargetGroup then 
counter = counter + 1
end if
next
if counter > 0 then
    blah blah blah .....

Although the above solution works, I find myself having to rely on this method when i know there is a better way. Can someone enlighten me?

TIA,

Errol

 
If you only care about the existance of 1 or more, and you don't care about how many, you can do this:

For Each Group in User.Groups
If Group.Name = TargetGroup then
bFound = True
Exit For '<-- Exit For/Next loop now
end if
next

If bFound Then
'was found
Else
'not found
End if
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top