使用 Powershell 仅知道部分文件名时如何查找文件?

问题描述 投票:0回答:2

对于某些类型的文件,可能有 pdf 等效文件。 然而,该 pdf 文件可能在左侧、右侧添加了字符,或者可能完全相同。 例如,对于文件 TAX457.idw,可能有 TAX457-1.pdf 或只是 TAX457.pdf

我还需要这个pdf文件的文件名。

Get-ChildItem -Path $PathEngDesign -File -Include $fileExtensions -Recurse -ErrorAction SilentlyContinue -Force|ForEach-Object{
$file = $_
$baseName = $file.Basename
                $filename = $file.Name
                $filePdf = "*$($baseName)*.pdf"
 $pdfFilePath = $file.fullname -Replace ($filename, $filePdf)
Write-host "Path" $file.FullName
  If (Test-Path $pdfFilePath){
                    Write-host "PDF File and Path Found" $filePdf "PATH-->" $pdfFilePath
}
}



`$filePdf` variable just doesn't work. I have tried `".*$([regex]::Escape($baseName)).*\.pdf"` this just doesn't work. The output is as if there is no file in the folder. 
`"*$($baseName)*.pdf"` this returns files that are not pdf for but adds .pdf and  * to the file name. 
For example  there are three files in folder B26945.idw,B26945.ipt, and B2694501.pdf
the output is `\\EngDesignLib\026\026945.007\*B26945*.pdf` `\\nml-fp\EngDesignLib\026\026945.007\*B26945*.pdf`

The intended output is 
`\\EngDesignLib\026\026945.007\B26945.idw`
`\\EngDesignLib\026\026945.007\B26945.ipt`
`\\EngDesignLib\026\026945.007\B2694501.pdf`
powershell get-childitem
2个回答
0
投票

您的

Test-Path $pdfFilePath
(其中
$pdfFilePath
等于,例如
\\nml-fp\EngDesignLib\026\026945.007\*B26945*.pdf
)回答了问题:

是否存在与该模式匹配的文件存在

但听起来你真正想问的问题是:

与此模式匹配的文件的名称是什么?

要回答您可以将您的

If (Test-Path $pdfFilePath) { ... }
替换为:

    $pdf = Get-ChildItem -Path $pdfFilePath
    if( $null -ne $pdf )
    {
        Write-host "PDF File and Path Found" $filePdf "PATH-->" $pdf.FullName
    }

注意 - 可能有多个匹配项,但上面的代码假设最多只有一个。如果您有多个匹配项,则需要以不同的方式处理...

如果我在我的机器上运行它,我会得到以下输出:

Path C:\src\so\test\B26945.idw
PDF File and Path Found *B26945*.pdf PATH--> C:\src\so\test\B2694501.pdf

其中显示文件名而不是搜索模式。


0
投票

-Filter
已经满足您的需要,没有理由使用
-Include

# Set the known part of the name
$KnownPart = 'TAX45'

# Recursively get all files having that part in their name, with anything before or after
Get-ChildItem -Path $PathEngDesign -Filter *$KnownPart* -Recurse -ErrorAction SilentlyContinue -Force | 
    ForEach-Object { 
        # Tests if there is a Item that has the same name but with PDF as extension. This includes the PDF files themselves, so you get all.
        if (Test-Path -PathType Leaf ( Join-Path -Path $_.DirectoryName -ChildPath "$($_.basename).pdf"  )) {
            # prints the full name. Or whatever you want.
            $_.FullName
        } 
    }
© www.soinside.com 2019 - 2024. All rights reserved.