使用Powershell:将所有文件从文件夹和子文件夹移动到单个文件夹

52

尝试在8K文件和2K文件夹中索引和搜索文件..

是否有一个简单的PowerShell脚本,可以将所有文件从文件夹和/或子文件夹移动到一个主文件夹中?

不需要删除空文件夹,但这会有所帮助。


5
将所有子文件夹移动到父文件夹中,只需使用一个命令: Get-ChildItem -Path ./ -Recurse -File | Move-Item -Destination ./ ; Get-ChildItem -Path ./ -Recurse -Directory | Remove-Item; - Vael Victus
3个回答

80

help -Examples Move-Item[1] 中的第四个示例与您需要的非常接近。要将 SOURCE 目录下的所有文件移动到 DEST 目录下,您可以执行以下操作:

Get-ChildItem -Path SOURCE -Recurse -File | Move-Item -Destination DEST

如果您想在之后清除空目录,可以使用类似的命令:

Get-ChildItem -Path SOURCE -Recurse -Directory | Remove-Item

[1] https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.management/move-item


3
我不确定你想要做什么。你肯定知道目标目录,否则操作就不知道把文件放在哪里。 - Don Cruickshank
如果我需要保留文件夹结构怎么办?这样会复制文件但不会保持文件夹结构。 - Juan Medina
@JuanMedina 对于这种情况,您可以只删除“-Recurse”和“-File”标志。 - Don Cruickshank
尝试移动文件夹时,它实际上会失败并显示“访问被拒绝”,即使您是管理员。 - Juan Medina
@JuanMedina 对我来说,这听起来像是权限问题或者目录仍在某种程度上被使用。 - Don Cruickshank
显示剩余2条评论

1

使用.parent表示父级目录。它可以递归使用:.parent.parent


1
另一个答案对我来说导致了错误,因为有重复的文件。我的代码通过在重复的文件名后添加“_x”来解决这个问题。 此外,只有在没有文件剩余的情况下才应该执行删除操作。
$files = Get-ChildItem -Path . -Recurse -File
foreach ($file in $files) {
  $dest = Join-Path . $file.Name
  if (Test-Path $dest) {
    $i = 1
    do {
      $newName = "$($file.BaseName)_$i$($file.Extension)"
      $newDest = Join-Path . $newName
      $i++
    } while (Test-Path $newDest)
    Move-Item -Path $file.FullName -Destination $newDest
  } else {
    Move-Item -Path $file.FullName -Destination $dest
  }
}

Get-ChildItem -Directory | Where-Object {(Get-ChildItem $_ -Recurse -File).count -eq 0} | ForEach-Object {Remove-Item $_ -Recurse}

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