Share via


Learning Powershell, sort a CSV file by date

Question

Thursday, April 2, 2015 9:02 PM

I'm scraping Subject, ReceivedTime and Sender from an Outlook Inbox that I'm trying to develop some monitoring for.

The captured data is dumped to a CSV for experimenting with.

What I'm trying to do now is sort the data by date.

A sample of the file is

#TYPE Selected.System.__ComObject
"SenderName","ReceivedTime","Subject"
"fname lname","3/31/2015 2:24:03 PM","ShadowProtect job success on SERVER1"
"fname lname,","3/31/2015 2:09:04 PM","ShadowProtect job success on PC"
"Partner Program","3/31/2015 2:07:59 PM","Partner Update - Your Accounts Require Action"
"fname lname,","3/31/2015 1:57:23 PM","ShadowProtect job success on SERVER2"
"[email protected]","3/31/2015 1:54:29 PM","ShadowProtect backup failure on 2K11- gram APP -"
"[email protected]","3/31/2015 1:52:52 PM","Bootable Screenshot for SERVER-2 on RVPEL-CH (00044E665CCF)

I've gotten to the point where the dates can be sorted by casting as datetime. 

Import-Csv .\RVPEL-mail.txt | Where-Object {$_.Subject -like "*xxx*"} | Select-Object -Property Subject, ReceivedTime | ForEach-Object {[DateTime]$_.ReceivedTime} | Sort-Object

...and of course the output is only a column of sorted dates

Any guidance how I can have the output with additional columns and still sorted by date?

Thank you

All replies (4)

Thursday, April 2, 2015 9:56 PM ✅Answered

Hi,

you just have to add a property of type DateTime, and then sort. Modify your code as this :

Import-Csv .\RVPEL-mail.txt |
   Where-Object {$_.Subject -like "*xxx*"} |
   Select-Object -Property Subject, ReceivedTime,
      @{label='DateReceivedTime';
         expression={[DateTime]$_.ReceivedTime}} |
sort DateReceivedTime

hope this helps


Thursday, April 2, 2015 10:37 PM ✅Answered

As per Leif ...

$sorted=Import-Csv  .\RVPEL-mail.txt | select *,@{N='SortTime';E={[datetime]($_.ReceivedTime)}} | sort sorttime

¯\(ツ)_/¯


Thursday, April 2, 2015 9:57 PM

Select ReceivedTime as a calculated property and remove ForEach-Object.


Monday, April 6, 2015 1:43 PM

Thank you Leif-Arne and Sébastien. Just exactly what I needed to learn. Now able to sort by date/time received.