Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell command over multiple lines

I have a batch script that looks like this:

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

I would like to split up the code inside the "&{ ... }" over multiple line for readability.

This post says that using a trailing backtick should do the trick, but when I write:

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

...that is, I end each line with a trailing backtick, then I get the following error:

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.

What am I doing wrong?

SOLUTION:

powershell -noprofile -command "&{"^
    "$process = start-process powershell -ArgumentList '-noprofile -noexit -file C:\Dev\Powershell\Sandbox.ps1' -verb RunAs -PassThru;"^
    "$process.WaitForExit();"^
    "}"
like image 297
Janne Beate Bakeng Avatar asked Jun 20 '12 12:06

Janne Beate Bakeng


1 Answers

You may try the caret ^ to indicate that the current line continues on the next one:

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

Please note also the leading space as well as the closing and opening " on each line.

See also Long commands split over multiple lines in Windows Vista batch (.bat) file.

like image 59
marapet Avatar answered Oct 01 '22 06:10

marapet