【发布时间】:2017-08-14 13:09:51
【问题描述】:
我正在尝试使用 PowerShell 将多个文件从一个目录复制到另一个目录。 我想:
- 维护文件夹/文件结构。
- 复制特定文件夹中的所有文件。
假设结构:
源文件夹 \用户 1 \文件夹 1 \文件 \文件夹 2 \文件 \文件夹 3 \文件 \用户 2 \文件夹 3 \文件 \用户 3 \文件夹 2 \文件 \用户 4 \文件夹 3 \文件 \文件夹 4 \文件可能的场景:
- 我想复制用户拥有文件夹 1 和文件夹 2 的文件。
预期结果:
目标文件夹 \用户 1 \文件夹 1 \文件 \文件夹 2 \文件 \用户 3 \文件夹 2 \文件这是我目前的代码:
$FolderName = '\\Folder 1\\'
$source = 'C:\CDPTest\Live'
$target = 'C:\CDPTest\DevTest'
$source_regex = [regex]::Escape($source)
(gci $source -Recurse | where {-not ($_.PSIsContainer)} | select -Expand FullName) -match $FolderName |
foreach {
$file_dest = ($_ | Split-Path -Parent) -replace $source_regex, $target
if (-not (Test-Path $file_dest)) {mkdir $file_dest}
}
正如您所见,匹配只会根据当前代码返回一个文件路径,我想做的是扩展它以匹配多个文件夹名称。
我尝试过的:
- 在单独的 PowerShell 文件中使用不同的 FolderName 运行此代码,但没有成功。
- 使用文件夹名称数组进行匹配。
- 使用
-and/-or运算符扩展匹配功能。
【问题讨论】:
-
你似乎在寻找
robocopy。 -
您好,感谢您的回复,我尝试了 robocopy 无济于事,我选择了 PowerShell,因为我认为它更强大。我将在 robocopy 再试一次。
-
使用
robocopy,您排除了您不想想要复制的内容,因此请尝试robocopy $source $target /s /xd "User 2" "User 4"。 -
再次感谢您的回复,我试图避免排除并使用包含,因为与我需要的 5 个相比,有很多潜在的文件夹名称。
-
您可以像这样构建排除列表:
$include = 'User 1', 'User 3'; ls $source | ? { $include -notcontains $_.Name }
标签: powershell directory data-migration file-copying