Here's another version, also using certutil
to generate the MD5 hash. It'll give you the MD5sum of a file or of a string argument, and can accept one line of input via the pipeline. This solution doesn't depend on an accompanying helper script.
@echo off & setlocal
set "plaintext=%~1"
set "file=%temp%\%~n0.tmp"
set md5=
if "%~1"=="/?" (
echo Usage: %~nx0 file^|string
echo or: command ^| %~nx0
echo;
echo Example: set /P "=password" ^<NUL ^| %~nx0
goto :EOF
)
if not defined plaintext set /P "plaintext="
if exist "%plaintext%" (
set "file=%plaintext%"
) else for %%I in ("%file%") do if %%~zI equ 0 (
<NUL >"%file%" set /P "=%plaintext%"
)
for /f "skip=1 delims=" %%I in ('certutil -hashfile "%file%" MD5') do (
if not defined md5 set "md5=%%I"
)
2>NUL del "%temp%\%~n0.tmp"
echo %md5: =%
Just because I felt like the challenge, here's yet another version that can accept multiple lines via the pipeline, as well as input from file redirection. (It wasn't easy preventing StdIn.AtEndOfStream
from prompting for keyboard input when the buffer was empty.)
@if (@CodeSection == @Batch) @then
@echo off & setlocal & goto main
:usage
echo Usage: %~nx0 file^|string
echo or: command ^| %~nx0
echo or: %~nx0 ^< file
echo;
echo Example: set /P "=password" ^<NUL ^| %~nx0
goto :EOF
:main
set "plaintext=%~1"
set "file=%temp%\%~n0.tmp"
set md5=
rem // check for input via the pipeline; timeout nearly instantly if none
start /b "" cscript /nologo /e:JScript "%~f0" "%file%" watcher
cscript /nologo /e:JScript "%~f0" "%file%"
if "%~1"=="" for %%I in ("%file%") do if %%~zI equ 0 goto usage
if "%~1"=="/?" goto usage
if not defined plaintext set /P "plaintext="
if exist "%plaintext%" (
set "file=%plaintext%"
) else for %%I in ("%file%") do if %%~zI equ 0 (
<NUL >"%file%" set /P "=%plaintext%"
)
for /f "skip=1 delims=" %%I in ('certutil -hashfile "%file%" MD5') do (
if not defined md5 set "md5=%%I"
)
2>NUL del "%temp%\%~n0.tmp"
echo %md5: =%
goto :EOF
@end // end Batch / begin JScript hybrid code
var fso = WSH.CreateObject('scripting.filesystemobject');
if (WSH.Arguments.Length > 1) {
WSH.Sleep(1);
if (!fso.FileExists(WSH.Arguments(0)))
WSH.CreateObject('WScript.Shell').Exec('taskkill /im "cscript.exe" /f');
} else if (!WSH.StdIn.AtEndOfStream) {
var file = fso.CreateTextFile(WSH.Arguments(0), 1);
file.Write(WSH.StdIn.ReadAll());
file.Close();
}