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.

1
  • 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 help topic. Commented May 9, 2022 at 13:29

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.