Format a command in powershell including a comma, can't find the right way to escape

1.3k Views Asked by At

I have a command that I need to run in a Powershell script, the command is :

".\pacli DELETEUSER DESTUSER='"dilip.v@astramwp`,com"' sessionid=333" | invoke-expression

The comma (,) in here :dilip.v@astramwp,com is not a mistake, and that's what is giving me the hard time.

I tried to escape the comma with ` (backtick) - but its not working.

How do I escape this ?

I get the error message :

parse error, expecting `';''

and in some variations :

Unexpected token 'dilip.v@astramwp`,com"`' sessionid=333"' in expression or statement.
At C:\CyberArk\Harel CyberArk WebService\deleteUser.ps1:6 char:70
+ ".\pacli DELETEUSER DESTUSER='"dilip.v@astramwp`,com"' sessionid=333" <<<<  | invoke-expression
+ CategoryInfo          : ParserError: (dilip.v@astramwp`,com"`' sessionid=333":String) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken

The command works when I use cmd.exe and just wrap it with "".

1

There are 1 best solutions below

0
Richard On BEST ANSWER
".\pacli DELETEUSER DESTUSER='"dilip.v@astramwp`,com"' sessionid=333"

You have double quotes in single quotes in double quotes, so the inner double quotes will terminate the string, so this will be parsed as three values:

".\pacli DELETEUSER DESTUSER='"
dilip.v@astramwp`,com
"' sessionid=333"

The answer is to escape, with a back tick (`), the inner double quotes:

".\pacli DELETEUSER DESTUSER='`"dilip.v@astramwp`,com`"' sessionid=333"

and thus those double quotes will be passed through to the command.

(As noted in the comments to the question, you'll also need to prefix the string with & to get PSH to treat it as a command.)