将每个文件夹移动到顶层,包括在 Powershell 中递归的内容

问题描述

我如何递归地将所有目录移动到顶层,包括它们的所有子目录。 目录中的文件也应该被复制。 如果目录已存在,则应合并其内容并保留所有文件(可能通过重命名文件

例如

dir1
----img1
----img2
----dir2
--------img1
--------img2
------------dir1
------------img1
------------img2
------------img3
dir4
----img1
----img2
----img3

成为

dir1
----img1
----img1_1
----img2
----img2_2
----img3
dir2
----img1
----img2
dir4
----img1
----img2
----img3

我的方法就是这样。

Get-ChildItem $SOURCE_PATH  -Recurse |
            Foreach-Object {
                $IS_DIR = Test-Path -Path $_.FullName -PathType Container
                if ($IS_DIR) {
                    Move-Item $_.FullName -dest ($DESTPATH + "/" + $_.Name)
                }
}

谢谢。

解决方法

我不会移动目录,而是移动单个文件以控制每个文件的目标名称。

此代码未经测试,只是为了给您一个想法。根据需要进行调整。

# Use parameter -File to operate on files only
Get-ChildItem $SOURCE_PATH -File -Recurse | Foreach-Object {

    # Get name of parent directory
    $parentDirName = $_.Directory.Name

    # Make full path of destination directory
    $destSubDirPath = Join-Path $DESTPATH $parentDirName

    # Create destination directory if not exists (parameter -Force).
    # Assignment to $null to avoid unwanted output of New-Item
    $null = New-Item $destSubDirPath -ItemType Directory -Force 

    # Make desired destination file path. First try original name.
    $destFilePath = Join-Path $destSubDirPath $_.Name

    # If desired name already exists,append a counter until we find an unused name.
    $i = 1
    while( Test-Path $destFilePath ) {
        # Create a new name like "img1_1.png"
        $destFilePath = Join-Path $destSubDirPath "$($_.BaseName)_$i.$($_.Extension)"
        $i++
    }

    # Move and possibly rename file.
    Move-Item $_ $destFilePath 
}