Home > Back-end >  Sort-Object: Can it use an object's method result for sorting?
Sort-Object: Can it use an object's method result for sorting?

Time:01-17

Using Add-Member I added a tiny method to an array of objects to calculate sort of a hash from a string:

$arr | Add-Member -MemberType ScriptMethod -Name 'SortedName' -Value {
    [string]$name = $this.Name
    [int]$start = [int][char]$name[0];
    [int]$index = [int]($name -replace '^. ?(\d )\.[^.] $','$1')

    [int]"$start$('{0:D4}' -f $index)"
}

Now I'd like to sort the array using $arr | Sort-Object -PropertyName 'SortedName'. But that doesn't seem to work as expected.

How can I apply Sort-Object on an array's methods?

CodePudding user response:

To invoke methods on each element you need to use a calculated expression.

For example:

$arr = 0..10 | ForEach-Object {
    [pscustomobject]@{ Name = 'Test'   (Get-Random -Maximum 20) }
}

$arr | Add-Member -MemberType ScriptMethod -Name SortedName -Value {
    [int] ($this.Name -replace '\D ')
}

$arr | Sort-Object { $_.SortedName() }
  • Related