gpt4 book ai didi

powershell - 将匹配名称的文件夹复制到匹配目录的其他子文件夹

转载 作者:行者123 更新时间:2023-12-02 23:35:09 24 4
gpt4 key购买 nike

如果文件夹名称匹配,我试图将文件夹从一个目录复制到另一个文件夹的子目录。

起始文件夹的结构是这样的-

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命令中我看到它只是将文件夹复制到第一个子文件夹而不匹配名称。

最佳答案

我如何形象地描述您的描述是,如果VR-0-1000中存在一个VR-01子文件夹,则要在Destination \ VR-0-1000文件夹中复制源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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com