I was recently looking at comparing the MD5 checksum of two files using the MD5CryptoServiceProvider class in Windows Powershell.
Firstly, we will need to create the ‘System.Security.Cryptography.MD5CryptoServiceProvider’ object within our session and store this as a variable.
$MD5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
Once the object has been created we can now compare the MD5 checksum of the two files, by converting the numeric value of each element of a specified array of bytes to its equivalent hexadecimal string representation. As I want to compare these MD5 checksums I will also store these as variables for each file.
$NSCMaster = [System.BitConverter]::ToString($MD5.ComputerHash([System.IO.File]::ReadAllBytes("\\Server\Share\NSClient++\NSC.ini"))) $NSCLocal = [System.BitConverter]::ToString($MD5.ComputerHash([System.IO.File]::ReadAllBytes("C:\Program Files\NSClient++\NSC.ini")))
The reasoning for me using the MD5 checksum to compare two files is to verify if my monitored servers are using the most recent configuration file which is stored in a shared folder and then to report back the status to Nagios, where if the MD5 checksum is the status is reported as ‘OK’, if this does not match is will report a status of ‘Warning’. Therefore in addition to the above I have
If ($NSLocal -eq $NSCMaster) { $returncode = 0 } ElseIf ($NSLocal -ne $NSMaster) { $returncode = 1 }
Once the status has been determined we will generate the status information by returning the 128-bit (16-byte) hash value of the local configuration file and exit the powershell session returning the exit code.
"The MD5 hash value is " + $NSLocal exit $returncode
Nice article to read and very helpful
LikeLike