从 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"}

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

解决方法

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