2

I have an array piped into PowerShell. Trying to select what matches today through the next 3 weeks.

1/4/2023    First Last
1/11/2023   First Last
1/19/2023   First Last
1/25/2023   First Last
2/1/2023    First Last
2/8/2023    First Last
2/15/2023   First Last
2/22/2023   First Last
3/1/2023    First Last
3/8/2023    First Last

Expected results would be:

1/19/2023   First Last
1/25/2023   First Last
2/1/2023    First Last
2/8/2023    First Last

Was trying to modify this to get results, but not getting what I need.

$referenceDate = (Get-Date).AddDays(21)
Get-Content -Path 'Dates.ini' |
Where-Object { $_ -match '^(\d{2}/\d{2}/\d{4})' } |
Where-Object { [datetime]::ParseExact($matches[1], 'MM/dd/yyyy', $null) -gt $referenceTime } |
ForEach-Object {
    $_
    #DO SOMETHING.. For demo just output the line(s) that matched
}

My PowerShell kung foo is not strong, and would be very grateful for the answer...

Listed in details. PowerShell version is default for Server 2019.

1 Answer 1

4

I would definitely consider using a switch here with the -Regex flag:

$referenceDate = (Get-Date).AddDays(21)

switch -Regex -File Dates.ini {
    '^(?:\d{1,2}/){2}\d{4}' {
        $date = Get-Date $Matches[0]
        if($date -ge [datetime]::Today -and $date -le $referenceDate) {
            $_
        }
    }
}

Regarding your code, it's almost correct, there are 3 problems:

  1. The regex needs a bit tweaking.
  2. The call to ParseExact is not using the correct Date Format.
  3. You're currently filtering for dates greater than 3 weeks, instead what you want is lower than or equal to 3 weeks and greater than or equal to Today.
$referenceDate = (Get-Date).AddDays(21)

Get-Content -Path 'Dates.ini' |
    Where-Object { $_ -match '^(\d{1,2}/\d{1,2}/\d{4})' } |
    Where-Object {
        $date = [datetime]::ParseExact($Matches[1], 'M/d/yyyy', $null)
        $date -ge [datetime]::Today -and $date -le $referenceDate
    } | ForEach-Object { $_ }
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much! Going to give this a try today :). I will report back in a few hours.
Thank you so very much! This helped me get to my end goal. Greatly appreciated!
@slacker220 my pleasure, just saw the previous comment :P thanks for accepting the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.