0

I'm writing a simple PowerShell script to get all the users from a specific OU in Active Directory (AD) and all the folders from a directory, then compare each username with each foldername to verify that the user has a folder there, and do something.

The script shown below works fine, but when it matches the strings, I want it to break and return to the outer For-EachObject, switching the username. (It's not necessary to verify the rest of the list if it already found one), but the break is breaking the entire script, it just ends.

$PerfilFolder = Get-ChildItem $FileServerPath | Sort
Get-ADUser -SearchBase $SB -Filter * | Sort SamAccountName | % {
    $UserName = $_.SamAccountName
    $PerfilFolder | % {
        if($UserName -match (($_.Name).Split(".")[0])){
            #Match!
            #Do something
            break
        }
    }
}

I already tried return and continue, but all of them have the same behavior. What should I do?

Also general improvements tips are welcome :)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
esserafael
  • 195
  • 1
  • 1
  • 6

3 Answers3

0

Check smeltplate's answer to this question. It seems your break perfectly exits the foreach loop, but not the pipeline.

Community
  • 1
  • 1
Roderick Bant
  • 1,534
  • 1
  • 9
  • 17
0

I usually avoid this by setting up two sets of objects, and then filtering one on the property of the other.

$PerfilFolder = Get-ChildItem $FileServerPath | Sort
foreach ($user in Get-ADUser -SearchBase $SB -Filter * | Sort SamAccountName){
   $matchingFolder = $PerfilFolder | ? {$user.SamAccountName -match (($_.Name).Split(".")[0])
   if (($matchingFolder | Measure-Object).Count -gt 0){
       #do something to $matchingFolder | Select -First 1
   }
   else {
       # Do something else
   }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chris N
  • 7,239
  • 1
  • 24
  • 27
0

Use a Do{} While() loop:

$PerfilFolder = Get-ChildItem $FileServerPath | Sort
Get-ADUser -SearchBase $SB -Filter * | Sort SamAccountName | % {
    $UserName = $_.SamAccountName
    $NoMatch = $true
    Do{$PerfilFolder | % {
        if ($UserName -match (($_.Name).Split(".")[0])){
            #Match!
            #Do something
            $NoMatch = $false
        }
    } While($NoMatch)
}

I am pretty sure that'll end your loop where you want it to. That answers the question, but it really doesn't solve your problem if that's what you're really trying to do. I think including a Where statement would serve you better:

    Do{$PerfilFolder | Where{$UserName -match (($_.Name).Split(".")[0])} |
        %{
            #Match!
            #Do something
            $NoMatch = $false
        }
    } While($NoMatch)

That may well make the Do{} While() unnecessary.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TheMadTechnician
  • 34,906
  • 3
  • 42
  • 56