首页 > 解决方案 > 检查folderone中文件名的一部分是否在文件夹2中匹配,如果找到匹配则输出两者

问题描述

检查folderone中的文件名的一部分是否与foldertwo中的文件名的一部分匹配。
外汇:april_logs-0410.txtin folderone 与 in foldertwo 匹配april_logs-0310.txt
我需要在 foldertwo..ex 中查看匹配的完整文件名 april_logs-0310.txt 必须打印在输出中。

$folderone = Get-ChildItem -Recurse folderone
foreach($file in $folderone)
{
$fileNon = $file.Name -split'(?=-\d)' #splits the filename with -0410
$newfile = $fileNon[0] #this has april_logs
If (test-path "d:\foldertwo\$newfile" -pathtype leaf)) {
write-host "$newfile is in foldertwo"
}

标签: powershell

解决方案


对于给定的树:

> tree a:\ /f
A:\
├───Folder1
│       april_logs-0410.txt
│       may_logs-0510.txt
│
└───Folder2
        april_logs-0310.txt

这一行

gci Folder1\*-[0-9]*|? Name -match '^(.*)-\d'|%{(gci Folder2\$($matches[1])*).FullName}

产量:

A:\Folder2\april_logs-0310.txt

这个更冗长且略有不同的脚本:

## Q:\Test\2019\04\10\SO_55605777.ps1
$FolderOne = 'A:\Folder1'
$FolderTwo = 'A:\Folder2'
foreach($File in (
    Get-ChildItem $FolderOne\*-[0-9]* |
    Where-Object Name -match '^(.*)-\d'|
    Select-Object FullName,@{n='Pattern';e={$Matches[1]}} )){
    if($Found = (Get-ChildItem $FolderTwo\$($File.Pattern)*).FullName){
        "{0} is matched by:" -f $File.FullName
         $Found
    }
}

产量:

> Q:\Test\2019\04\10\SO_55605777.ps1
A:\Folder1\april_logs-0410.txt is matched by:
A:\Folder2\april_logs-0310.txt

推荐阅读