powershellshellhashget-filehash

Powershell Script to compare File-Hash from a Stream and published


Good morning guys,

I'm new to powershell scripting. And i can't figure out what I'm doing wrong.

I tried to write a .ps1 script to compare the hash value of a stream. I used the microsoft documentation for help and modify it to a runable script so i don't need to write it over and over again.

$wc = [System.Net.WebClient]::new()
$pkgurl = Read-Host "Please enter Package Url: "
$publishedHash = Read-Host "Enter Published Hash: "
$FileHash = Get-FileHash -InputStream ($wc.OpenRead($pkgurl))
if ($FileHash.Hash -eq $publishedHash) {
    Write-Host "File Hash is equal to published Hash."
}
else {
    Write-Host "File Hash NOT equal to published Hash."
}

When i run the script and enter the package url and the published Hash, the program all of a sudden abruptly shuts down.

Please, anyone an idea?


Solution

  • The script ends as it has nothing else to do.

    You can add read-host at the end to wait for user input before it closes. (it wont do anything with the input, this just forces it to stay open until input has been made.)

    Alternatively if you want to use it multiple times without it closing you can create a loop:

    $KeepOpen = $true
    
    While($KeepOpen -eq $true){
        $wc = [System.Net.WebClient]::new()
        $pkgurl = Read-Host "Please enter Package Url: "
        $publishedHash = Read-Host "Enter Published Hash: "
        $FileHash = Get-FileHash -InputStream ($wc.OpenRead($pkgurl))
        if ($FileHash.Hash -eq $publishedHash) {
            Write-Host "File Hash is equal to published Hash."
        }
        else {
            Write-Host "File Hash NOT equal to published Hash."
        }
        $user_input = Read-Host "Please enter Y to run again"
        if($user_input -ne "Y"){
            $KeepOpen = $false
        }
    }
    

    This will keep the script open so you can see the results and if you want it to run again insert Y and hit enter and you should be back to where you start.