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.
-
1In answer to your specific question, yes there is.Compo– Compo2018-07-11 17:23:11 +00:00Commented Jul 11, 2018 at 17:23
-
1The batch file can run powershell and give it a scriptblock of code to execute.EBGreen– EBGreen2018-07-11 17:23:26 +00:00Commented Jul 11, 2018 at 17:23
-
2This is definitely a duplicate question. Several questions about this already.Squashman– Squashman2018-07-11 17:43:31 +00:00Commented Jul 11, 2018 at 17:43
-
1You may review a simple method to embed PS code into a Batch file at this topic.Aacini– Aacini2018-07-11 17:49:10 +00:00Commented Jul 11, 2018 at 17:49
-
Possible duplicate of How to run a PowerShell script within a Windows batch fileaschipfl– aschipfl2018-07-12 13:04:00 +00:00Commented Jul 12, 2018 at 13:04
Add a comment
|
1 Answer
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-Outputdue to only passing the actual script content to powershell.exe
1 Comment
OscarGarcia
An enhancement: instead
@goto :EOF, I'm using exit %ERRORLEVEL% and $_.IndexOf('exit' + ' ') to allow propagation of exit code.