Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

windows - Findstr always fails to find hash string in text file

I'm trying to replace a certain .jar file if the MD5 hash of the file changes. I've written a small PowerShell script to do the hashing of the file and the .ps1 script is run through a batch file.

After PowerShell prints the hash into 1.txt I want the batch script to check the text file for the correct hash and if the hash is different it will overwrite the file with the old version. The replacing of the file is not yet implemented but will be once the findstr issue is resolved.

@echo off
setlocal EnableDelayedExpansion

:a
powershell.exe -ExecutionPolicy ByPass -file powershellmd5.ps1

findstr /c:"ff b1 b9 2d b1 03 db 59 3f 9e ca 51 f0 14 67 62 ca a8 d7 7d" "1.txt"
echo !errorlevel!
timeout /t 10 /NOBREAK
goto a

Here is the content of 1.txt when the hashing is complete:

SHA1 hash of file license.jar:
ff b1 b9 2d b1 03 db 59 3f 9e ca 51 f0 14 67 62 ca a8 d7 7d
CertUtil: -hashfile command completed successfully.

The errorlevel is always 1, even though the string is identical to the one in the text file. Maybe I am using the arguments wrong?

I'm using Out-File in powershellmd5.ps1 to write the result:

certutil -hashfile license.txt | Out-File 1.txt
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Apparently you're using Out-File for creating 1.txt. The cmdlet uses Unicode (little endian UTF-16) as the default encoding, which findstr doesn't support. The command processes the file as ASCII1 text and thus can't find a match.

There are two ways of approaching this problem:

  • Write 1.txt using ASCII encoding, either by calling Out-File with the -Encoding parameter:

    certutil -hashfile license.txt | Out-File 1.txt -Encoding Ascii
    

    or by calling Set-Content (which defaults to ASCII encoding):

    certutil -hashfile license.txt | Set-Content 1.txt
    
  • Use the find command (which supports Unicode) instead of findstr:

    find "ff b1 b9 2d b1 03 db 59 3f 9e ca 51 f0 14 67 62 ca a8 d7 7d" 1.txt
    

1 Yes, I know, it's actually an ANSI encoding, but the parameter argument is named Ascii, so let's stick with that name for now to avoid confusion.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...