Home > Software design >  Hash value not injecting other variable's value in powershell
Hash value not injecting other variable's value in powershell

Time:05-09

I have a hashtable like below in powershell

 $children = @{'key'='value\\$child\\Parameters'}
 

Now consider the below:

$child = "hey"
$parent = "$child ho"

Write-Host $parent

This prints

hey ho

so basically the string $parent is able to use the string $child defined. When expecting the same behavior from the value of the hashtable, this doesn't happen. For example:

$child = "hey"
$children = @{'key'='value\\$child\\Parameters'}

$children.GetEnumerator() | ForEach-Object {
$param = $_.Value
Write-Host $param
} 

This prints

 value\\$child\\Parameters 

instead of making use of $child and printing value\\hey\\Parameters I thought it might be because of the type so I tried using | Out-String and |% ToString with $_.Value to convert in to string but it still doesn't work. Any way to make use of $_.Value and still have the $child value injected?

Apologies but my vocab is more java-like than powershell.

CodePudding user response:

The problem here is with quotes. If you change the single quotes to double quotes you can see the interpolation will work as expected.

$child = "hey"
$children = @{"key"="value\\$child\\Parameters"}

Here is the relevant part from the documentation which explain this behaviour.

Single-quoted strings

A string enclosed in single quotation marks is a verbatim string. The string is passed to the command exactly as you type it. No substitution is performed.

Double-quoted strings

A string enclosed in double quotation marks is an expandable string. Variable names preceded by a dollar sign ($) are replaced with the variable's value before the string is passed to the command for processing.

  • Related