PowerShell查找匹配文件夹,然后从src移动到目标

时间:2015-09-23 21:08:13

标签: powershell match move directory

我需要弄清楚在两个目录中找到匹配文件夹的代码。

Source Directory

Destination Directory

找到匹配项后,我需要将源目录的内容移动到目标目录,然后从源目录中删除该文件夹。如果目标目录中的匹配文件夹与源目录中的匹配文件夹匹配,我只希望发生这种情况。

文件夹名称的格式为3;15-cr-2015423-5993

每次字母和数字都不同,所以我需要搜索文件夹名称的格式,即:

[0-9];[0-9][0-9]-..-[0-9][0-9][0-9][0-9][0-9].

感谢您的任何帮助。

2 个答案:

答案 0 :(得分:1)

你可以利用这种模式

(\d+;\d+-\w+-\d+)|(\d+-\d+)

在此处查看演示https://regex101.com/r/wL4iL7/1

<强>解释

(\d+;\d+-\w+-\d+): First group to be captured
(\d+-\d+): second group to be captured

对于第一组

\d+:matches all numbers
;:matches the semicolon
\d+-: matches all numbers and hyphen
\w+-\d+: matches words hyphen and numbers

第二组

\d+-: matches all numbers and hyphen
\d+: matches the last set of numbers

答案 1 :(得分:0)

正则表达式完全是unessacary。如果您只是想在匹配时进行复制,那么您只需要使用带有Compare-Object cmdlet的小型PowerShell来比较列表。更简单的只是使用where过滤器,这是我们要做的。还假设您不需要递归逻辑,因为您没有请求它。

$sourceDirectory = "f:\temp\source"
$destinationDirectory = "f:\temp\destination"

$sourceFolders = Get-ChildItem -Path $sourceDirectory | Where-Object{$_.PSisContainer} | Select-Object -ExpandProperty Name
$destinationFolders = Get-ChildItem -Path $destinationDirectory | Where-Object{$_.PSisContainer} | Select-Object -ExpandProperty Name

$matchesInBoth = $sourceFolders | Where-Object{$destinationFolders -contains $_}
$matchesInBoth | ForEach-Object{
    $sourcePath = (Join-Path $sourceDirectory $_)
    Copy-Item -Path $sourcePath -Destination $destinationDirectory -Force -Recurse
    Remove-Item $sourcePath -Force -Recurse #-WhatIf 
}

获取两个目标中的所有文件名。对于两者中的每个目录,我们复制所有内容并删除源目录。