在保持文件夹结构的同时将文件复制到新的目标文件夹

时间:2019-03-05 11:27:37

标签: powershell tree directory

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

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\copied
├─ 1.1
│  └─ 1.1.txt
└─ 1.txt

即没有“ 1”子文件夹。

虽然确保目标文件夹不存在任何问题,但我有兴趣尝试了解此处的情况。

3 个答案:

答案 0 :(得分:0)

我无法重新创建您的问题。

New-Item -Path C:\test\1 -ItemType Directory | Out-Null
New-Item -Path C:\test\1\1.txt -ItemType File | Out-Null
New-Item -Path C:\test\1\1.1 -ItemType Directory | Out-Null
New-Item -Path C:\test\1\1.1\1.1.txt -ItemType File | Out-Null
Copy-Item -Path "C:\test\*" -Destination "C:\temp" -Recurse
Get-ChildItem C:\temp -Recurse | Select-Object -ExpandProperty FullName

输出:

C:\temp\1
C:\temp\1\1.1
C:\temp\1\1.txt
C:\temp\1\1.1\1.1.txt

答案 1 :(得分:0)

如果您想让复制项正确递归,
源和目标应该保持平衡。

在我的空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

答案 2 :(得分:0)

根据-Destination参数指定的目录路径是否存在,Copy-Item的行为有所不同。

Copy-Item -Path "D:\tmp\copytest\1" -Destination "D:\tmp\copied" -Recurse

如果“已复制”目录不存在,则将目录“ 1”复制为名称“已复制”。另一方面,如果存在“已复制”目录,则目录“ 1”将直接复制到“已复制”目录下。

如果复制目录,则应事先检查目标目录是否存在。简单的方法如下。

Copy-Item -Path "D:\tmp\copytest\*" -Destination (mkdir "D:\tmp\copied" -Force) -Recurse
相关问题