2013-02-05 21 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'に**ない**すべてのファイルをコピーしますか? – user3026965

関連する問題