0

This is the code that acts strange :

Function Get-Something
{
Param($destination)

[array]$list = "networkPath1","networkPath2","networkPath3","networkPath4"

$list | % { 

Copy-Item -Path $_ -Destination $destination -Force -ErrorAction SilentlyContinue
if(Test-Path -Path ($destination+"\"+$($_ | Split-Path -Leaf)) -ErrorAction SilentlyContinue)
{
    return $_
}
}
}

$var = Get-Something -destination "C:\Temp"

Here, its meant to try and copy a file from different locations and if successful from any path, its meant to return the successful network path to main code.

Instead, when return is executed, next iteration of foreach block starts executing. Due to this, the code tries to copy from all locations one by one irrespective of success or failure.

I implemented same block using For loop and it worked as expected.

I am now looking for an explanation for this behavior, where return statement inside foreach block acts like 'continue' keyword.

  • 2
    Why are you not testing if "the file" exists in any of the network paths and only if so, copy it to your destination and break the loop? – Theo Jun 06 '20 at 10:02
  • These network paths will have the file for sure, i need to make sure if the copy was successful before coming out of the function. – Rishabh Gupta Jun 06 '20 at 13:39

0 Answers0