Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a list of files to a directory

There is a folder that contains a lot of files. Only some of the files needs to be copied to a different folder. There is a list that contains the files that need to be copied.

I tried to use copy-item, but because the target subfolder does not exist an exception gets thrown "could not find a part of the path”

Is there an easy way to fix this?

$targetFolderName = "C:\temp\source"
$sourceFolderName = "C:\temp\target"

$imagesList = (
"C:\temp\source/en/headers/test1.png",
"C:\temp\source/fr/headers/test2png"
 )


foreach ($itemToCopy in $imagesList)
{
    $targetPathAndFile =  $itemToCopy.Replace( $sourceFolderName , $targetFolderName ) 
    Copy-Item -Path $itemToCopy -Destination   $targetPathAndFile 
}
like image 953
Mathias F Avatar asked Feb 05 '13 16:02

Mathias F


People also ask

How do I copy a list of files in UNIX?

Copy Multiple Files with “cp” Command: To copy multiple files with the “cp” command, navigate the terminal to the directory where files are saved and then run the “cp” command with the file names you want to copy and the destination path.

How do I copy all contents from one directory to another?

Answer: Use the cp Command You can use the cp command to copy files locally from one directory to another. The -a option copy files recursively, while preserving the file attributes such as timestamp. The period symbol ( . ) at end of the source path allows to copy all files and folders, including hidden ones.


1 Answers

Try this as your foreach-loop. It creates the targetfolder AND the necessary subfolders before copying the file.

foreach ($itemToCopy in $imagesList)
{
    $targetPathAndFile =  $itemToCopy.Replace( $sourceFolderName , $targetFolderName )
    $targetfolder = Split-Path $targetPathAndFile -Parent

    #If destination folder doesn't exist
    if (!(Test-Path $targetfolder -PathType Container)) {
        #Create destination folder
        New-Item -Path $targetfolder -ItemType Directory -Force
    }

    Copy-Item -Path $itemToCopy -Destination   $targetPathAndFile 
}
like image 115
Frode F. Avatar answered Sep 23 '22 17:09

Frode F.