Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch launching PowerShell with a multiline command parameter

I want to pass several lines of code from a batch file to powershell.exe as -command parameter.

For example, code like this:

SET LONG_COMMAND=
if ($true)
{
Write-Host "Result is True"
}
else
{
Write-Host "Result is False"
}

START Powershell -noexit -command "%LONG_COMMAND%"

I would like to do it without creating a PowerShell script file, only a batch file.
Is it possible?

Thanks.

like image 632
mcu Avatar asked Feb 20 '12 18:02

mcu


People also ask

How do I run a multiline command in PowerShell?

To split long command into multiple lines, use the backtick (`) character in the command where you want to split it into multiple lines.

How do I run multiple PowerShell commands in one batch file?

The commands can be in one PowerShell invocation by using a SEMICOLON at the end of each line. You need just one execution of PowerShell, and multiple commands passed to it. Each of those commands should be separated with semicolons, ; , and should all be enclosed within one doublequoted -Command argument.

How do I string multiple PowerShell commands together?

To execute multiple commands in Windows PowerShell (a scripting language of Microsoft Windows), simply use a semicolon.


1 Answers

You can add ' ^' to continue the string that you are assigning to a variable. This creates the command as a single line, so you need to use ';' between statements:

@ECHO off
SET LONG_COMMAND= ^
if ($true) ^
{ ^
Write-Host "Result is True"; ^
Write-Host "Multiple statements must be separated by a semicolon." ^
} ^
else ^
{ ^
Write-Host "Result is False" ^
}

START Powershell -noexit -command %LONG_COMMAND%

If the only code you need to execute is PowerShell, you can use something like:

;@Findstr -bv ;@F "%~f0" | powershell -command - & goto:eof

if ($true){
    Write-Host "Result is True" -fore green
}
else{
    Write-Host "Result is False" -fore red
}

Start-Sleep 5

which pipes all lines not starting with ";@F" to PowerShell.

Edit: I was able to start PowerShell in a separate window and allow cmd to exit with this:

@@ECHO off
@@setlocal EnableDelayedExpansion
@@set LF=^


@@SET command=#
@@FOR /F "tokens=*" %%i in ('Findstr -bv @@ "%~f0"') DO SET command=!command!!LF!%%i
@@START powershell -noexit -command !command! & goto:eof

if ($true){
    Write-Host "Result is True" -fore green
}
else{
    Write-Host "Result is False" -fore red
}

Note that there must be 2 spaces after setting the 'LF' variable since we are assigning a line feed to the variable.

like image 93
Rynant Avatar answered Sep 29 '22 11:09

Rynant