当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 使用 PowerShell 哈希表的初学者指南

作者:精品下载站 日期:2024-12-14 13:12:21 浏览:13 分类:玩电脑

使用 PowerShell 哈希表的初学者指南


第一次接触哈希表时,您可能想知道它们是什么以及它们如何在脚本或命令中发挥关键作用。不用担心!本教程向您介绍如何开始使用 PowerShell 哈希表。

简而言之,哈希表允许您使用键值对存储和操作数据,可以快速有效地访问数据。在本教程中,您将学习哈希表的基础知识以及如何将它们用于 PowerShell 脚本和命令。

继续阅读并开始使用 PowerShell 哈希表扩展您的技能!

先决条件

本教程将是一个实践演示。要继续操作,请确保您的系统安装并配置了 PowerShell v5+。本教程使用带有 PowerShell 7 的 Windows 10,但其他版本的 PowerShell 和 Windows 也可以使用。

创建 PowerShell 哈希表

在某些时候,检索特定数据可能会变成“大海捞针”的情况。但使用哈希表,您可以在广泛的数据集合中快速搜索特定项目。

在 PowerShell 中,哈希表是灵活的数据结构,可用于多种用途,例如存储配置数据、将参数传递给 cmdlet 以及在脚本中存储数据。

要了解 PowerShell 哈希表的工作原理,您首先必须按如下方式创建一个哈希表:

1. 打开 PowerShell 会话,然后运行以下命令,该命令不会产生输出,但声明一个名为 name 的变量来引用空哈希表。

如下所示,与 PowerShell 中的数组类似,哈希表是使用 @ 符号定义的。

$name = @{}

2. 接下来,运行以下命令来验证 name 变量的类型 (GetType())。

$name.GetType()

name变量的类型是Hashtable,如下所示。此信息确认您的哈希表已成功创建。

[玩转系统] 使用 PowerShell 哈希表的初学者指南

3. 验证哈希表后,运行以下代码检查哈希表是否为空。

下面的代码确定 Count 属性是否等于 (-eq) 于 0,并打印相应的消息。

# Compare if the Count property value is equal (-eq) to 0
if ($name.Count -eq 0) {
	# If yes, print the below message.
  Write-Output "The hashtable is empty."
} else {
	# Otherwise, print the message below instead.
  Write-Output "The hashtable is not empty."
}

在下面,您可以看到哈希表是空的,因为您刚刚创建了它,并且其中没有定义键值对。

[玩转系统] 使用 PowerShell 哈希表的初学者指南

将项目添加到 PowerShell 哈希表

您刚刚创建了一个几乎为空的 PowerShell 哈希表,只有在添加项目时该表才有用。如何?通过将键值对添加到哈希表中。

与数组类似,但 PowerShell 哈希表不使用整数作为索引,而是使用键(可以是任何数据类型)来标识值。此功能允许快速插入、检索和删除哈希表中的项目,因为键可以快速找到相应的值。

以下是将键值对添加到 PowerShell 哈希表的语法,其中:

  • $hashtable - 哈希表的名称。
  • $key - 密钥的名称,不区分大小写。例如,“FirstName”和“firstname”将被视为哈希表中的相同键
  • $value - 与键关联的值。
$hashtable[$key] = $value

运行以下代码,该代码不会向控制台生成输出,但会声明键值对,并将它们添加到哈希表中 ($name)。

在哈希表中,键允许您执行哈希函数,该函数将键映射到哈希表内部数据结构中的特定位置。

? 哈希表值可以是任何类型,例如数字、字符串、数组、对象和其他数据类型作为哈希表中的值。

# Declare the key FirstName
$key = "FirstName"
# Declare the value of the key
$value = "John"
# Add the item to the hashtable
$name[$key] = $value

# Declare the key LastName
$key = "LastName"
# Declare the value of the key
$value = "Doe"
# Add the item to the hashtable
$name[$key] = $value

现在,重新运行下面的代码来检查哈希表是否为空。

if ($name.Count -eq 0) {
  Write-Output "The hashtable is empty."
} else {
  Write-Output "The hashtable is not empty."
}

如下所示,您将收到一条消息,说这次哈希表不为空。

[玩转系统] 使用 PowerShell 哈希表的初学者指南

从 PowerShell 哈希表中检索项目

假设您确信您的哈希表不为空。您如何知道哈希表中存在哪些项目?幸运的是,您也可以从哈希表中检索项目。

运行下面的代码以键值对形式检索并输出(Write-Output)哈希表中的所有项目,每行一个。

# Iterates through all the key-value pairs in the hashtable
foreach ($key in $name.Keys) {
	$value = $name[$key]
  # Outputs all the key-value pairs in the hashtable, one per line.
	Write-Output "${key}: ${value}"
}

