Marc Trottier
Marc Trottier

Reputation: 15

Powershell sort-by numbers at end of values

I'm looking to sort numerically my output with the numbers at the end of each.

Get-ADComputer -Filter * -SearchBase "OU=ComputerOU,DC=dc,DC=com" -Properties * | Select-Object -ExpandProperty Name

What i would like:
QCL-00010
JPL-00011
TUL-00012
TUL-00013
QCL-00014

What i have:
JPL-00011
QCL-00010
QCL-00014
TUL-00012
TUL-00013

Thank you in advance

Upvotes: 0

Views: 389

Answers (3)

Theo
Theo

Reputation: 61068

Using the example names, where all numeric values have the same length, padded with leading zeroes, you could simply extend the code you have:

Get-ADComputer -Filter * -SearchBase "OU=ComputerOU,DC=dc,DC=com" | 
    Select-Object -ExpandProperty Name | 
    Sort-Object {($_ -split '-')[-1]}

However, to be on the safe side I'd cast to [int] as well:

Get-ADComputer -Filter * -SearchBase "OU=ComputerOU,DC=dc,DC=com" | 
    Select-Object -ExpandProperty Name | 
    Sort-Object {[int]($_ -split '-')[-1]}

Result:

QCL-00010
JPL-00011
TUL-00012
TUL-00013
QCL-00014

BTW. if all you need is the .Name property, do not ask for ALL properties with -Properties *

Upvotes: 1

Steven
Steven

Reputation: 7057

There are a couple of ways to do something like this, somewhat depending on how static the format is.

$Names = @(
    'JPL-00011'
    'QCL-00010'
    'QCL-00014'
    'TUL-00012'
    'TUL-00013'
)

$Names | Sort-Object {[Void]($_ -match "(\d{5}$)"); $matches[1]}

Here I used the matches collection as the sort expression.

Upvotes: 0

Bacon Bits
Bacon Bits

Reputation: 32155

If every computer in the OU matches the nomenclature, I would just use a calculated property with Sort-Object and some pretty standard text munging:

Get-ADComputer -Filter * -SearchBase "OU=ComputerOU,DC=dc,DC=com" |
Sort-Object -Property @{e={$_.Name.Substring($_.Name.IndexOf('-') + 1)}} | 
Select-Object -ExpandProperty Name

Also, you should avoid -Properties * with Get-AD* commands unless you absolutely have to. Name is returned by default.

Upvotes: 0

Related Questions