exit out of embedded foreach loop once a folder find

AnneW 61 Reputation points
2022-09-07T02:58:09.923+00:00

I had multiple foreach loop in my script, I want to break out of the loop once it find a studentid folder and copy it. But my current script keep searching other folders even it find the student folder. I know the folders has unique value of studentid, so once it find it, not necessary to search again. It should go on to find another studentid folder.
I add a label to my foreach script, but not working. I tried break mid, or break outer, either not working, it keeps to search in the next folder for example 00, then 01 find the studentid folder, then it keeps searching 02, 03 folder.

folder structure: under photo folder there is 00, 01, 02...99, and in 00 there are student folder like 45622, 34599, under each of these folder there are 3 photo files, ph.jpg. phthumnail.jpg, phlarge.jpg
Could you help:

$srcPath = '\\myserver\photo'  
 $AllIds = Get-Content 'C:\dbfile\idfile.txt'  
  
$parentFolders = Get-ChildItem $srcPath  -Dir -ea "Stop" |   
                 Sort-Object  
   Write-Host "parent folder is  $parentfolders"  
     
   :outer foreach ($id in $AllIds) {  
    Write-Host "this is the id $id"  
         
     :mid  foreach ($pf in $parentFolders) # folders like 00 01 02 03 ...99  
	{  
     
          $childFolders = Get-ChildItem $pf.FullName |   
                   Where-Object {$_.PSIsContainer  -and $_.GetFiles().Count}|  
                   Sort-Object  
                 Write-Host "I am in parent loop $pf-----------------------------------------"  
              :inner   Foreach ($cf in $childFolders) ## Foldername is studentid  
		{  
                    $studentid=$cf.Name  
                      Write-Host "I am in  child $cf loop================================"  
                  if($studentid -eq $id)      
                   {   
                    Write-Host "I am in if $id"  
                    $from ="$srcPath\$pf\$cf"  
                    $to = "c:\dbfile\copyphoto"  
  
                    write-host "from $from to $to"  
                    Copy-Item  $from $to  -force -Recurse  
                    break :outer  
                  }          
                       }       
                                    }  
                                        }  
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,390 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rafael da Rocha 5,076 Reputation points
    2022-09-07T03:56:34.773+00:00

    on the break, try not using : before the label

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful