Monday, January 14, 2019

Sorting Array and Hashtable in PowerShell

It's different, but both are quite simple.


  • Array

$array=@()
Get-Service -PipelineVariable Service | %{
$arrayItem = [pscustomobject]@{
DisplayName = $Service.DisplayName
Name = $Service.Name
}
$array += $arrayItem

$array | Sort-Object displayname

"Measure-Command {$array | Sort-Object displayname}" took around 3 milliseconds, for 203 items.

Or,

Get-Service | Sort-Object -Property DisplayName | %{
  [pscustomobject]@{
    DisplayName = $_.DisplayName
    Name = $_.Name
  }


  • Hashtable

$hashtable = @{}
Get-Service -PipelineVariable Service | %{
$hashtable[$Service.Name] = $Service.DisplayName
$hashtable.GetEnumerator() | sort -Property value

"Measure-Command {$hashtable.GetEnumerator() | sort -Property value}" took around 5 milliseconds, for 203 items.


No comments:

Post a Comment