使用 PowerShell 将大量文件夹递归移动到同一文件夹中的另一个文件夹

Move amount of folders recursive to another folder in the same folder with PowerShell

我有一个到 Z 的根文件夹(一个映射的网络驱动器),在这个文件夹中我有一个名为 Archive 的文件夹,我想将 Z 中的一些文件夹移动到存档文件夹。

我在 csv 文件中要移动的文件夹的标题。

我已经创建了一个 PowerShell 脚本,但不知何故它并没有真正起作用,它确实移动了一个文件夹,但是即使在 PowerShell 命令中也没有任何反应,只是空的,过了一会儿没有任何反应,我不得不关闭PowerShell window.

因此,如果我有十个文件夹要复制,则只移动第一个文件夹。

代码如下:

$currentPath = Split-Path -Parent $PSCommandPath;
$areaCsvPath = $currentPath + "\CSVFile.csv";
write-host $areaCsvPath;

$csv = Import-Csv $areaCsvPath;
$count =0;

$Creds = Get-Credential

foreach ($row in $csv)
{
    Get-ChildItem -Path "Z:\" -Recurse |
      Where-Object {$_.name -eq $row.Title} |
      Move-Item -destination "Z:\_Archive" -Credential $Creds

    $count++;
    write-host $count;

}

CSV如下

Title
12345
22223
75687
...

我不明白为什么只移动了一个文件夹,但您可以尝试以下脚本,它应该更快,因为 Get-ChildItem cmdlet 只被调用一次:

$currentPath = Split-Path -Parent $PSCommandPath;
$areaCsvPath = $currentPath + "\CSVFile.csv";
write-host $areaCsvPath;

$csv = Import-Csv $areaCsvPath;
$Creds = Get-Credential

Get-ChildItem -Path "Z:\" -Recurse |
      Where-Object Name -in ($csv | select -expand Title) |
      Move-Item -destination "Z:\_Archive" -Credential $Creds

如果文件夹位于 Z: 的顶层,您应该省略 -Recurse 参数。此外,如果您只想移动文件夹,可以将 -Directory 开关添加到 Get-ChildItem 调用以进一步提高性能。