17

有一个文件夹,里面有很多文件。只有一些文件需要复制到不同的文件夹。有一个列表,其中包含需要复制的文件。

我尝试使用复制项,但由于目标子文件夹不存在,抛出异常“找不到路径的一部分”</p>

有没有简单的方法来解决这个问题?

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

1 回答 1

20

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

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 
}
于 2013-02-05T17:31:20.233 回答