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

时间:2019-08-14 23:12:14

标签: powershell

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

起始文件夹结构如下-

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

1 个答案:

答案 0 :(得分:1)

我如何形象地描述您的目标是,如果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
相关问题