PowerShell命令跨多行

12

我有一个批处理脚本,它看起来像这样:

Test.bat

@echo off

:: Starts a PowerShell session that starts a PowerShell process with administrator privileges
powershell -noprofile -command "&{$process = start-process powershell -ArgumentList '-noprofile -noexit -file GetTools.ps1' -verb RunAs -PassThru;$process.WaitForExit();}"

我想将"&{...}"中的代码分成多行以便阅读。

这篇文章说可以通过使用尾随反斜杠来解决问题,但是当我编写以下代码时:

powershell -noprofile -command "&{`
    $process = start-process powershell -ArgumentList '-noprofile -noexit -file GetTools.ps1' -verb RunAs -PassThru;`
    $process.WaitForExit();`
}"

如果我在每行的末尾都使用一个反引号来结束,那么我会得到以下错误:

Incomplete string token.
At line:1 char:4
+ &{` <<<<
    + CategoryInfo          : ParserError: (`:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : IncompleteString

'$process' is not recognized as an internal or external command,
operable program or batch file.
'$process.WaitForExit' is not recognized as an internal or external command,
operable program or batch file.
'}"' is not recognized as an internal or external command,
operable program or batch file.

我做错了什么?

解决方案:

powershell -noprofile -command "&{"^
    "$process = start-process powershell -ArgumentList '-noprofile -noexit -file C:\Dev\Powershell\Sandbox.ps1' -verb RunAs -PassThru;"^
    "$process.WaitForExit();"^
    "}"
2个回答

11
你可以尝试使用插入符号^来表示当前行在下一行继续:
powershell -noprofile -command "&{"^
 "$process = start-process powershell -ArgumentList '-noprofile -noexit -file GetTools.ps1' -verb RunAs -PassThru;"^
 "$process.WaitForExit();"^
 "}"
请注意每行开头的空格以及每行末尾和开头的引号。

还可以参见Windows Vista批处理(.bat)文件中命令跨多行拆分


这导致出现以下错误:"语句块中缺少闭合 '}'。 在第1行字符4处:
  • &{^ <<<<
    • CategoryInfo : ParserError: (CloseBraceToken:TokenId) [], ParentContainsErrorRecord Exception
    • FullyQualifiedErrorId : MissingEndCurlyBrace
'$process' 不是内部或外部命令,也不是可运行的程序或批处理文件。
- Janne Beate Bakeng
尝试在以下行的开头添加一个空格。 - marapet
现在它可以工作了...在前导空格上,双引号必须在行末关闭,并在下一行重新打开。 - marapet
我已经让它工作了,你差不多就成功了,只需要删除末尾的反引号。 :) 谢谢! - Janne Beate Bakeng
我在我的示例中删除了它们...在发现它们之后 :-) - marapet

1
请尝试以下方法。我认为这会有所帮助。
powershell -noprofile -command ""&{^
    $process = start-process powershell -ArgumentList '-noprofile -noexit -file GetTools.ps1' -verb
    RunAs -PassThru;^
    $process.WaitForExit();^
}""

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接