PowerShell batch launch with multi-line command parameter

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

For example, the code is as follows:

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 this without creating a PowerShell script file, just a batch file.
Is it possible?

Thanks.

+7
source share
4 answers

You can add '^' to continue the line that you assign to the 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 that needs to be executed 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 passes all lines that do not begin with "; @F" to PowerShell.

Edit: I was able to run PowerShell in a separate window and enable cmd 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 } 

Please note that after setting the variable "LF" there should be 2 spaces, since we assign a string to the variable.

+9
source

Using

 start powershell -NoExit -EncodedCommand "aQBmACAAKAAkAHQAcgB1AGUAKQAKAHsACgBXAHIAaQB0AGUALQBIAG8AcwB0ACAAIgBSAGUAcwB1AGwAdAAgAGkAcwAgAFQAcgB1AGUAIgAKAH0ACgBlAGwAcwBlAAoAewAKAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAiAFIAZQBzAHUAbAB0ACAAaQBzACAARgBhAGwAcwBlACIACgB9AAoA" 

Quote from powershell /?

 # To use the -EncodedCommand parameter: $command = 'dir "c:\program files" ' $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) $encodedCommand = [Convert]::ToBase64String($bytes) powershell.exe -encodedCommand $encodedCommand 

You can use a command that would otherwise require inconvenient escaping through -EncodedCommand , simply by providing a Base64 encoded string.

+5
source

You can use -Command - , which causes ps to read its commands from stdin. Put your commands in a file and call

 powershell -Command - <myCommandFile 
+1
source

Joey's path is reliable, but you can also use a simple multi-line command in your case

Blank lines are needed here (as in the LF Rynant example)

 powershell -command if ($true)^ {^ Write-Host "Result is True"^ }^ else^ {^ Write-Host "Result is False"^ } 

Here is an explanation of Long commands divided into several lines

+1
source

All Articles