I have this line in a Powershell script:
if (Select-String -Path "$holidays" -Pattern "(?<!\*)$datestr" -SimpleMatch -Quiet)
$holidays is a text file where i have some date:
2023-09-04
2023-11-23
*2023-11-24
2023-12-25
$datestr is today date: 2023-11-23
why negative lookbehind pattern doesn't work in the line above?
I just want to esclude (don't match) all dates that start with *
I think that something is wrong in negative lookbehind because the line:
if (Select-String -Path "$holidays" -Pattern $datestr -SimpleMatch -Quiet)
works perfectly --> results is true
in the first line results is false
As explained in comments, when -SimpleMatch
is used the cmdlet doesn't use regex:
Indicates that the cmdlet uses a simple match rather than a regular expression match. In a simple match,
Select-String
searches the input for the text in the Pattern parameter. It doesn't interpret the value of the Pattern parameter as a regular expression statement.
In your case the cmdlet is looking for a literal (?<!\*)2023-11-23
instead of 2023-11-23
not preceded by *
:
$datestr = '2023-11-23'
'2023-11-23' | Select-String -Pattern "(?<!\*)$datestr" -SimpleMatch -Quiet # No output
'2023-11-23' | Select-String -Pattern "(?<!\*)$datestr" -Quiet # True
In summary, your condition should be:
if (Select-String -Path $holidays -Pattern "(?<!\*)$datestr" -Quiet) {
# do stuff
}