Search code examples
powershellcopycopy-item

Copy jar files to local folder


I have in a folder some JAR files generated by Maven.

I tried to copy only JAR files to another path with PowerShell using this command:

Copy-Item -Path C:\jenkins\workspace\maven-test\target\*.jar -Destination C:\jenkins\extlib -Recurse

But the result is a file called extlib without extension in C:\Jenkins.

What is wrong?


Solution

  • When extlib doesn't already exist as a subfolder of C:\Jenkins and you specify the destination path without a trailing backslash PowerShell will copy all files to the destination file C:\Jenkins\extlib, replacing each copied file with the next one.

    Adding a backslash to the end of the destination path will make PowerShell throw an error if the folder doesn't exist:

    $src = 'C:\jenkins\workspace\maven-test\target'
    $dst = 'C:\jenkins\extlib'
    
    Copy-Item -Path "${src}\*.jar" -Destination "${dst}\" -Recurse
    

    To avoid this issue entirely create a missing folder before copying the files:

    $src = 'C:\jenkins\workspace\maven-test\target'
    $dst = 'C:\jenkins\extlib'
    
    if (-not (Test-Path -LiteralPath $dst -PathType Container)) {
        New-Item -Type Directory $dst | Out-Null
    }
    Copy-Item -Path "${src}\*.jar" -Destination "${dst}\" -Recurse