Powershell – escaping string passed to child process

It is how PowerShell.exe parse its command line. It mostly follows .NET rules of command line parsing:

  • Space is an argument separator. PowerShell.exe will join individual arguments by single space regardless of how many spaces you use to separate arguments.

    CMD> PowerShell -Command echo 'multiple   spaces'
    multiple spaces
    
  • If you want to include space in argument value, then you should enclose space in double quotes. Double quotes itself are not a part of resulting argument value and can be anywhere inside argument:

    CMD> PowerShell -Command echo 'mult"iple   spa"ces'
    multiple   spaces
    
  • If you want literal double quote to be part of argument value, then you have to escape it with backslash:

    CMD> PowerShell -Command echo 'literal\"double\"quotes'
    literal"double"quotes
    
  • If you want literal backslash to precede double quote, then you have to escape that backslash with another backslash. Other than that, backslash interpreted literally and does not need to be escaped:

    CMD> PowerShell -Command echo 'back\\slash\\"   something\\else\\"'
    back\\slash\   something\\else\
    

Leave a Comment