如果文件夹名称匹配,我正在尝试将文件夹从一个目录复制到另一个文件夹的子目录。
起始文件夹结构是这样的 -
Data > VR-01
整个VR-01
文件夹应该移动到目标文件夹,如下 -
Data > VR-0-1000 > VR-01 [match this name] > Archive > [matched folder (VR-01) should go here]
VR 被分成不同的文件夹,0-1000、1001-2000 等,具有相同的目录结构。
$startPath = "C:\Start\Data"
$destinationPath = "C:\Destination\Data"
$DestinationFolders = Get-ChildItem -Path $destinationPath -Directory | Select -ExpandProperty FullName
# for each item in the folder that is a directory (folder)
Get-ChildItem -Path $startPath -Recurse -Directory | %{
#Get the folder name to compare it to the destination folder
$CurrentFolderName = ($_.Name)
#Find matching directory for that folder
#Where-Object
$DestinationFolders | ?{$CurrentFolderName -like $DestinationFolders}
#Copy files
Copy-Item -Path $_.FullName -Destination $DestinationFolders -WhatIf
}
我尝试使用 -match
命令,但由于\字符是正则表达式的一部分而失败,所以我切换到 -like
。
看起来我错过了比较文件夹名称并复制它们的步骤,因为从 -WhatIf
命令中我看到它只是将文件夹复制到第一个子文件夹而不匹配名字。
最佳答案
我如何形象地描述您的描述是,在 Destination\VR-0-1000 文件夹中,如果 VR-0-1000 中存在 VR-01 子文件夹,您希望复制源 VR-01。可能不一定存在 Destination\VR-0-1000\VR-n
。
我曾尝试过。不保证效率,但我相信它会完成这项工作。
$startPath = "C:\Start\Data"
$destinationPath = "C:\Destination\Data"
$sourceNames = (Get-ChildItem $startPath -Recurse -Directory).Name
(Get-ChildItem $destinationPath -Directory).FullName | % {
# For each folder named 'VR-****-****'
Get-ChildItem -Path $_ | % {
# For each folder named VR-****-****\VR-****
if($sourceNames -Contains $_.Name)
{
$sourceFolder = "$startPath\$($_.Name)\*"
$destFolder = $_.FullName
Write-Output "Copying $sourceFolder into $destFolder"
Copy-Item -Path $sourceFolder -Destination $destFolder -Recurse
}
}
}
我在这样的结构上运行了它
C:.
├───Dest
│ ├───VR-1-2
│ │ └───VR-01
│ └───VR-3-4
│ └───VR-03
└───Start
├───VR-01
├───VR-02
├───VR-03
└───VR-05
输出:
Copying C:\soverflowtest\Start\VR-01\* into C:\soverflowtest\Dest\VR-1-2\VR-01
Copying C:\soverflowtest\Start\VR-03\* into C:\soverflowtest\Dest\VR-3-4\VR-03
关于powershell - 将名称匹配的文件夹复制到匹配目录的其他子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57503124/