12

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

测试.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();"^
    "}"
4

2 回答 2

10

您可以尝试使用插入符号^来指示当前行在下一行继续:

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

请注意前导空格以及"每行的结束和开始。

另请参阅在 Windows Vista 批处理 (.bat) 文件中拆分为多行的长命令

于 2012-06-20T12:17:41.383 回答
1

试试下面的。我认为这会有所帮助。

powershell -noprofile -command ""&{^
    $process = start-process powershell -ArgumentList '-noprofile -noexit -file GetTools.ps1' -verb
    RunAs -PassThru;^
    $process.WaitForExit();^
}""
于 2012-06-20T12:30:47.410 回答