[玩转系统] 使用 PowerShell 哈希表的初学者指南

现在,运行以下代码来检索哈希表中的所有项目并将其打印(Write-Output)到控制台。

? 请注意,在本教程中您将经常使用以下代码。您可以通过创建函数来避免多次复制和粘贴相同的代码,但这超出了本教程的范围。

# Get an object that can be used to iterate over the elements of a collection.
$enumerator = $name.GetEnumerator()
foreach ($element in $enumerator) {
	# Outputs a string that includes the key and value of each element in the collection.
	Write-Output "Key: $($element.Key), Value: $($element.Value)"
}

这次,您可以看到列出的项目中哪些是键和值的指示。

[玩转系统] 使用 PowerShell 哈希表的初学者指南

使用预定义值创建哈希表

到目前为止,您只了解了创建空哈希表。但是,如果您知道哈希表中始终需要某些值,则可以使用预定义值创建一个哈希表。

具有预定义值的哈希表可以节省您的时间并使代码更加高效,因为您不必稍后将值添加到哈希表中。

? 请注意,创建哈希表不会产生输出。但不用担心。在本教程中,您将在创建后验证每个哈希表。

1. 运行以下命令创建包含三个键值对的哈希表 ($hashtable1)。

$hashtable1 = @{
  "Key1" = "Value1"
  "Key2" = "Value2"
  "Key3" = "Value3"
}

2. 接下来,运行以下代码来验证新哈希表 (hashtable1) 是否存在。

# Get an object that can be used to iterate over the elements of a collection.
$enumerator = $hashtable1.GetEnumerator()
foreach ($element in $enumerator) {
  # Outputs a string that includes the key and value of each element in the collection.
	Write-Output "Key: $($element.Key), Value: $($element.Value)"
}

您将看到每个键值对的值按预期打印在屏幕上。此输出确认预定义值存储在哈希表中的适当位置。

[玩转系统] 使用 PowerShell 哈希表的初学者指南

3. 现在,运行以下代码,使用循环(或数组)创建具有预定义值的哈希表 ($hashtable2)。

$keys = "Key1", "Key2", "Key3"
$values = "Value1", "Value2", "Value3"
$hashtable2 = @{}
for ($i = 0; $i -lt $keys.Count; $i++) {
  $hashtable2[$keys[$i]] = $values[$i]
}

4. 最后,运行以下代码以验证新哈希表 (hashtable2) 是否已成功创建。

# Get an object that can be used to iterate over the elements of a collection.
$enumerator = $hashtable2.GetEnumerator()
foreach ($element in $enumerator) {
	# Outputs a string that includes the key and value of each element in the collection.
	Write-Output "Key: $($element.Key), Value: $($element.Value)"
}

下面的输出确认了循环方法在使用预定义值创建哈希表时有效。但由于这些项目是随机列出的,请跳至以下部分进行修复。

[玩转系统] 使用 PowerShell 哈希表的初学者指南

在哈希表中创建项目的有序列表

默认情况下,哈希表中的项目不按特定顺序存储。但是如果您需要一个有序列表怎么办?您还可以在哈希表中创建项目的有序列表,以按特定顺序排列数据。

要在哈希表中创建项目的有序列表,请使用 [ordered] 属性,如下所示:

1. 运行以下代码以在哈希表 ($hashtable3) 中创建一个 [ordered] 项目列表。

$hashtable3 = [ordered]@{
"Key1" = "Value3"
"Key2" = "Value2"
"Key3" = "Value1"
}

2. 接下来,运行以下代码来验证哈希表的有序列表是否已成功创建。

# Get an object that can be used to iterate over the elements of a collection.
$enumerator = $hashtable3.GetEnumerator()
foreach ($element in $enumerator) {
	# Outputs a string that includes the key and value of each element in the collection.
	Write-Output "Key: $($element.Key), Value: $($element.Value)"
}

如下所示,列出的项目保持您在创建哈希表时定义的顺序。

使用有序哈希表的一些可能的好处包括但不限于以下内容:

Benefits

描述

Easier to read and debug

元素以可预测的顺序显示,如果您处理大型哈希表的许多元素,这会特别有用。

Improved performance

当以特定顺序频繁访问元素时,有序哈希表可以更有效。

[玩转系统] 使用 PowerShell 哈希表的初学者指南

3. 最后,调用您的有序哈希表 ($hashtable3) 以进一步确认您仍将获得有序的项目列表。

$hashtable3

下面的输出确认,无论您如何访问哈希表,您仍然会获得项目的订单列表。

[玩转系统] 使用 PowerShell 哈希表的初学者指南

更新哈希表中的现有项目

数据不断变化,如果您有现有的哈希表,更新它们是一项至关重要的任务。例如,您使用哈希表来存储配置值。如果是这样,当配置发生变化时,您可能需要更新键的值。

