How do I properly escape the quotes in the -param
value in the following command line?
$cmd="\\server\toto.exe -batch=B -param="sort1;parmtxt='Security ID=1234'"" Invoke-Expression $cmd
This of course fails. I tried to escape the quotes (single and double) using the escape character ` and did various combination, but nothing is working.
Escaping a string means to reduce ambiguity in quotes (and other characters) used in that string. For instance, when you're defining a string, you typically surround it in either double quotes or single quotes: "Hello World." But what if my string had double quotes within it? "Hello "World.""
If you need to use the double quote inside the string, you can use the backslash character. Notice how the backslash in the second line is used to escape the double quote characters. And the single quote can be used without a backslash.
In short, escaping characters means just ignore the double quotes (mid ones throughout the string). That's one of the things that escaping characters can do, certainly, but only one of them. For example there's no need to escape double-quotes, if your string assignment is surrounded by single quotes.
Using the backtick (`) works fine for me if I put them in the following places:
$cmd="\\server\toto.exe -batch=B -param=`"sort1;parmtxt='Security ID=1234'`""
$cmd
returns as:
\\server\toto.exe -batch=B -param="sort1;parmtxt='Security ID=1234'"
Is that what you were looking for?
The error PowerShell gave me referred to an unexpected token 'sort1', and that's how I determined where to put the backticks.
The @' ... '@ syntax is called a "here string" and will return exactly what is entered. You can also use them to populate variables in the following fashion:
$cmd=@' "\\server\toto.exe -batch=B -param="sort1;parmtxt='Security ID=1234'"" '@
The opening and closing symbols must be on their own line as shown above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With