主题
about_Hash_Tables
简短说明
说明如何在 Windows PowerShell 中创建、使用和排序哈希表。
详细说明
哈希表(也称为字典或关联数组)是一种紧凑型数据结构,用于存储一个或多个名称/值对。例如,
哈希表可能包含一系列姓名与职员 ID、计算机名称与 IP 地址,或消息 ID 与消息文本。
哈希表很常用,这是因为哈希表在查找和检索数据时的效率很高。在 Windows PowerShell 中,哈
希表可用来存储列表和创建计算属性。此外,Windows PowerShell 具有 cmdlet ConvertFrom-
StringData,可用于将字符串转换为哈希表。
创建哈希表
哈希表中的各项按名称/值对排列,如下所示:
Msg1="Please enter your password."
Msg2="The path parameter is required."
Msg3="The alias of Get-Command is gcm."
值映射到名称或与名称关联,以便提交名称时 Windows PowerShell 返回相应值。
在 Windows PowerShell 中,哈希表的语法如下:
@{ <name> = <value>; [<name> = <value> ] ...}
创建哈希表时,请遵循以下准则:
- 以 at 符号 (@) 作为哈希表开头。
- 用大括号 ({}) 将哈希表括起。
- 输入一个或多个名称/值对作为哈希表的内容。
- 使用等号 (=) 将每个名称与其值分隔开。
- 使用分号 (;) 分隔名称/值对。
- 如果名称或值包含空格,请将其用引号括起。
例如,上述用户消息的哈希表如下所示:
@{
Msg1="Please enter your password.";
Msg2="The path parameter is required.";
Msg3="The alias of Get-Command is gcm.";
}
若要在脚本和命令中使用哈希表,请将其保存在变量中。该变量的值是一个哈希表对象
(System.Collections.Hashtable),而名称/值对中的每个名称都是该哈希表对象的一个属性。
以下命令将 user-message 哈希表保存在 $a 变量中,并使用点表示法显示这些值。
C:\PS> $a = @{
>> Msg1="Please enter your password.";
>> Msg2="The path parameter is required.";
>> Msg3="The alias of Get-Command is gcm.";
>> }
C:\PS> $a
Name Value
---- -----
Msg1 Please enter your password.
Msg3 The alias of Get-Command is gcm.
Msg2 The path parameter is required.
C:\PS> $a.Msg1
Please enter your password.
哈希表不限于一种数据类型。可以在哈希表中输入任何数据类型,还可以将不同数据类型
合并在一个哈希表中。例如,可以生成一个包含整数、cmdlet 调用和字符串的哈希表。
排序哈希表
要按键或值的字母顺序对哈希表进行排序,请使用哈希表的 GetEnumerator 方法获取哈希表中的
键和值,然后使用 Sort-Object cmdlet 对其进行排序。
例如,以下命令按键的字母顺序对 $a 中的哈希表进行排序。
C:\PS> $a.getenumerator() | sort-object -property key
Name Value
---- -----
Msg1 Please enter your password.
Msg2 The path parameter is required.
Msg3 The alias of Get-Command is gcm.
以下命令使用同一方法按降序对哈希值进行排序。
C:\PS> $a.getenumerator() | sort-object -property value
-descending
Name Value
---- -----
Msg2 The path parameter is required.
Msg3 The alias of Get-Command is gcm.
Msg1 Please enter your password.
ConvertFrom-StringData
ConvertFrom-StringData cmdlet 将名称/值对的字符串或 here-string 转换为哈希表。可
以在脚本的 Data 节中安全地使用 ConvertFrom-StringData cmdlet,还可以将该 cmdlet 与
Import-LocalizedData cmdlet 一起使用,从而以当前用户的用户界面 (UI) 区域性显示用户
消息。
当哈希表中的值包含引号时,Here-string 尤为有用。(有关 here-string 的详细信息,请参
阅 about_Quoting_Rules。)
以下示例说明如何为上例中的用户消息创建 here-string,以及如何使用 ConvertFrom-
StringData 将其从字符串转换为哈希表。
以下命令创建名称/值对的 here-string,然后将其保存在 $string 变量中。
C:\PS> $string = @"
Msg1="Please enter your password."
Msg2="The path parameter is required."
Msg3="The alias of Get-Command is gcm."
"@
以下命令使用 ConvertFrom-StringData cmdlet 将 here-string 转换为哈希表。
C:\PS> convertfrom-stringdata $string
Name Value
---- -----
Msg3 "The alias of Get-Command is gcm."
Msg2 "The path parameter is required."
Msg1 "Please enter your password."
另请参阅
about_Arrays
about_Quoting_Rules
about_Script_Internationalization
ConvertFrom-StringData
Import-LocalizedData