PS2CMD - embed PowerShell code in a batch file - Svendsen Tech
Jump to page sections
In this article I describe how to embed PowerShell code in a (not so standalone after all) batch/cmd.exe file. It allows for it to run seamlessly.

To embed PowerShell code in a cmd file in the way I'm going to describe in this article comes with two known disadvantages, which are as follows:

It works on my Vista computer with PSv2. Primary testing and "development" has been done on Windows 8.1 with PowerShell version 4.

This might serve as a crude alternative to PS2EXE found on Technet.

As always, I'm posting in case it's useful for someone. One scenario might be wanting a double-clickable shortcut (but you could then just call powershell.exe from a batch script "manually"). The technique I describe here is just some logic that copies to a temp .ps1 file and runs it, with some voodoo to avoid running the batch code that's in the same file.

Example PS2CMD screenshot

Example PS2CMD code

An example file that just dumps the $PSVersionTable will look like this:
REM <#
@echo off
REM This file needs to be ASCII encoded for cmd.exe to understand it.
copy %0 %0.tmp.ps1 > nul
PowerShell.exe -ExecutionPolicy Unrestricted -NoProfile -Command "$ErrorActionPreference = 'SilentlyContinue'; if ('%0' -notmatch '[\\/]') { . .\%0.tmp.ps1 } else { . %0.tmp.ps1 }; Remove-Item %0.tmp.ps1"
goto :EOF
REM #>

$ErrorActionPreference = 'Continue'

# PowerShell code goes here:


#ls | sort length -desc | select -first 5 | ft -a #ps | sort ws -desc | select -first 5 | ft -a

You need to store this code in a file with the .cmd extension, and cmd.exe is the most happy with ASCII-encoded files. I recommend using PowerShell ISE or another capable PowerShell editor to create the PowerShell code, and then paste it into the ASCII/ANSI-encoded .cmd file in the right place (at the bottom).

Converting to ASCII for the batch file

A one-liner to convert a file to ASCII encoding is:
Get-Content original-file.cmd | Set-Content -Encoding ASCII new-file.cmd
    Powershell     Windows     Batch     Programming    All Categories

Google custom search of this website only

Minimum cookies is the standard setting. This website uses Google Analytics and Google Ads, and these products may set cookies. By continuing to use this website, you accept this.

If you want to reward my efforts