Search code examples
stringpowershellescapingparameter-passingquoting

How to pass PowerShell string parameter that has both `(backtick), ' and " inside?


I am executing a Python script using a PowerShell command, The Python script takes a string that could contain special characters inside it. This parameter is passed from an ansible pipeline. The ansible host is a Windows Machine, therefore we have to use win_shell module which used PowerShell. So, the solution should be a general one that can be applied to any string. The PowerShell version I am running is PowerShell 5.1.

python.exe script.py --special_string the"str`in'g --otherparam value

But this gives errors. (Simply " and ' doesn't get skipped properly)

Based on my current findings,

  • In PowerShell ' means a literal string and " could be used to add variable values.
  • As the escape character we use `, but the`"strin`'g gives an error. "the`"strin`'g" doesn't work either. The error is, PowerShell considers the skipped ". Eith it takes all the remaining content in the command as the string content or closes already started string with " at the begining.
script.py: error: the following arguments are required: --otherparam
  • You cannot surround the string with " using ' like 'string"g'. This also gives an error.
  • Backtick can be escaped using double backticks or surrounding the string with single quotes. (making it a literal string)

What is the best way to do this?


Solution

  • You can force PowerShell to skip parsing arguments of the python runtime. Just insert --% before the arguments of the external python.exe command:

    python.exe --% script.py --special_string the"str`in'g --otherparam value
    

    It will pass the arguments as is.