首页 > 解决方案 > 从具有相同名称的文件夹/子文件夹中移动文件夹和文件(要重命名的副本)

问题描述

(我试图重写这个更清楚)

我有数百个文件夹和文件(每个以 ABC 开头,然后是数字 001-936)需要移动到同名的单个文件夹的问题。例如:

C:\folders\ABC001 
C:\folders\random\ABC001\ 
C:\folders\files\ABC001.pdf 
C:\folders\ABC002.pdf 
C:\folders\ABC002\  
C:\folders\needs sorting\ABC002\

我想将所有文件和文件夹移动到同名文件夹:

C:\folders\ABC\ABC001\ 
C:\folders\ABC\ABC002\  
and so on...

但是,有时原始文件夹和/或文件会在目标文件夹中有重复项(或者可能已经存在,因为文件夹已经存在),所以我希望它添加到名称 (1)、(2) 等中。

C:\folders\ABC\ABC001\ABC001\
C:\folders\ABC\ABC001\ABC001 (1)\ 
C:\folders\ABC\ABC001\ABC001.pdf 
C:\folders\ABC\ABC002\ABC002.pdf 
C:\folders\ABC\ABC002\ABC002\  
C:\folders\ABC\ABC002\ABC002 (1)\

任何帮助将不胜感激,我已经尝试解决这个问题数周(每次我需要文件),但对脚本/代码是新手。我开始:

for /R "C:\folders" %x in (*abc123*.*) do move "%x" "D:\folders\abc\abc123"

最近的尝试(对另一个代码的微小编辑):

function MoveFileToFolder ([string]$source,[string]$destination){
# get a list of source files
$files = Get-ChildItem -Path $source -Recurse | ?{($_.PSIsContainer)}
# verify if the list of source files is empty
if ($files -ne $null) {
    foreach ($file in $files) {
    $filename = $file.Name
    $filebase = $file.BaseName
    $fileext = $file.Extension
# verify if destination file exists
    $filenameNU = $filename 
    if (Test-Path (Join-Path $destination $filename)) {
        $n = 0
        while ((Test-Path (Join-Path $destination $filenameNU)) -eq $true)
        {
        $filenameNU = $filebase + "(" + ++$n + ")" + $fileext
        }
    }
    Move-Item $file.FullName (Join-Path $destination $filenameNU)
    }
}
}

MoveFileToFolder C:\folders\ C:\folders\abc\abc123

(我会尝试在 Powershell 中为每个子文件夹运行它,但它变得很难跟上)

感谢您的阅读。

标签: powershellscriptingdirectoryrename

解决方案


推荐阅读