Home > Enterprise >  PowerShell Array Filter
PowerShell Array Filter

Time:01-24

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.

CodePudding user response:

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 { $_ }
  • Related