Findstr always fails to find hash string in text file

余生颓废 提交于 2019-11-28 01:46:38

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 ASCII¹ 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
    

¹ 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.

Accordingly to the comments posted in this question I think there are some misconceptions on this topic, that I try to clear.

All command-line based applications included with Windows are primarily designed to work with cmd.exe and Batch files. As a matter of fact, one of the features of PowerShell is that it "can use command-line applications in the same way as cmd.exe do". There is not a single command-line based application designed to work with PowerShell, but not with cmd.exe/Batch file.

In my humble opinion the use of PowerShell in this topic is not just unnecessary, but it is also the cause of the original problem. The pure Batch-file code below should run as originally intended, with no problems:

@echo off
setlocal EnableDelayedExpansion

:a
certutil -hashfile license.jar > "1.txt"

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

As an additional point, the time required to run this pure Batch file is much lesser than the required to run the PowerShell-based one.

Instead of using findstr I used FC (filecompare). I let powershell create 1.txt and then I copied the content over to 2.txt and saved it as unicode.

The white spaces in the file generated by powershell seems to not be regular spaces and use of the /W to suppress white spaces and /U for parsing the files as Unicode is necessary to make it work.

The code is now as following:

@echo off
setlocal EnableDelayedExpansion

:a

powershell.exe -ExecutionPolicy ByPass -file powershellmd5.ps1
timeout /t 3 /NOBREAK

fc /U /W /lb3 1.txt 2.txt

IF NOT ERRORLEVEL 1 ( 
    echo Indentical.
) else (
    echo Different.
)
pause


del /q 1.txt

timeout /t 10 /NOBREAK

goto a

The script now successfully compares both files, returns error code 0 and prints Identical"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!