First of all I'll supply my code and then explain.
$toImport = gci "\\server\folder\*" -include "Examplefile*.txt"
$toImport = $toImport.fullname
$date_of_file = @()
foreach($item in $toImport){
$date_of_file += (split-path $item -leaf).substring(11,6)
}
write-host ($date_of_file | sort-object)
I am getting filenames with get-childitem, then just putting their full path into an array. My $toImport
variable holds the filepaths and it looks like:
\\server\folder\Examplefile010220.txt
\\server\folder\Examplefile010320.txt
\\server\folder\Examplefile010420.txt
\\server\folder\Examplefile010520.txt
\\server\folder\Examplefile120919.txt
I then use split-path
on it to get just the filename where I can run .substring()
on it to extract the dates and then I add those dates into variable $date_of_file
, which using the above example will hold these values... 010220 010320 010420 010520 120919
I tried to then sort these dates in ascending order because I have a later part of my script that will process the files but they must be done in order.
Some things I've tried to fix the above posted script: (get-date -date $date_of_file | sort-object)
($date_of_file.ToString('MMddyy') | sort-object)
$date_of_file += ((split-path $item -leaf).substring(11,6) ).toString("MMddyy")
$date_of_file += get-date -date ((split-path $item -leaf).substring(11,6) )
($date_of_file | Sort-Object { $_. -as [datetime] })
$date_of_file += [datetime]::parseexact(((split-path $item -leaf).substring(11,6) ), 'MMddyy', $null).ToString('MMddyy')
How can I get this to sort by date in ascending order? So far every time I try something I'm running into errors or this date is still at the end of the list, '120919', when it should be first.
================= UPDATE
$toImport = gci "\\server\folder\*" -include "Examplefile*.txt"
$toImport = $toImport.fullname
cls
$date_of_file = @()
foreach($item in $toImport){
$date_of_file += [datetime]::parseexact(((split-path $item -leaf).substring(11,6) ), 'MMddyy', $null)
}
write-host ($date_of_file | Sort-Object)
This bit seems to work but it's putting the format of the dates into a format that looks like Thursday, January 2, 2020 12:00:00 AM
. and I tried to do .ToString('MMddyy') on the result but I'm getting this error Cannot find an overload for "ToString" and the argument count: "1".