How do I check the filehash of a file thats online in PowerShell?

Viewed 169

So well, I am making a pull request to Chris Titus Tech's Ultimate Windows Toolkit, and I wanna make something that checks if it's updated. But when I try running:

Get-FileHash -Algorithm SHA256 https://raw.githubusercontent.com/fgclue/etcher/master/desktop.ini

It just says:

Get-FileHash: Cannot find drive. A drive with the name 'https' does not exist. And I want to make it look something like this:

$hash = Get-FileHash -Algorithm SHA256 URL
$chash = Get-FileHash -Algorithm SHA256 win10debloat.ps1

if ($hash -ne $chash){
     Write-Host "There is an update!"
     Write-Host "Update?"
     $Opt = Read-Host "Choice"     
     if (Opt -ne y){
          exit
     }
     if (Opt -ne yn){
          Start-Process "https://github.com/ChrisTitusTech/win10script/"
          Write-Host Please download the new version and close this windows.
     }
}
1 Answers

I'm not totally sure what actually you want to compare but here is how you can test if what you have is up to date without downloading anything to your disk, in this case I believe you need to use IO.MemoryStream to get the hash of the remote file.

$uri = 'https://raw.githubusercontent.com/fgclue/etcher/master/desktop.ini'
$theHashIHave = Get-FileHash myfilehere.ext -Algorithm SHA256

try {
    $content = Invoke-RestMethod $uri
    $memstream = [System.IO.MemoryStream]::new($content.ToCharArray())
    $thisFileHash = Get-FileHash -InputStream $memstream -Algorithm SHA256
    if($theHashIhave.Hash -eq $thisFileHash.Hash) {
        "all good"
    }
    else {
        "should update here"
    }
}
finally {
    $memstream.foreach('Dispose')
}

In the off chance you need to use a specific encoding to get the hash, for example UTF8 Encoding with a BOM, you can use the following:

$memstream = [System.IO.MemoryStream]::new(
    [System.Text.Encoding]::UTF8.GetBytes($content)
)

However this way you need to make sure the encoding you're using is correct, i.e.: if you need UTF8 no BOM, use [System.Text.UTF8Encoding]::new().GetBytes(...) instead, etc.

Related