对 Hashtable 进行排序并将其分配给 Powershell 中的新变量 [英] Sort Hashtable and assign it to a new variable in Powershell

查看:101
本文介绍了对 Hashtable 进行排序并将其分配给 Powershell 中的新变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用以下命令将已排序的 hasttable 分配给新变量.我正在使用以下命令

I would like to know how to assign a sorted hasttable using the following command to a new variable. I am using the following command

$ht =   @{ 
           1 = "Data1"; 
           3 = "Data3"; 
           2 = "Data2"; 
         }

$htSorted = $ht.GetEnumerator() | Sort-Object Name

但运行后我无法遍历结果哈希表

but after running it i can't traverse on the resultant hashtable

foreach($key in $htSorted.Keys)
{
     $item[$key]
}

有什么想法吗?

推荐答案

如果你需要一个排序的哈希表,你可以使用 SortedDictionary.示例:

In case you need to have a sorted hashtable, you can use SortedDictionary. Example:

$s = New-Object 'System.Collections.Generic.SortedDictionary[int, string]'
1..20 | % { 
  $i = (Get-Random -Minimum 0 -Maximum 100)
  write-host $i
  $s[$i] = $i.ToString() 
}
$s

我创建了 20 个随机值并将它们存储在字典中.然后,当 PowerShell 遍历字典时(通过 GetEnumerator()),值按键排序.

I created 20 random values and stored them in the dictionary. Then when PowerShell is going through the dictionary (via GetEnumerator()), the values are sorted by keys.

它可能比使用旧的哈希表和通过 Sort-Object 排序快得多.

It will be probably much faster than using old hashtable and sorting via Sort-Object.

这篇关于对 Hashtable 进行排序并将其分配给 Powershell 中的新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