【问题标题】:Powershell: Move all files from folders and subfolders into single folderPowershell:将文件夹和子文件夹中的所有文件移动到单个文件夹中
【发布时间】:2022-05-07 03:51:41
【问题描述】:

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

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

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

【问题讨论】:

  • 使用“一个命令”将所有子文件带入父级:Get-ChildItem -Path ./ -Recurse -File | Move-Item -Destination ./ ; Get-ChildItem -Path ./ -Recurse -Directory | Remove-Item;

标签: powershell


【解决方案1】:

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://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/move-item

【讨论】:

  • 如果我只知道source 的名字而不知道dest 怎么办? dest 对我来说是父目录,它具有任意名称。
  • 我不确定您要做什么。当然,您必须知道目标目录,否则操作将不知道将文件放在哪里。
  • 如果我需要维护文件夹结构怎么办?这将复制文件,但不会保持更完整的结构
  • @JuanMedina 对于这种情况,您只需删除 -Recurse-File 标志。
  • 尝试移动文件夹时它实际上失败了,它说访问被拒绝,即使你是管理员
【解决方案2】:

使用.parent 作为父目录。可以递归使用:.parent.parent

【讨论】:

    【解决方案3】:

    我知道这篇文章有点老了,但我遇到了一个类似的问题,但这并不包括我需要维护所有 fsubolder 结构的情况,所以这是我维护子文件夹结构的解决方案

    $sourcePath = "C:\FolderLocation"
    $destPath = "C:\NewFolderLocation"
    Write-Host "Moving all files in '$($sourcePath)' to '$($destPath)'"
    $fileList = @(Get-ChildItem -Path "$($sourcePath)" -File -Recurse)
    $directoryList = @(Get-ChildItem -Path "$($sourcePath)" -Directory -Recurse)
    ForEach($directory in $directoryList){
        $directories = New-Item ($directory.FullName).Replace("$($sourcePath)",$destPath) -ItemType Directory -ea SilentlyContinue | Out-Null
    }
    Write-Host "Creating Directories"
    ForEach($file in $fileList){
        try {
            Move-Item -Path $file.FullName -Destination ((Split-Path $file.FullName).Replace("$($sourcePath)",$destPath)) -Force -ErrorAction Stop
        }
        catch{
            Write-Warning "Unable to move '$($file.FullName)' to '$(((Split-Path $file.FullName).Replace("$($sourcePath)",$destPath)))': $($_)"
            return
        }
    }
    Write-Host "Deleting folder '$($sourcePath)'"
    Remove-Item -Path "$($sourcePath)" -Recurse -Force -ErrorAction Stop
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-30
      • 2011-04-24
      • 2021-04-09
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2021-12-02
      相关资源
      最近更新 更多