Embed PowerShell code in a batch file


In a certain scenario, I needed a batch file (bat or cmd extension) that runs PowerShell code, and I could have only one file, so I couldn't go with the easy way of a batch file calling PowerShell.exe with the -File parameter specifying the path to a ps1 file.

For this, I created a special batch file with a header that reads the contents of itself, excludes the lines that have the batch code (lines stat start with @@) and then runs the rest in PowerShell.

Here is the batch template, just replace the lines below the comment that says "POWERSHELL CODE STARTS HERE" with your PowerShell code.

Though not intended, it's another way of bypassing the ExecutionPolicy even if it's set in Group Policy, since the code is run as commands and not a script file.


HTH,

Martin.

Comments (5)

  1. Martin Myers says:

    This is super cool. I had to make a slight change to get it to work.
    Make sure you have two empty lines after @@set LF=^
    If there’s just one, you’ll get errors.
    Thanks!

    1. Good catch! I updated the code. Thanks!

  2. Here’s a variant of that approach. It uses PowerShell.exe’s encodedcommand switch that helps to avoid issues with batch files and special characters:

    –8<– cut here –8<–
    @ECHO OFF
    FOR /F "delims=:" %%i IN ('findstr.exe /N ":PSEncodedCommand" "%~f0"') DO (SET LINE=%%i)
    FOR /F %%i IN ('more.com +%LINE% ^< "%~f0"') DO (
    powershell.exe -NoProfile -EncodedCommand %%i
    )
    GOTO :EOF
    :PSEncodedCommand
    VwByAGkAdABlAC0ASABvAHMAdAAgACIASABlAGwAbABvACwAIABXAG8AcgBsAGQAIQAiAA==
    –8<– cut here –8<–

    BTW, the encoded command resolves to Write-Host "Hello, World!"

    1. Forget about my last reply. In order to call an encoded PowerShell command you just need one line in you batch file:

      PowerShell.exe -EncodedCommand VwByAGkAdABlAC0ASABvAHMAdAAgACIASABlAGwAbABvACwAIABXAG8AcgBsAGQAIQAiAA==

Skip to main content