1

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.

5
  • 1
    In answer to your specific question, yes there is. Commented Jul 11, 2018 at 17:23
  • 1
    The batch file can run powershell and give it a scriptblock of code to execute. Commented Jul 11, 2018 at 17:23
  • 2
    This is definitely a duplicate question. Several questions about this already. Commented Jul 11, 2018 at 17:43
  • 1
    You may review a simple method to embed PS code into a Batch file at this topic. Commented Jul 11, 2018 at 17:49
  • Possible duplicate of How to run a PowerShell script within a Windows batch file Commented Jul 12, 2018 at 13:04

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

An enhancement: instead @goto :EOF, I'm using exit %ERRORLEVEL% and $_.IndexOf('exit' + ' ') to allow propagation of exit code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.