Powershell ForEach loop, to send a file to multiple locations, not working

105 Views Asked by At

I am attempting to send one file to multiple locations using a ForEach loop.

It gets sent to one location, but not the second. I have noticed that the second location gets output to the host, though, which is a bit strange to me.

Code:

$filename = "test.txt"
$Fullpath = "C:\Path\To\Folder\"+$filename
$Testpath1 = "C:\Path\To\Folder\TestCopyTo\"
$Testpath2 = "C:\Path\To\Folder\TestCopyTo_SecondPath\"
$TESTFilepaths = $Testpath1;$Testpath2
$FilePathList = $TESTFilepaths.split(';')
    
foreach($Path in $FilePathList){
                        
    Write-Host "Copying $Filename to $Path"

    Copy-Item $Fullpath -destination $Path 
    
}

Output:

enter image description here

As per above, it makes it to TestCopyTo, but not TestCopyTo_SecondPath

I have been wracking my brain for half a day over this, and I am sure it is something simple!

Thanks

========== EDIT EDIT =============

I FIGURED IT OOOOUUUTT! Almost a whole workday because of these stupid little things: +';'+

It's always something small. I know you all feel me right now.

Fixed code:

$filename = "test.txt"
$Fullpath = "C:\FIS\Site\Quantum Reporting\Output\"+$filename
$Testpath1 = "C:\FIS\Site\Quantum Reporting\Output\TestCopyTo"
$Testpath2 = "C:\FIS\Site\Quantum Reporting\Output\TestCopyTo_SecondPath"
$TESTFilepaths = $Testpath1+';'+$Testpath2
$FilePathList = $TESTFilepaths.split(';')

foreach($Path in $FilePathList){
                        
    Write-Host "Copying $Filename to $Path"

    Copy-Item $Fullpath -destination $Path 
    
}

The reason for the complications, as mentioned by the commenter, is due to the real world code being complicated. Data is extracted with a semi colon and that worked fine in 'Production', but issues arose when I added a test section to the script. I wrote it to tell the difference between production and test, to automate testing as much as I could.

In the real world, the semi colon is a part of the string already. In the Test section of the code I had to make it a part of the string using the quotes.

~picard_facepalm.gif~

1

There are 1 best solutions below

2
Avshalom On

Your code is a little bit complex. you just need to create an array with the paths and iterate it, like this:

$filename = "test.txt"
$FilePathList = @("C:\Path\To\Folder","C:\Path\To\Folder\TestCopyTo",
"C:\Path\To\Folder\TestCopyTo_SecondPath")
    
foreach($Path in $FilePathList){
    Write-Host "Copying $Filename to $Path"
    $Fullpath = Join-Path $Path $filename
    Copy-Item $Fullpath -Destination $Path
}