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.
To split long command into multiple lines, use the backtick (`) character in the command where you want to split it into multiple lines.
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.
To execute multiple commands in Windows PowerShell (a scripting language of Microsoft Windows), simply use a semicolon.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With