Trying to import CSV that has columns of ID, Start Date, End Date where each row could contain the same ID value but different dates.
Want to sort this so it's finding the earliest date for each ID AND the latest End date for that same ID, then write that to a CSV.
Input csv:
ID | Start Date | End Date |
---|---|---|
100 | 01-Apr-2021 | 23-May-2021 |
100 | 10-June-2021 | 30-Dec-2021 |
200 | 12-Aug-2021 | 23-Sep-2021 |
200 | 25-Dec-2021 | 24-May-2022 |
Output csv:
ID | Start Date | End Date |
---|---|---|
100 | 01-Apr-2021 | 30-Dec-2021 |
200 | 12-Aug-2021 | 24-May-2022 |
I thought I could import CSV, then identify ID and then for each ID sort start and end dates but can't seem to get it to work.
Code thus far:
$source = "C:\test\test.csv"
$outPut = "C:\test\Testsort.csv"
$csv = Import-Csv $source
Foreach ($usr in $csv){
$userID= $usr."ID"
$filtered = $csv | Where-Object {($_.'ID') -eq $userID}
$output = [pscustomobject]@{
'ID' = $userID
'Start Date' =($filtered.'Start Date' | Sort-Object @{Expression=
{[datetime]($_."Start Date")};Descending=$false} | Select -First 1
'End Date' =($filtered.'Start Date' | Sort-Object @{Expression=
{[datetime]($_."End Date")};Descending=$True} | Select -Last 1
}
}
$output | Export-csv $outPut
Sadly I'm struggling with the sorting of start and end dates per ID and setting a value of earliest and oldest per ID.
Any thoughts?