PowerShell: 递归移动文件

6
我将尝试将所有构建输出的文件和文件夹复制到一个名为BinOutputDir/Bin)的文件夹中,但某些文件将留在OutputDir中。 Bin文件夹永远不会被删除。 初始条件:
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

这种方法行不通,因为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递归地移动文件?

如果您展示一个示例文件夹结构,说明当前的情况和您想要的最终结果,那么这将有助于我们为您提供所需的答案。 - Andy Arismendi
2个回答

6

你可以将Move-Item命令替换为Copy-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

点赞给你,唯一的缺点是你的过滤器只适用于根目录中的项目,并且不会递归应用过滤器。 - Adam Plocher

0

如前所述,Move-Item不会覆盖文件夹,因此只能使用复制。另一种解决方案是在for-each循环中为每个文件调用Robocopy,并使用/MOV开关(以及其他选项!);这将移动然后删除源文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接