Powershell 如何使用包含正则表达式的测试路径

Powershell 如何使用包含正则表达式的测试路径,powershell,Powershell,我想检查文件Test.txt是否存在于特定目录中(文件夹名为16位) 例如,我尝试了以下命令: Test-Path "C:\Users\<USERNAME>\Desktop\Test\([0-9]{16})\Test.txt" 测试路径“C:\Users\\Desktop\Test\([0-9]{16})\Test.txt” 以下命令不能在我的情况下使用 Test-Path "C:\Users\<USERNAME>\Desktop\Test\*\Test.txt"

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

例如,我尝试了以下命令:

Test-Path "C:\Users\<USERNAME>\Desktop\Test\([0-9]{16})\Test.txt"
测试路径“C:\Users\\Desktop\Test\([0-9]{16})\Test.txt”
以下命令不能在我的情况下使用

 Test-Path "C:\Users\<USERNAME>\Desktop\Test\*\Test.txt"
测试路径“C:\Users\\Desktop\Test\*\Test.txt”

谢谢大家!

这是一种方法:

# 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"
        }
    }
#这适用于PowerShell 3.0及更高版本。如果您使用的是旧版本,请使用
#获取ChildItem-Path“C:\Users\\Desktop\Test”|其中对象{$\u.PSIsContainer-和$\u.Name-match'\d{16}}
获取ChildItem-Path“C:\Users\\Desktop\Test”-目录|其中对象{$\名称-match'\d{16}}}
ForEach对象{
$fileName=Join Path-Path$\ux.FullName-ChildPath'Test.txt'
if(测试路径-路径$fileName-路径类型叶){
写入主机“$fileName存在”
}
否则{
写入主机“$fileName不存在”
}
}

测试路径
将返回$True/$False,以实现类似的操作:

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

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

除了通配符
?*
之外,您可以在文件夹/文件名中使用范围
[0-9]
,但这并不意味着您可以在此处使用完整的正则表达式。理论上,您可以使用
[0-9][0-9][0-9][0-9][0-9]…
,但IIRC对可用范围的数量有限制。