powershell 逐个比较多个文件的哈希值

epggiuax  于 2023-06-06  发布在  Shell
关注(0)|答案(3)|浏览(176)

所以我有两个服务器和两个文件夹,它们应该包含相同的 *.jar,这意味着相同的哈希。我试图比较前2罐从第一个到2罐从第二个服务器。使用下面的语句总是返回Different,因为它不是单独获取每个文件。

$FileHash1 = (Get-FileHash '\\server1\c$\some_folder\*jar').Hash
$FileHash2 = (Get-FileHash '\\server2\c$\some_folder\*jar').Hash
if($FileHash1 -eq $FileHash2) {
    Write-Host "Equal"
} Else {
    Write-Host "Different"
}

我明白,在某个地方应该有foreach,但似乎找不到如何确切地使它的工作。

7nbnzgx9

7nbnzgx91#

所以你可以使用Group-Object来实现,将的哈希数组分组,如果有一个组的.Count1,那么你就可以确定文件夹之间存在差异。假设源文件夹没有重复

[array] $FileHash1 = (Get-FileHash '\\server1\c$\some_folder\*jar').Hash
[array] $FileHash2 = (Get-FileHash '\\server2\c$\some_folder\*jar').Hash

# If there is output from here, then for sure there is a difference between the folders
$FileHash1 + $FileHash2 | Group-Object | ? Count -EQ 1

另一种方法是使用为此设计的cmdlet:

# Create a source Catalog (only once)
$newFileCatalogSplat = @{
    Path            = '\\server1\c$\some_folder\*.jar'
    CatalogFilePath = 'path\to\mycatalog.cat'
}
New-FileCatalog @newFileCatalogSplat

# Then you can use it to test against any other path
$testFileCatalogSplat = @{
    CatalogFilePath = 'path\to\mycatalog.cat'
    Path            = '\\server2\c$\some_folder\*.jar'
    Detailed        = $true
}
Test-FileCatalog @testFileCatalogSplat
scyqe7ek

scyqe7ek2#

正如注解中提到的,你可以使用Compare-Object来比较两个集合--如果它们是对称的,Compare-Object不会输出任何东西,所以测试不对称性就像测试 * 任何输出 * 一样简单:

if(-not(Compare-Object $fileHash1 $fileHash2 |Select -First 1)) {
    "Equal"
}

如果需要测试多个服务器,请选择一个作为参考,并将所有其他服务器与之进行比较:

$reference,$rest = 'server1', 'server2', 'server3', 'server4'

$referenceList = @(Get-FileHash "\\${reference}\c$\some_folder\*jar" |ForEach-Object Hash)

foreach($otherServer in $rest) {
    $otherList = @(Get-FileHash "\\${otherServer}\c$\some_folder\*jar" |ForEach-Object Hash)
    $differences = Compare-Object $referenceList $otherList
    if ($differences) {
        Write-Warning "At least one file on '${otherServer}' is different from '${reference}'"
        # you might want to log $differences to a file here 
    }
}
cwtwac6a

cwtwac6a3#

如果您的文件具有相同的名称,您可以创建一个文件名列表(实际上是一个数组),并比较它们:

$Files = ("name1.jar", "name2.jar")

Foreach ($File in $Files) {
    $FileHash1 = (Get-FileHash "\\server1\c$\some_folder\$($File)").Hash
    $FileHash2 = (Get-FileHash "\\server2\c$\some_folder\$(File)").Hash
    if($FileHash1 -eq $FileHash2) {
        Write-Host $File "are equal"
    } Else {
        Write-Host $File "are different"
    }
}

相关问题