There is an existing question of how to run a ps1 file when you double click found here. However I want to know if there is a solution that does not require 2 separate files.
Asked
Active
Viewed 1,548 times
1
-
1In answer to your specific question, yes there is. – Compo Jul 11 '18 at 17:23
-
1The batch file can run powershell and give it a scriptblock of code to execute. – EBGreen Jul 11 '18 at 17:23
-
2This is definitely a duplicate question. Several questions about this already. – Squashman Jul 11 '18 at 17:43
-
1You may review a simple method to _embed_ PS code into a Batch file at [this topic](https://stackoverflow.com/questions/36672784/convert-a-small-ps-script-into-a-long-line-in-a-batch-file). – Aacini Jul 11 '18 at 17:49
-
Possible duplicate of [How to run a PowerShell script within a Windows batch file](https://stackoverflow.com/questions/2609985/how-to-run-a-powershell-script-within-a-windows-batch-file) – aschipfl Jul 12 '18 at 13:04
1 Answers
6
One method is to embed the Powershell script into a .bat file with a combination of echos and comments:
echo `
REM | Out-Null <#
powershell.exe -ExecutionPolicy Bypass -Command "iex ((Get-Content \"%~f0\") -join \"`n\") | Out-Null"
goto :eof
#>
(powershell script here)
<#
:eof
::#>
This results in some artifacts in the console output but the script is successfully run embedded in a bat file. This works without errors because "echo" is both a Windows Command Line command as well as a Powershell command.
EDIT: Here I am years later with an improved version:
@powershell.exe -ExecutionPolicy Bypass -Command "$_=((Get-Content \"%~f0\") -join \"`n\");iex $_.Substring($_.IndexOf(\"goto :\"+\"EOF\")+9)"
@goto :EOF
(powershell script here)
Improvements:
- Only requires a 2 line file header (I didn't know about
:EOF
) - No console output unless you do so from the script
- Compatible with
Write-Output
due to only passing the actual script content to powershell.exe

Jason
- 506
- 3
- 14
-
An enhancement: instead `@goto :EOF`, I'm using `exit %ERRORLEVEL%` and `$_.IndexOf('exit' + ' ')` to allow propagation of exit code. – OscarGarcia Nov 24 '20 at 14:15