Search code examples
stringpowershellhashtable

add entry in hashtable from string in Powershell


I have a string like this, retrieved from a txt file:

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

$Printername
NAME="W018"

So I thought I could easily add this to a hashtable:

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

but this is not working.

Either this:

$HashPrinter = @{$PRINTERNAME}

If I type it manually:

$HashPrinter = @{NAME="W018"}

it works as expected. What I am doing wrong?


Solution

  • 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