使用cmd.exe中的多行PowerShell命令

lit*_*lit 3 powershell cmd

我想在cmd.exe .bat脚本中指定多行PowerShell命令.我显然还没有正确的续行和/或引用.我也尝试使用反引号作为具有类似失败的行继续符.我怎样才能正确输入?

PS C:\src\t> cat .\pd.bat
powershell -NoProfile -Command "Get-ChildItem -Path '../' -Filter '*.doc' | ^
    Select-Object -First 1 | ^
    ForEach-Object { notepad `"$_.FullName`" }"
PS C:\src\t> .\pd.bat

C:\src\t>powershell -NoProfile -Command "Get-ChildItem -Path '../' -Filter '*.doc' | ^
^ : The term '^' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if
a path was included, verify that the path is correct and try again.
At line:1 char:45
+ Get-ChildItem -Path '../' -Filter '*.doc' | ^
+                                             ~
    + CategoryInfo          : ObjectNotFound: (^:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
Run Code Online (Sandbox Code Playgroud)

mkl*_*nt0 7

如果没有使用中间临时文件,您可以使用selective ^-escaping:

powershell -NoProfile -Command Get-ChildItem -Path '../' -Filter '*.doc' ^| ^
Select-Object -First 1 ^| ^
ForEach-Object { notepad "\"$($_.FullName)\"" }
Run Code Online (Sandbox Code Playgroud)

需要注意的是notepad "$_.FullName"不能在PowerShell中的工作,因为你需要一个封闭$(...)引用属性里面"...".我已经纠正了上面的问题,但请注意在这种情况下你根本不需要双引号.

^ 必须使用:

  • 逃避|以防止cmd.exe事先解释它.
    • 一般情况下,你必须^-escape 所有cmd.exe的元字符,如果你想通过对PowerShell来传递它们:& | < > %
    • "您希望PowerShell按字面意思查看的实例(当它们被解释为PowerShell源代码时具有合成意义)是一种特殊情况:您必须\- 它们(!) "..." -enclose您想要被识别为单个参数的字符串通过PowerShell,以便准确地保留嵌入的空白.
  • 转义行尾以告诉cmd.exe命令在下一行继续.
    • 请注意,^必须是该行的最后一个字符.
    • 另请注意,换行符^ 会删除换行符,因此生成的命令是单行命令.

要在命令中包含实际的换行符 - 这是将命令传递给Python等语言所必需python -c,正如eryksun 指出的那样 - 使用^<newline><newline>,如PetSerAl建议:

powershell.exe -noprofile -command "\"line 1^

line 2\""
Run Code Online (Sandbox Code Playgroud)

以上产量(基于PowerShell简单地回显(输出)作为命令提交的带引号的字符串文字):

line 1
line 2
Run Code Online (Sandbox Code Playgroud)

注意:("\"和匹配\"")不仅需要最终传递具有正确保留的嵌入空格的字符串,而且还要在该行上呈现一个平衡的集合(不管-escaping,哪些不能识别) - 没有它,该行末尾的换行符将无法识别."cmd.exe\cmd.exe^

PetSerAl还指出,如果你传递的是PowerShell应该认为的字符串文字,你也可以传递PowerShell最终看到的单引号字符串('...'):

powershell.exe -noprofile -command ^"'line 1^

line 2'^"
Run Code Online (Sandbox Code Playgroud)

这里,实例的^-escaping "是为了好处,cmd.exe所以它不会将newline-escaping误^认为是在双引号字符串中.