user61375
user61375

Reputation: 23

Format the output of a CMD command

Hi I'm executing this bat in a windows environment

for /f "usebackq" %%i in (hostname) DO SET host=%%i
for /R c:\Users\ %%G IN (*.jpg) DO (
echo %host% >> output.txt
certutil -hashfile "%%G" MD5)

And I'm getting this output

Hostame
Hahs MD5 of the file <file> is
<hash>
CertUtil: -hashfile command executed

I need help so I can format the output like:

<hostname>,,<File>,,<hash>

Upvotes: 0

Views: 5696

Answers (1)

MC ND
MC ND

Reputation: 70923

@echo off
    setlocal enableextensions disabledelayedexpansion

    for /f "delims=" %%a in ('hostname') do set "host=%%a"

    >output.txt (
        for %%z in (*.jpg) do for /f "delims=" %%a in ('
            certutil -hashfile "%%z" MD5 ^| find /v ":"
        ') do echo %host%,,%%z,,%%a
    )

You can use the %computername% instead of execute hostname to retrieve the machine name, but:

  • The first for /f to execute the hostname command now includes a delims= clause to ensure (I think this is not needed, but just to be sure) there will be no splitting on spaces in the machine name. Also, the command to execute is enclosed in single quotes

  • The inner for /f will process the output of the certutil command. delims= is also included to retrieve the full MD5 line (in this case is a requirement as the output is a separate list of two hex characters). The output of the cerutil -hashfile also includes informative lines that are removed piping the output to a find command to remove lines with a colon (present in informative lines and not in the hash)

  • The full for %%z that iterates the files and the inner for /f that executes certutil have been redirected to the output file. This will open the output file only once, sending to it all the output of the inner commands sent to standard output stream.

Upvotes: 1

Related Questions