且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Powershell - 转义字符串传递给子进程

更新时间:2023-11-03 18:24:46

这是 PowerShell.exe 解析其命令行的方式.它主要遵循 .NET 命令行解析规则:

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

  • 空格是参数分隔符.PowerShell.exe 将通过单个空格连接各个参数,无论您使用多少个空格来分隔参数.

  • 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\