0

Why is my code not executed after the "break" when it is outside the loop? What is the solution, please?

Here is my code:

$disk = 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
    
$disk | ForEach-Object {
    if (!(Test-Path  "${_}:\"))
        {
            $ldisk=$_
            $ldisk
            break;
        }
    }
    
$ldisk
Write-Host "test"   

Here is the output

PS D:\powershell> d:\powershell\ftpdisk.ps1
A

For me, my output must be:

PS D:\powershell> d:\powershell\ftpdisk.ps1
A
A
test
zett42
  • 25,437
  • 3
  • 35
  • 72
geekdu972
  • 189
  • 1
  • 14
  • well!! Perfect! Thanks! it works! – geekdu972 Feb 28 '21 at 20:39
  • The linked duplicate is not a very good one. I would have suggested the following, more PowerShell-idiomatic way: `$ldisk = $disk | Where-Object { ! (Test-Path "${_}:\") } | Select-Object -First 1`. Here the `Select-Object` cmdlet acts like a `break` statement as it actually breaks the pipeline when the 1st matching element has been found. – zett42 Feb 28 '21 at 20:44
  • Thanks! your solution is perfect for me! – geekdu972 Feb 28 '21 at 20:48

0 Answers0