I have a powershell script which calls another powershell file passing a string argument.
param (
[string]$strVal = "Hello World"
)
$params = @{
message = "$strVal"
}
$sb = [scriptblock]::create(".{$(get-content $ps1file -Raw)} $(&{$args} @params)")
Somehow the script passes message variable without double quotes so the powershell file receives only the first part of the message variable (before space) i.e. "Hello".
How can I pass the strVal variable with space (i.e. "Hello World")?
A double quote pair signals PowerShell to perform string expansion. If you want double quotes to output literally, you need to escape them (prevent expansion) or surround them with single quotes. However, a single quote pair signals PowerShell to treat everything inside literally so your variables will not interpolate. Given the situation, you want string expansion, variable interpolation, and literal double quotes.
You can do the following:
# Double Double Quote Escape
@{message = """$strVal"""}
Name Value
---- -----
message "Hello World"
# Backtick Escape
@{message = "`"$strVal`""}
Name Value
---- -----
message "Hello World"
Quote resolution works from left to right, which means the leftmost quote type takes precedence. So '"$strVal"'
will just print everything literally due to the outside single quote pair. "'$strVal'"
will print single quotes and the value of $strVal
.