如何使用包含正则表达式的Test-Path

3

我想检查特定目录(文件夹名称为16位数字)中是否存在Test.txt文件。

例如,我尝试使用以下命令:

Test-Path "C:\Users\<USERNAME>\Desktop\Test\([0-9]{16})\Test.txt"

在我的情况下,无法使用以下命令。

 Test-Path "C:\Users\<USERNAME>\Desktop\Test\*\Test.txt"

谢谢你!


除了通配符?*,您可以在文件夹/文件名中使用范围[0-9],但这并不意味着您可以在此处使用完整的正则表达式。理论上,您可以使用[0-9][0-9][0-9][0-9][0-9]...,但我记得可用范围数量有限制。 - user6811411
2个回答

3
这是一种实现方法:
# This is for PowerShell version 3.0 and up. If you are using an older version, use
# Get-ChildItem -Path "C:\Users\<USERNAME>\Desktop\Test" | Where-Object { $_.PSIsContainer -and $_.Name -match '\d{16}' }

Get-ChildItem -Path "C:\Users\<USERNAME>\Desktop\Test" -Directory | Where-Object { $_.Name -match '\d{16}' } | 
    ForEach-Object {
        $fileName = Join-Path -Path $_.FullName -ChildPath 'Test.txt'
        if (Test-Path -Path $fileName -PathType Leaf) {
            Write-Host "$fileName exists"
        }
        else {
            Write-Host "$fileName does not exist"
        }
    }

1

Test-Path会返回$True/$False,要实现类似的功能,您可以这样做:

((Get-ChildItem "C:\Users\<USERNAME>\Desktop\Test\*\Test.txt" | 
    where FullName -match "\\Test\\\d{16}\\Test.txt$").Count -gt 0)

但这并不会显示哪些文件夹匹配。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接