在無第三方工具、純系統內建環境(Windows Script Host)下快速獲取文件 MD5、大小、版本、屬性等資訊。
Windows Installer 服務提供的 COM 物件,暴露 FileHash 方法可計算文件雜湊(支援 MD5、SHA1 等)。
Option Explicit
Dim wi, file, file_size, file_attributes, file_version, file_hash
Set wi = CreateObject("WindowsInstaller.Installer")
file = "C:\WINDOWS\explorer.exe"
file_size = wi.FileSize(file)
file_attributes = wi.FileAttributes(file)
file_version = wi.FileVersion(file)
file_hash = GetFileHash(file)
Set wi = Nothing
MsgBox "File: " & file & vbCrLf & _
"Size: " & file_size & vbCrLf & _
"Attributes: " & file_attributes & vbCrLf & _
"Version: " & file_version & vbCrLf & _
"MD5: " & file_hash
Function GetFileHash(file_name)
Dim file_hash, hash_value, i
' 0 = MD5, 1 = SHA1, 2 = SHA256, 3 = SHA384, 4 = SHA512
Set file_hash = wi.FileHash(file_name, 0)
hash_value = ""
For i = 1 To file_hash.FieldCount
' IntegerData 返回小端序 32 位整數,需轉大端序十六進位
hash_value = hash_value & BigEndianHex(file_hash.IntegerData(i))
Next
GetFileHash = hash_value
Set file_hash = Nothing
End Function
Function BigEndianHex(int_val)
Dim result, b1, b2, b3, b4
result = Hex(int_val) ' 返回不足 8 位前導零會缺失
' 補零至 8 字符
result = Right("00000000" & result, 8)
b1 = Mid(result, 7, 2)
b2 = Mid(result, 5, 2)
b3 = Mid(result, 3, 2)
b4 = Mid(result, 1, 2)
BigEndianHex = b1 & b2 & b3 & b4
End Function
FileHash(path, type):type=0 為 MD5,返回 Record 物件。Record.FieldCount:MD5 為 4 個 32 位字段(共 128 位)。Record.IntegerData(i):返回**小端序**整數(低位在前),需逐字節反轉為標準大端序十六進位顯示。BigEndianHex:補零 + 字節序交換 (12345678 → 78563412)。| 優點 | 缺點 |
|---|---|
| 零依賴,系統內建 | 需 Windows Installer 服務啟動 |
| 同時獲取大小/版本/屬性 | VBScript 效能較低,大量文件不適用 |
| 代碼極簡單 | 僅限 Windows 平台 |