首页 > 解决方案 > 从Powershell中的字符串添加哈希表中的条目

问题描述

我有一个这样的字符串,从 txt 文件中检索:

$txtindex = 5
$PRINTERNAME = get-content $txtPrinterfile | select -Index $txtindex
$PRINTERNAME = $PRINTERNAME.Trim()
$PRINTERNAME = $PRINTERNAME.Replace(" ","")

$Printername
NAME="W018"

所以我想我可以轻松地将其添加到哈希表中:

$HashPrinter = @{}
$HashPrinter.Add($PRINTERNAME)

但这不起作用。

要么:

$HashPrinter = @{$PRINTERNAME}

如果我手动输入:

$HashPrinter = @{NAME="W018"}

它按预期工作。我做错了什么?

标签: stringpowershellhashtable

解决方案


PS C:\Users\alHaos> $HashTable = @{}
PS C:\Users\alHaos> $HashTable.Add("Name", "Pr001")
PS C:\Users\alHaos> $HashTable.Add("Manufacture", "Epson")
PS C:\Users\alHaos> $HashTable

Name                           Value
----                           -----
Name                           Pr001
Manufacture                    Epson

推荐阅读