jcrow
jcrow

Reputation: 35

Powershell inline commands on command line, quotation marks and new line

I have a powershell script that takes a parameter from the command line.

The passed parameter is a string with new line characters but I cannot get it to work as I wish.

Example running from command line:

powershell.exe -command "& {& 'C:\My Scripts\Script.ps1' "Some Text`nWoo Hoo"}"

The script above is only passed the text Some. If I use single quotes around the passed text the `n newline character is interpreted literally, not as a newline.

I'm sure there is some way to solve this!

thanks

Upvotes: 3

Views: 1847

Answers (1)

mklement0
mklement0

Reputation: 437998

Since your overall command string is (of necessity when calling from cmd.exe) double-quoted, you must escape the embedded double quotes as \" (even though inside PowerShell it is ` that serves as the escape character, as used in the embedded `n escape sequence):

# From cmd.exe
powershell.exe -command "& 'C:\My Scripts\Script.ps1' \"Some Text`nWoo Hoo\""

Also note that there's never a need to use -Command "& { ... }" when calling the PowerShell CLI - just -Command "..." is sufficient.

In your case, embedded double-quoting (\"...\"), i.e. use of an (escaped) expandable string is a must in order to get interpolation of the `n escape sequence to an actual newline.
In cases where a verbatim (literal) string is sufficient, you can bypass the need to escape by using single-quoting ('...').

See the bottom section of this answer for more information about string literals in PowerShell.

Upvotes: 2

Related Questions