Using sort-object
seems like the right way to go about it, but your foreach
is not using the sorted list. I'd add another |
to pipe the output from sort-object
to the foreach
.
get-childitem -path c:\users\tom\ -filter "*.journal" |
sort-object -property creationtime |
where-object { $_.Name -match "Daily_Reviews\[\d{1,12}-\d{1,12}\].journal" } |
foreach-object {
# $_ is the file we're currently looking at
write-host $_.Name
}
The first command is get-childitem
. It outputs a list of files in no particular order.
The unordered list of files is piped to sort-object
. It outputs the same list of files but now sorted by creationtime.
The sorted list of files is piped to where-object
. It outputs the filtered list of files, still sorted.
The filtered & sorted list of files is piped to foreach-object
, so the body of foreach
is run once for each file, with $_
being the file that's currently being processed. In this code I've written out the file name, but of course you would replace that with whatever you want to do with the file.