Josh Richards
Josh Richards

Reputation: 13

Powershell if file is different then do something

As the title suggests, how do I do an if statement for comparing 2 files? This is what I have so far but even though the files are the same it still keeps prompting me for an update

Add-Type -AssemblyName 'PresentationFramework'

$continue = 'Yes'
Invoke-WebRequest -Uri "https://<url>/file" -OutFile "C:\temp\file"
if ( "C:\temp\file" -ne "C:\app\file" ) {
    $caption = "Update Available!"    
    $message = "There is a new version available. Do you want to update to the latest version?"

    $continue = [System.Windows.MessageBox]::Show($message, $caption, 'YesNo');
} else {
    Write-Output "You have the latest version!"
}

if ($continue -eq 'Yes') {
    Write-Output "Downloading application Please wait..."
    // Do something //
} else {
    Write-Output "Cancelled"
}

Any help would be greatly appreciated! Thanks

Upvotes: 1

Views: 91

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 60060

This is the logic I would personally follow, you can re-estructure it later for your need but in very basic steps:

  1. Get the MD5 sum of my current file.
  2. Query the new file with Invoke-WebRequest and using a MemoryStream check if the new hash is the same as the previous one.
  3. If it's not, write that stream to a FileStream.
$ErrorActionPreference = 'Stop'

try {
    $previousFile = "C:\app\file"
    $previousHash = (Get-FileHash $previousFile -Algorithm MD5).Hash

    $webReq    = Invoke-WebRequest 'https://<url>/file'
    $memStream = [IO.MemoryStream] $webReq.Content
    $newHash   = (Get-FileHash -InputStream $memStream -Algorithm MD5).Hash

    if($previousHash -ne $newHash) {
        $file = [IO.File]::Create('path\to\mynewfile.ext')
        $memStream.WriteTo($file)
    }
}
finally {
    $file, $memStream | ForEach-Object Dispose
}

The main idea behind it is to check all in memory so as to avoid the need to download a file if not needed.

Upvotes: 1

Related Questions