'Powershell: Copy files from multiple folders to one folder appending files name as source server name

I currently have multiple servers on the farm and want to copy the files of the same extension from these servers to one folder. Each server has the same folder name. The goal is to copy all files from these servers(same path) to another remote folder by appending the files name as the source server. The powershell script I wrote works but was wondering if there was a more elegant way by excluding the second foreach loop in the script (using a foreach-object after the GCI command doesn't work)


Clear-Variable source
Clear-Variable destination
Clear-Variable files
Clear-Variable file
Clear-Variable newPath 
Clear-Variable server

$machines = Get-Content "C:\Users\localadmin\Desktop\servers.txt" 

$destination = '\\nprodserver1\C$\Users\localadmin\Documents'

foreach($server in $machines){

$source = "\\$server\L$\Logs\W3SVC21"


#$files = Get-ChildItem -File "\\$server\L$\Logs\W3SVC21" -Filter *.log -Recurse -Force | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-1)}

$files = Get-ChildItem -Path $source -Filter *.log -Recurse -Force | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-1)}


    foreach ($file in $files) {

      $newPath = Join-Path -Path "$destination" -ChildPath "$($file.BaseName)-$("$server")-$(Split-Path -Path $source -Leaf).log" #change file output format here (e.g..txt)

      Copy-Item -Path $($file.FullName) -Destination $newPath
    }

}





Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source