Brian
Brian

Reputation: 13571

How can I test file existence using regular expressions

I want to test if the file C:\workspace\test_YYYYMMDD.txt, where YYYYMMDD means year, month, and date, exists on my disk.

How can I do this in PowerShell?

I know that test-path test_*.txt command returns true.

But test_*.txt also returns true when the file name is something like test_20170120asdf.txt, or test_2015cc1119aabb.txt.

I don't want file names like test_20170120asdf.txt being marked as true in test-path.

I'd like to apply regular expression test_\d{8}\.txt in test-path. How can I do this in PowerShell?

Upvotes: 1

Views: 1143

Answers (2)

user6811411
user6811411

Reputation:

Something like:

gci C:\workspace\test_*.txt | ? {$_.Name -match '^test_\d{8}\.txt$'}

Upvotes: 3

mklement0
mklement0

Reputation: 437121

Wildcard expressions are much more limited in their matching abilities than regular expressions - see Get-Help about_Wildcards - but in this particular case they're enough:

Test-Path test_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9].txt

If more sophisticated matching is needed, see LotPing's answer, which shows how to use regular expressions.

Upvotes: 1

Related Questions