要更新 PowerShell 哈希表,= 赋值运算符将执行以下操作:

1. 运行以下命令,该命令不提供输出,但将 $hashtable3 中键 Key2 的值更新为 NewValue2

$hashtable3["Key2"] = "NewValue2"

接下来,运行以下命令将新的键值对 (Key4=NewValue4) 添加到哈希表 ($hashtable3)。

添加新的键值对不会产生类似于更新哈希表中现有列表的输出,但您将在以下步骤中验证更改。

$hashtable3.Add("Key4", "NewValue4")

3. 运行以下代码以验证哈希表 ($hashtable3) 中的键值是否已更新。

# Get an object that can be used to iterate over the elements of a collection.
$enumerator = $hashtable3.GetEnumerator()
foreach ($element in $enumerator) {
	# Outputs a string that includes the key and value of each element in the collection.
	Write-Output "Key: $($element.Key), Value: $($element.Value)"
}

[玩转系统] 使用 PowerShell 哈希表的初学者指南

? 在 PowerShell 中,哈希表中的每个键都必须是唯一的。如果您尝试添加哈希表中已有的键值对,您将收到如下错误。为了避免出现此错误,请跳至以下步骤。

[玩转系统] 使用 PowerShell 哈希表的初学者指南

4. 现在,运行以下代码,该代码使用 Contains() 方法在添加键值对之前检查您尝试添加的键是否已存在于哈希表中。

# Define the variable to hold the new key
$newkey="Key5"
# Check if $newkey already exists in the hashtable.
if (-not $hashtable3.Contains($newkey)) {
	# If not, add the new key-value pair.
	$hashtable3.Add($newkey, "NewValue5")
	Write-Output "The new key '$newkey' has been added to the hashtable."
} else {
	# If the key exists, print a message.
	Write-Output "The key '$newkey' already exists."
}

如果新密钥不存在,您将收到以下消息,表明新密钥已添加到哈希表中。

[玩转系统] 使用 PowerShell 哈希表的初学者指南

否则,如下所示,如果您尝试的密钥已存在,您将收到一条消息。

[玩转系统] 使用 PowerShell 哈希表的初学者指南

5. 最后,重新运行以下代码以检索哈希表 ($hashtable3) 中的所有项目。

# Get an object that can be used to iterate over the elements of a collection.
$enumerator = $hashtable3.GetEnumerator()
foreach ($element in $enumerator) {
	# Outputs a string that includes the key and value of each element in the collection.
	Write-Output "Key: $($element.Key), Value: $($element.Value)"
}

在下面,您可以看到新添加的键 (Key5) 以及迄今为止已添加到哈希表中的其他项目。

[玩转系统] 使用 PowerShell 哈希表的初学者指南

从哈希表中删除项目

哈希表中的项目太多,尤其是不必要的项目,可能只会导致混乱。从哈希表中删除不再相关或不再需要的项目会给您带来好处。

假设您的哈希表包含用户及其信息的列表。如果是这样,请从哈希表中删除不再活跃的用户。

运行以下代码从哈希表 ($hashtable3) 中删除特定项目 (Key1)。

$key = "Key5"
if ($hashtable3.Contains($key)) {
  $hashtable3.Remove($key)
  Write-Output "The key-value pair with the key '$key' was removed from the hashtable."
} else {
  Write-Output "The key-value pair with the key '$key' was not found in the hashtable."
}

下面,输出打印一条消息,表明密钥已被删除。但如果密钥不存在,您将收到一条消息,提示未找到密钥。

[玩转系统] 使用 PowerShell 哈希表的初学者指南

现在,运行以下代码来检查哈希表中的所有项目并验证项目删除是否成功。

# Get an object that can be used to iterate over the elements of a collection.
$enumerator = $hashtable3.GetEnumerator()
foreach ($element in $enumerator) {
	# Outputs a string that includes the key and value of each element in the collection.
	Write-Output "Key: $($element.Key), Value: $($element.Value)"
}

下面,您可以验证哈希表中不再存在键为“Key5”的键值对。

[玩转系统] 使用 PowerShell 哈希表的初学者指南

结论

PowerShell哈希表具有键值对结构和快速访问的特点,非常适合管理各种场景下的大量数据。在本教程中,您学习了如何从哈希表中创建、添加、更新和删除项目。所有这些都为您提供了在脚本中有效使用哈希表的技能。

为什么不将您新获得的技能提升到一个新的水平呢?考虑将哈希表合并到脚本中以执行更高级的任务,例如数据操作和转换。或者尝试将哈希表与 PowerShell 中的其他数据结构(例如数组和对象)结合起来,以解决更复杂的问题?

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