Copy a list of files to a directory

浪子不回头ぞ 提交于 2020-12-29 03:05:42

问题


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 
}

回答1:


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 
}


来源:https://stackoverflow.com/questions/14712435/copy-a-list-of-files-to-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!