Search code examples
powershellgroupingbambooget-childitemselect-object

Copying Only The Last File Of Each Group Of The Same File Using PowerShell


I ran into an issue building the Bamboo deployment of a legacy application. The application has many version of the same DLLs, so when they are copied over as artifacts during the deployment process, they needlessly overwrite each other, adding an additional 15 minutes to deployment.

This was my original method of selecting and copying the required DLLs:

Get-ChildItem $sourcePath -Include $includedDlls -Recurse | 
Copy-Item -Destination $applicationDestinationRoot -Force

Solution

  • After spending hours researching and piecing together different PS scripts, I assembled a solution:

    Get-ChildItem $sourcePath -Include $includedDlls -Recurse | 
    Group-Object BaseName | 
    ForEach-Object {$_.Group[-1] | Copy-Item -Destination $applicationDestinationRoot -Force}
    

    First, I had to group the files by their BaseName. Then take the grouping object of each DLL. Finally, selecting only the last FullName path of each DLL and copying that to the remote server destination.

    Subsequently, if you wanted to take the first file instead of the last, simply replace $_.Group[-1] with $_.Group[0].

    Edit: I've updated my answer with @Ansgar Wiechers' shorter version of the code.