Windows Folder And Files Hashes Comparison 資料夾與檔案雜湊值清單與比較


  1. 說明
    1. Get Folder All Files And Its Hashes
    2. Two Folder Comparison
  2. 相關技巧

說明如何使用 PowerShell 來取得所有檔案的 FileHash 用於監督檔案是否有竄改或者不一致的情形,以及說明如何針對兩個資料夾來源比較 Symmetric Difference 的檔案差異。

logo

說明

Get Folder All Files And Its Hashes

$folderPath = "C:\folder1"
$outputFile = "C:\temp\file.csv"

$files = Get-ChildItem -Path $folderPath -File -Recurse

$fileInfoArray = @()

foreach ($file in $files) {
    $fileInfoObject = [PSCustomObject]@{
        FileName = $file.Name
        FilePath = $file.FullName
        FileExtension = $file.Extension
        FileHash = (Get-FileHash -Path $filePath).Hash
        Size = $file.Length
        CreatedDate = $file.CreationTime.ToString("yyyy/MM/dd HH:mm:ss")
        ModifiedDate = $file.LastWriteTime.ToString("yyyy/MM/dd HH:mm:ss")
    }

    $fileInfoArray += $fileInfoObject
}


$fileInfoArray | Export-Csv -Path $outputFile -NoTypeInformation

Two Folder Comparison

$folder1 = "C:\folder1"
$folder2 = "C:\folder2"
$outputFile = "C:\filehash.csv"

$hashTable1 = @{}
$hashTable2 = @{}
$result = @{}

$files1 = Get-ChildItem -Path $folder1 -File -Recurse
$files2 = Get-ChildItem -Path $folder2 -File -Recurse

foreach ($file in $files1) {
    $hash = (Get-FileHash -Path $file.FullName).Hash
    $hashTable1[$hash] = $file
}

foreach ($file in $files2) {
    $hash = (Get-FileHash -Path $file.FullName).Hash
    $hashTable2[$hash] = $file
}

# Add hashTable1 distinct item to result
foreach ($key in $hashTable1.keys) {
    if (-not $hashTable2.Contains($key)) {
      $result[$key] = $hashTable1[$key]
    }
}

# Add hashTable2 distinct item to result
foreach ($key in $hashTable2.keys) {
    if (-not $hashTable1.Contains($key)) {
      $result[$key] = $hashTable2[$key]
    }
}


$fileInfoArray = @()
foreach ($file in $result.values) {
    $fileInfoObject = [PSCustomObject]@{
        FileName = $file.Name
        FilePath = $file.fullName
        FileExtension = $file.Extension
        FileHash = (Get-FileHash $file.FullName).Hash
        Size = $file.Length
        CreatedDate = $file.CreationTime.ToString("yyyy/MM/dd HH:mm:ss")
        ModifiedDate = $file.LastWriteTime.ToString("yyyy/MM/dd HH:mm:ss")
    }

    $fileInfoArray += $fileInfoObject
}

$fileInfoArray | Export-Csv -Path $outputFile -NoTypeInformation

相關技巧

如果是想要從眾多的檔案當中,比對 Hash 找到檔案則可以參考 PowerShell Find File With FileHash (比對 FileHash 搜尋檔案)