PowerShell命令多行

时间:2012-06-20 12:09:58

标签: powershell batch-file

我有一个如下所示的批处理脚本:

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();}"

为了便于阅读,我想将“& {...}”内的代码拆分为多行。

This帖子说使用尾随反引号应该可以解决问题,但是当我写道:

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.

我做错了什么?

SOLUTION:

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

2 个答案:

答案 0 :(得分:6)

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

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

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

另请参阅 Long commands split over multiple lines in Windows Vista batch (.bat) file

答案 1 :(得分:1)

尝试以下方法。我认为这会有所帮助。

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