2012-02-14 36 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;这将移动然后删除源文件。

相关问题