PS2CMD - embed PowerShell code in a batch file

From Svendsen Tech PowerShell Wiki
Jump to: navigation, search

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:

  • The cmd.exe prompt line with "REM <#" will be output before the rest of the PowerShell script's output.
  • The cmd script needs write access to the current working directory - or a hardcoded directory (you will then need to edit the -Command "..." stuff).

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.

    (adsbygoogle = window.adsbygoogle || []).push({
         google_ad_client: "ca-pub-5203802095278960",
         enable_page_level_ads: true


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