I\'m attempting to write an ASCII null character (nul) to a file from a Windows batch script without success. I initially tried using echo
like this:
Here's an article which describes how to write arbitrary bytes with a batch file (search for h2b.com
). This effectively solves the problem of writing any non-printable data using a batch script (including null).
An alternative to the accepted answer which doesn't involve having to put null characters into the batch file is as follows:
@echo off
set NULL_FILE=null.txt
set DEBUG_COMMANDS=write-null.dbg
echo e 100 >%DEBUG_COMMANDS%
echo 0 >>%DEBUG_COMMANDS%
echo n %NULL_FILE% >>%DEBUG_COMMANDS%
echo rbx >>%DEBUG_COMMANDS%
echo 0 >>%DEBUG_COMMANDS%
echo rcx >>%DEBUG_COMMANDS%
echo 1 >>%DEBUG_COMMANDS%
echo w >>%DEBUG_COMMANDS%
echo q >>%DEBUG_COMMANDS%
debug < %DEBUG_COMMANDS% >nul
del %DEBUG_COMMANDS%
This is obviously more verbose and also has the downside that it won't work on Win64 machines (due to debug
no longer being available in those environments).
Okay, this was tricky, and the solution is ugly, but it works.
You can use the batch file itself as the file containing the null character to be copied.
This batch file, called null.bat
:
findstr /v /r \n null.bat >> myfile.txt
[NULL]
(where the last line contains only the null character) appends the null character to myfile.txt
.
findstr /v /r
shows all lines that aren't matched by the regex, i.e. only the last one, because there's no newline character.
I have tried several other things, but this was the only one I could find that didn't strip the null character.
Note: findstr
was first shipped with Windows 2000 so may not be available on prior versions of Windows
I don't like the solution that cannot be easy copy/paste-d to text files.So few more ways:
1) mshta (can be directly used in batch file or from command line):
mshta vbscript:execute("CreateObject(""Scripting.FileSystemObject"").GetStandardStream(1).Write( Chr(00) ):Close")>testfile
2) certutil (requires a temp file)
echo 00>null.hex
certutil -decodehex null.hex null.bin
3) makecab just check the subroutine here - http://ss64.com/nt/syntax-genchr.html