1

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")?

1
  • 2
    You can use double double quote escape here. message = """$strVal""" Commented Jan 17, 2020 at 15:35

1 Answer 1

1

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.