首页 > 解决方案 > 将文件复制到新的目标文件夹,同时保持文件夹结构

问题描述

我正在使用 PowerShell Copy-Itemcmdlet 来尝试复制目录结构。此结构包含许多我需要维护的子文件夹。我正在使用命令:

Copy-Item <<src folder>> <<dest folder>> -Recurse

如果我首先确保目标文件夹存在,那么一切都很好。但是,如果它不存在,则 PowerShell 将创建它,但复制的文件夹结构会丢失第一级。例如,如果我的源文件夹结构是:

D:\tmp\copytest
└─ 1
   ├─ 1.1
   │ └─ 1.1.txt
   └─ 1.txt

我使用命令

Copy-Item "D:\tmp\copytest\*" "D:\tmp\copied" -Recurse

如果我没有提前创建“复制”文件夹,那么目标文件夹如下所示:

D:\tmp\已复制
├─ 1.1
│ └─ 1.1.txt
└─ 1.txt

即没有“1”子文件夹。

虽然确保目标文件夹存在没什么大不了的,但我有兴趣尝试了解这里发生了什么。

标签: powershelltreedirectory

解决方案


如果你想让 Copy-Item 正确递归,
Source 和 Destination 应该平衡。

在我空的 RamDisk 上,这个脚本:

$Drive = "A:"
New-Item -Path "$Drive\tmp\copytest\1\1.1"         -ItemType Directory | Out-Null
New-Item -Path "$Drive\tmp\copytest\1\1.txt"       -ItemType File      | Out-Null
New-Item -Path "$Drive\tmp\copytest\1\1.1\1.1.txt" -ItemType File      | Out-Null

Tree /F $Drive

Copy-Item -Path "$Drive\tmp\copytest\" `
   -Destination "$Drive\tmp\copied\" -Recurse

Tree /F $Drive

有这个输出:

Auflistung der Ordnerpfade für Volume RamDisk
A:\
└───tmp
    └───copytest
        └───1
            │   1.txt
            │
            └───1.1
                    1.1.txt

Auflistung der Ordnerpfade für Volume RamDisk
A:\
└───tmp
    ├───copied
    │   └───1
    │       │   1.txt
    │       │
    │       └───1.1
    │               1.1.txt
    │
    └───copytest
        └───1
            │   1.txt
            │
            └───1.1
                    1.1.txt

推荐阅读