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
}
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With