2012-02-14 69 views
6

我想所有生成的輸出文件和文件夾複製到除其留在OutputDir一些文件的文件夾(OutputDir /斌)。 Bin文件夾將永遠不會被刪除。PowerShell的:移動文件遞歸

初始條件:

Output 
    config.log4net 
    file1.txt 
    file2.txt 
    file3.dll 
    ProjectXXX.exe 
    en 
     foo.txt 
    fr 
     foo.txt 
    de 
     foo.txt 

目標:

Output 
    Bin 
     file1.txt 
     file2.txt 
     file3.dll 
     en 
     foo.txt 
     fr 
     foo.txt 
     de 
     foo.txt 
    config.log4net 
    ProjectXXX.exe 

我第一次嘗試:

$binaries = $args[0] 
$binFolderName = "bin" 
$binFolderPath = Join-Path $binaries $binFolderName 

New-Item $binFolderPath -ItemType Directory 

Get-Childitem -Path $binaries | ? {$_.Name -notlike "ProjectXXX.*" -and $_.Name -ne "config.log4net" -and $_.Name -ne $binFolderName } | Move-Item -Destination $binFolderPath 

這確實沒有t工作,因爲Move-Item不能覆蓋文件夾。

我的第二次嘗試:

function MoveItemsInDirectory { 
    param([Parameter(Mandatory=$true, Position=0)][System.String]$SourceDirectoryPath, 
      [Parameter(Mandatory=$true, Position=1)][System.String]$DestinationDirectoryPath, 
      [Parameter(Mandatory=$false, Position=2)][System.Array]$ExcludeFiles) 
    Get-ChildItem -Path $SourceDirectoryPath -Exclude $ExcludeFiles | %{ 
     if ($_ -is [System.IO.FileInfo]) { 
      $newFilePath = Join-Path $DestinationDirectoryPath $_.Name 
      xcopy $_.FullName $newFilePath /Y 
      Remove-Item $_ -Force -Confirm:$false 
     } 
     else 
     { 
      $folderName = $_.Name 
      $folderPath = Join-Path $DestinationDirectoryPath $folderName 

      MoveItemsInDirectory -SourceDirectoryPath $_.FullName -DestinationDirectoryPath $folderPath -ExcludeFiles $ExcludeFiles 
      Remove-Item $_ -Force -Confirm:$false 
     } 
    } 
} 

$binaries = $args[0] 
$binFolderName = "bin" 
$binFolderPath = Join-Path $binaries $binFolderName 
$excludeFiles = @("ProjectXXX.*", "config.log4net", $binFolderName) 

MoveItemsInDirectory $binaries $binFolderPath $excludeFiles 

是否有使用PowerShell中更簡單的方法遞歸移動文件的任何其他方式?

+0

如果顯示的是如何一個例子文件夾結構,然後如何你希望它最終能夠幫助你得到你需要的答案。 – 2012-02-14 17:03:11

回答

6

你可以用Copy-Item命令替換Move-Item命令,並在這之後,你可以通過簡單地調用Remove-Item刪除您移動的文件:

$a = ls | ? {$_.Name -notlike "ProjectXXX.*" -and $_.Name -ne "config.log4net" -and $_.Name -ne $binFolderName } 
$a | cp -Recurse -Destination bin -Force 
rm $a -r -force -Confirm:$false 
+0

Upvote for you,唯一的缺點是您的過濾器僅適用於根目錄中的項目,並且不會遞歸應用過濾器。 – 2013-12-12 21:13:51

0

如前所述,Move-Item不會覆蓋文件夾,因此您只需複製。另一種解決方案是使用/ MOV開關(其中包括!)爲每個循環中的每個文件調用Robocopy;這將移動然後刪除源文件。