powershell - 将文件复制到新的目标文件夹,同时保持文件夹结构
问题描述
我正在使用 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\已复制 ├─ 1.1 │ └─ 1.1.txt └─ 1.txt
即没有“1”子文件夹。
虽然确保目标文件夹存在没什么大不了的,但我有兴趣尝试了解这里发生了什么。
解决方案
如果你想让 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
推荐阅读
- java - 调用将字符串数组作为参数的方法导致 IllegalArgumentException
- c++ - 具有 Linkedlist 数据类型的模板堆栈类在地址 c++ 处给出无法访问内存的错误
- excel - 如果满足某些条件,请选中复选框 excel vba
- jquery - 如何在CSS中将div2添加到div1右侧底部
- angular - Algolia 的 nbHits 不适用于角度条件下的条件
- android - 如何根据活动状态更改 TextInputEditText 样式
- azure - 使用 B2C 和 Active Directory 为公司实施身份验证和授权流程
- c++ - 如何根据 1) 名称和 2) 年龄对数组元素进行排序,以及输出中数组元素的匹配名称和年龄?
- javascript - 如何在 foor 循环中的 x-bind alpine.js 中添加条件?
- python - 如何在 Python 中找到一个 id 的所有孩子?