18

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 
}
Mathias F
  • 15,906
  • 22
  • 89
  • 159

1 Answers1

21

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 
}
Frode F.
  • 52,376
  • 9
  • 98
  • 114
  • nice. is there a easy way to flip this over and do the exact opposite? i.e, copy all files that are **NOT** in the `$imagesList`? – user3026965 Nov 04 '17 at 09:13
  • @user3026965: see https://stackoverflow.com/a/16992154/1915920 ... with something like `Get-ChildItem $sourceFolderName -exclude $imagesList` – Andreas Covidiot Jan 23 '19 at 12:55