2009-09-23

Powershell & Get-HashFile

Avendo la necessità di calcolare l'hash di un file all'interno di uno script Powershell, mi sono preparato questa piccola funzione che fa al caso mio:

function Get-HashFile([System.IO.FileInfo[]] $file)
{    
        if (($file.Count -le 0) )
        {
            #Write-Host "NA"
            return $null             
        }
        
        [object[]] $out = New-Object object[] $file.Length
        
        for($z = 0; $z -lt $file.Length; $z++)
        {
            #Write-Host $file[$z].FullName
            [System.Security.Cryptography.SHA1Managed] $hashAlg = New-Object System.Security.Cryptography.SHA1Managed
            $str = New-Object System.IO.FileStream $file[$z].FullName, Open, Read
            [byte[]] $hash = $hashAlg.ComputeHash($str)
            #$out[$z] =  [System.BitConverter]::ToString($hash)
            $out[$z] = @{File=$file[$z]; FileHash=[System.BitConverter]::ToString($hash)}
            $str.Close()
            $str.Dispose()
        }
        return $out
}


$myFile = Get-Item c:\tmp\_Varie_\_Working\*.*
$test = Get-HashFile($myFile)
foreach($i in $test) {$i}

Le flessibilità e la potenzialità offerte dalla Powershell sono (come sempre) semplicemente fantastiche!a