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:
- 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.
Example PS2CMD screenshot
Example PS2CMD code
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:$PSVersionTable
#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
Get-Content original-file.cmd | Set-Content -Encoding ASCII new-file.cmdPowershell Windows Batch Programming
Blog articles in alphabetical order
A
- A Look at the KLP AksjeNorden Index Mutual Fund
- A primitive hex version of the seq gnu utility, written in perl
- Accessing the Bing Search API v5 using PowerShell
- Accessing the Google Custom Search API using PowerShell
- Active directory password expiration notification
- Aksje-, fonds- og ETF-utbytterapportgenerator for Nordnet-transaksjonslogg
- Ascii art characters powershell script
- Automatically delete old IIS logs with PowerShell
C
- Calculate and enumerate subnets with PSipcalc
- Calculate the trend for financial products based on close rates
- Check for open TCP ports using PowerShell
- Check if an AD user exists with Get-ADUser
- Check when servers were last patched with Windows Update via COM or WSUS
- Compiling or packaging an executable from perl code on windows
- Convert between Windows and Unix epoch with Python and Perl
- Convert file encoding using linux and iconv
- Convert from most encodings to utf8 with powershell
- ConvertTo-Json for PowerShell version 2
- Create cryptographically secure and pseudorandom data with PowerShell
- Crypto is here - and it is not going away
- Crypto logo analysis ftw
D
G
- Get rid of Psychology in the Stock Markets
- Get Folder Size with PowerShell, Blazingly Fast
- Get Linux disk space report in PowerShell
- Get-Weather cmdlet for PowerShell, using the OpenWeatherMap API
- Get-wmiobject wrapper
- Getting computer information using powershell
- Getting computer models in a domain using Powershell
- Getting computer names from AD using Powershell
- Getting usernames from active directory with powershell
- Gnu seq on steroids with hex support and descending ranges
- Gullpriser hos Gullbanken mot spotprisen til gull
H
- Have PowerShell trigger an action when CPU or memory usage reaches certain values
- Historical view of the SnP 500 Index since 1927, when corona is rampant in mid-March 2020
- How to check perl module version
- How to list all AD computer object properties
- Hva det innebærer at særkravet for lån til sekundærbolig bortfaller
I
L
M
P
- Parse openssl certificate date output into .NET DateTime objects
- Parse PsLoggedOn.exe Output with PowerShell
- Parse schtasks.exe Output with PowerShell
- Perl on windows
- Port scan subnets with PSnmap for PowerShell
- PowerShell Relative Strength Index (RSI) Calculator
- PowerShell .NET regex to validate IPv6 address (RFC-compliant)
- PowerShell benchmarking module built around Measure-Command
- Powershell change the wmi timeout value
- PowerShell check if file exists
- Powershell check if folder exists
- PowerShell Cmdlet for Splitting an Array
- PowerShell Executables File System Locations
- PowerShell foreach loops and ForEach-Object
- PowerShell Get-MountPointData Cmdlet
- PowerShell Java Auto-Update Script
- Powershell multi-line comments
- Powershell prompt for password convert securestring to plain text
- Powershell psexec wrapper
- PowerShell regex to accurately match IPv4 address (0-255 only)
- Powershell regular expressions
- Powershell split operator
- Powershell vs perl at text processing
- PS2CMD - embed PowerShell code in a batch file
R
- Recursively Remove Empty Folders, using PowerShell
- Remote control mom via PowerShell and TeamViewer
- Remove empty elements from an array in PowerShell
- Remove first or last n characters from a string in PowerShell
- Rename unix utility - windows port
- Renaming files using PowerShell
- Running perl one-liners and scripts from powershell
S
- Sammenlign gullpriser og sølvpriser hos norske forhandlere av edelmetall
- Self-contained batch file with perl code
- Simple Morningstar Fund Report Script
- Sort a list of computers by domain first and then name, using PowerShell
- Sort strings with numbers more humanely in PowerShell
- Sorting in ascending and descending order simultaneously in PowerShell
- Spar en slant med en optimalisert kredittkortportefølje
- Spre finansiell risiko på en skattesmart måte med flere Aksjesparekontoer
- SSH from PowerShell using the SSH.NET library
- SSH-Sessions Add-on with SCP SFTP Support
- Static Mutual Fund Portfolio the Last 2 Years Up 43 Percent
- STOXR - Currency Conversion Software - Open Exchange Rates API