PowerShell: Sort-Object descending wrong order

1.4k Views Asked by At

We currently have the following folder structure:

C:\Packages\Adobe\DC\9.2.2
C:\Packages\Adobe\DC\10.0.3
C:\Packages\Adobe\DC\10.0.8

C:\Packages\Microsoft\Edge\6.1.10
C:\Packages\Microsoft\Edge\6.1.18
C:\Packages\Microsoft\Edge\6.1.20

With a PowerShell script I try to keep only the highest version of the respective application folder and delete all others. The result should be:

C:\Packages\Adobe\DC\10.0.8

C:\Packages\Microsoft\Edge\6.1.20

However, the sorting doesn't seem to work properly in my script.

$folders_root = Get-ChildItem -Path C:\Packages -Directory

foreach ($folder in $folders_root)
{
    $folders_appilcation = Get-ChildItem $folder.FullName -Directory

    foreach ($app_folder in $folders_appilcation)
    {
        $versionfolder = Get-ChildItem $app_folder.FullName -Directory | Sort-Object -Descending | Select-Object -Skip 1 | % {Write-host "Deleting $($_.FullName)"<#;  Remove-Item $_.FullName#>}

    }
}

For the path "C: \ Packages \ Adobe \ DC" 9.2.2 is considered as the highest version (according to the script) but it should be 10.0.8.

Deleting C:\Packages\Adobe\DC\10.0.8
Deleting C:\Packages\Adobe\DC\10.0.3
Deleting C:\Packages\Microsoft\Edge\6.1.18
Deleting C:\Packages\Microsoft\Edge\6.1.10

Can someone tell me what I'm doing wrong?

2

There are 2 best solutions below

1
On BEST ANSWER

Sort is comparing strings and not numbers. When you compare the string 10 and 9 it will interpret the 10 as a 1.

Force the sort to us it as version, try something like that:

sort {[version]::Parse(($_.split("\"))[-1])} -Descending
0
On

Thank you. The following code works perfectly:

$folders_root = Get-ChildItem -Path \\hkt-cmgmt01a\d$\Empirum\Configurator\Packages -Directory

foreach ($folder in $folders_root)
{
    $folders_appilcation = Get-ChildItem $folder.FullName -Directory

    foreach ($app_folder in $folders_appilcation)
    {
        $versionfolder = Get-ChildItem $app_folder.FullName -Directory | Sort-Object { [version] $_.Name } -Descending -ErrorAction SilentlyContinue| Select-Object -Skip 1 | % {Write-host "Deleting $($_.FullName)"<#;  Remove-Item $_.FullName#>}

    }
}