2013-02-05 150 views
6

存在包含大量文件的文件夹。只有部分文件需要被复制到不同的文件夹。有一个列表包含需要复制的文件。将文件列表复制到目录

我试图用复制项目,但因为目标子文件夹不存在异常被抛出“找不到路径的一部分”

是否有一个简单的方法来解决这一问题?

$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 
} 

回答

10

试试这个作为你的foreach循环。它创建targetfolder和复制文件之前,必要的子文件夹。

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 
} 
+0

好看。有一个简单的方法来翻转这个在做完全相反的?也就是说,在'$ imagesList'中复制** NOT **的所有文件? – user3026965

相关问题