Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape pipe character from PowerShell command line to pass into non-PowerShell command

I'm in a PowerShell console session, trying to run a Gradle script that exists in the cwd from the PowerShell command line.

The Gradle command accepts an argument which includes quotes that can contain one or more pipe characters, and I can't for the life of me figure out how to get PowerShell to escape it using just one line (or any number of lines, actually - but I'm not interested in multi-line solutions).

Here's the command:

./gradlew theTask -PmyProperty="thisThing|thatThing|theOtherThing"

...which produces this error:

'thatThing' is not recognized as an internal or external command, operable program or batch file.

I've tried all of these variants, none of which work. Any idea?

./gradlew theTask -PmyProperty="thisThing`|thatThing`|theOtherThing"
./gradlew theTask -PmyProperty=@"thisThing|thatThing|theOtherThing"
./gradlew theTask -PmyProperty="thisThing\|thatThing\|theOtherThing"
./gradlew theTask -PmyProperty="thisThing\\|thatThing\\|theOtherThing"
./gradlew theTask -PmyProperty="thisThing^|thatThing^|theOtherThing"
like image 347
Hoobajoob Avatar asked Oct 18 '22 06:10

Hoobajoob


1 Answers

Well, I have found that:

First call your script like this as I first suggested:

./gradlew theTask -PmyProperty="thisThing^|thatThing^|theOtherThing"

Then modify your gradlew.bat script by adding quotes:

set CMD_LINE_ARGS="%*"

The problem is: now CMD_LINE_ARGS must be called within quotes or the same error will occur.

So I assume that your command line arguments cannot be something else and I'm handling each parameter one by one

rem now remove the quotes or there will be too much quotes
set ARG1="%1"
rem protect or the pipe situation will occur
set ARG1=%ARG1:""=%
set ARG2="%2"
set ARG2=%ARG2:""=%
set ARG3="%3"
set ARG3=%ARG3:""=%

echo %ARG1% %ARG2% %ARG3%

The output is (for my mockup command):

theTask -PmyProperty "thisThing|thatThing|theOtherThing"

The "=" has gone, because it has separated parameters from PowerShell. I suppose this won't be an issue if your command has standard argument parsing.

Add as many arguments as you want, but limit it to 9 anyway.

like image 130
Jean-François Fabre Avatar answered Nov 01 '22 10:11

Jean-François Fabre