简体   繁体   中英

How do you code in Powershell to get the latest date from an array?

I have folders as follow: - 10-17-17 - 10-18-17 - 10-19-17 - 10-20-17

I wanted to have PS to spit out that 10-20-17 is the latest folder located in my folder structure. I have no clue to go from here:

$path = "C:\Users\JJames\Desktop\Folder Structure Test"

$todaydate = Get-Date -Format "MM-dd-yy"

$arr = Get-ChildItem $path | 
       Where-Object {$_.PSIsContainer} | 
       Foreach-Object {$_.Name}

I was able to get it spit out the names of each folder.

You should be able to sort the object:

$path = "C:\Users\JJames\Desktop\Folder Structure Test"

$todaydate = Get-Date -Format "MM-dd-yy"

$folders = Get-ChildItem $path | 
    Where-Object {$_.PSIsContainer}

$folders | Sort-Object { [DateTime]::Parse($_.Name)} -Descending

That's the short way, without error handling for date formats.

To get only the first item (sticking with super quick and easy)

 ($dateStrings | Sort{ [DateTime]::Parse($_.Name)} -Descending)[0]

try this:

$path = "C:\temp"
$dirDate=New-Object DateTime

Get-ChildItem $path -Directory | %{

    if ([DateTime]::TryParseExact($_.Name, 
                                    "MM-dd-yy", 
                                    [System.Globalization.CultureInfo]::InvariantCulture, 
                                    [System.Globalization.DateTimeStyles]::None,
                                    [ref] $dirDate)
       )
    {
        $_ | Add-Member -MemberType NoteProperty "DateName" -Value $dirDate
        $_
    }

} | sort DateName -Descending | select -First 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM