This might take you 2 minutes to read.

For a small project we will use Powershell to verify if a file on github is updated and then download it.

We could download it and test the file size and do other stuff. A colleague of mine came up with a better idea. why don’t we use http-protocol to do that for us.

He knew how to do that with curl. My job was to take it to powershell.

The command to use was Invoke-webrequest. and use “-headers” to bring the wanted header.

Invoke-WebRequest-Uri$sourcepath-Headers @{"If-None-Match"="idToCompare"}

With that request I http compares my string withe the one on the server. To catch the file and to be able to handle the object I fetch it in a variable and saves the file to disk and stores the new id in registry.

	$sourcepath      = 'https://installer.msi'
	$destinationpath = "C:temppath"
	$filename        = "installer.msi"
	$registry        = "hklm:softwareapplicationname"
	$logname         = "eventlogname"
	$logsource       = "eventlogsource"

	if (-not (Get-EventLog -list | Where-Object {$_.logdisplayname -eq $logname})) {
	New-EventLog -LogName $logname -Source $logsource
	}

	$wp = New-Object Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())
	if (-not $wp.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) {
	Write-Eventlog  -Logname $logname -Source $logsource -EventID 1000 -EntryType Error -Message "File downloader-script requires administrative privileges, please re-launch with elevated credentials."
	#exit
	}

	if (-not (test-path($destinationpath))){
	New-Item -ItemType Directory -Force -Path ($destinationpath)
	}
	if (-not (test-path($registry))){
	New-Item -Path hklm:software -Name applicationname
	}

	if((Get-ItemProperty $registry -Name "etag" -ErrorAction 0).etag) {
	$etag = (Get-Itemproperty $registry -Name "etag").etag
	}else{ 
	$etag = "0x0x0"
	Set-ItemProperty -Path $registry  -Name "etag" -Value $etag
	}

	try {
	$abb = Invoke-WebRequest -Uri $sourcepath -Headers @{"If-None-Match"=$etag} 

	[io.file]::WriteAllBytes(($destinationpath+$filename), $abb.Content)
	$etag = $abb.headers.etag
	Set-ItemProperty -Path $registry -Name etag -Value $etag
	}
	catch {
	}


And voila.

Now it needs some more error handling and logging and obvious an installation of the msi… but that is another days work.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.