0

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.

Sonali Gupta
  • 494
  • 1
  • 5
  • 20
  • In short: Only `"..."` strings (double-quoted aka _expandable strings_) perform string interpolation (expansion of variable values) in PowerShell, not `'...'` strings (single-quoted aka _verbatim strings_). If the string value itself contains `"` chars., escape them as `\`"` or `""`, or use a double-quoted _here-string_. See the conceptual [about_Quoting_Rules](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Quoting_Rules) help topic. – mklement0 May 09 '22 at 13:29

1 Answers1

3

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.

Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46