Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

How do I stop searching in a Foreach loop after my condition is found?

$
0
0

Hi,

The goal is for each user in a list ($AllUsers) to search if a Mail attribute is already set on another user acct's UserPincipalName ($Upn) in the directory, and if found, set a flag and go to the next user ($User).

So below, I read a $User from the $AllUsers list and if their Mail attr is not equal to their UPN, compare their Mail attr with the UPN attr of every user in the $Allusers list.  When I find the Mail attr of a user to equal the UPN attr of another user, I set the $UpnEq flag to True, but then I keep searching the rest of the list.  When I find a match and the $UpnEq flag is set to True, I want to exit the Foreach ($UPn in $Allusers) loop cause my condition was found, and then start with a new user in the Foreach ($User in $Allusers) loop.  How do I do this effectively?

Foreach ($User in $AllUsers) { #2
        $UpnEQ   = ""
        $UserNE  = ""
        If ($User.Mail -ne $User.UserPrincipalname) { #3
             $UserNE = "True"
           Foreach ($Upn in $Allusers) {  #4
           If (($User.Mail -eq $Upn.UserPrincipalName) -and       
               ($User.SamAccountName -ne $Upn.SamAccountName))           
             {
             $UpnEQ    = "True"
             # Log to track this
             $UpnNEobj     = New-Object psobject -Property ([ordered] @{
             UserSam       = $User.SamAccountName;
             UserMail      = $User.Mail;
             UserUPN       = $User.UserPrincipalName;
             UserDN        = $User.DistinguishedName;
             UpnSam        = $Upn.SamAccountName;
             UpnrMail      = $Upn.Mail;
             UpnrUPN       = $Upn.UserPrincipalName;
             UpnDN         = $Upn.DistinguishedName})

             $UpnEQArray += $UpnNEobj

             }

            } #4

           } #3  
       } # 2  


Thanks for your help! SdeDot



Viewing all articles
Browse latest Browse all 21975

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>