Your code fundamentally doesn't do what you intend it to do, due to the mistaken use of Write-Host
:
# !! Doesn't capture anything in $var, prints directly to the screen.
$var=Write-host '$'text[$i]
$var # !! is effectively $null and produces no output.
See the bottom section for details.
Instead, what you want is an expandable string (aka interpolating string, "..."
-enclosed), with selective `
-escaping of the $
character you want to be treated verbatim:
$var= "`$text[$i]" # Expandable string; ` escapes the $ char., $i is expanded
$var
There are other ways to construct the desired string:
$var = '$text[{0}]' -f $i
, using -f
, the format operator.
$var = '$' + "text[$i]"
, using string concatenation with +
but the above approach is simplest in your case.
As for what you tried:
Write-Host
is typically - and definitely in your case - the wrong tool to use, unless the intent is to write to the display only, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, or redirect it to a file. To output a value, use it by itself; e.g., $value
instead of Write-Host $value
(or use Write-Output $value
, though that is rarely needed); see this answer.
What you thought of as a single argument, '$'text[$i]
, was actually passed as two arguments, verbatim $
and expanded text[$i]
(e.g., text[0]
) and because Write-Host
simply space-concatenates multiple arguments, a space was effectively inserted in the (for-display) output.
That '$'text[$i]
becomes two arguments is a perhaps surprising PowerShell idiosyncrasy; unlike in POSIX-compatible shells such as bash
, composing a single string argument from a mix of unquoted and (potentially differently) quoted parts only works if the argument starts with an unquoted substring or (mere) variable reference; for instance:
Write-Output foo'bar none'
does pass a single argument (passes foobar none
), whereas
Write-Output 'bar none'foo
does not (passes bar none
and foo
)
- See this answer for more information.