Monday, December 19, 2016

Holding an executable inside a batch file

Suppose you want to include an EXE inside a batch file and have the batch script extract the program from itself and run it. Just pasting the EXE into the file will almost certainly butcher it, because programs are binary files and batch scripts are text files. Therefore, you'll need to encode the binary data.

Start with this batch file:

@echo off
powershell -command "[IO.File]::WriteAllBytes('extracted.exe', [Convert]::FromBase64String((gc '%0')[-1]))"
extracted
del extracted.exe
exit

REM Base64-encoded program will be inserted below


The extra blank line at the end is important.

Notice that the PowerShell script embedded in the second line takes a Base64 string from the end of the batch file. To put it there, use this PowerShell command:

[Convert]::ToBase64String([IO.File]::ReadAllBytes('C:\fullPathTo\file.exe')) | Out-File 'batchFile.bat' -Append -Encoding ASCII

Running the batch file will decode the executable, save it to disk, run it, and delete it once it finishes.

Based on my Super User answer.

No comments:

Post a Comment