My Profile Photo

Matthew Hodgkins Blog


❤️er of Platform Engineering, SRE, K8s, Golang, Observability and working with nice humans. Aussie living in the Netherlands.


Downloading a file with PowerShell without specifying its name

I’m going to show you how to download a file from the web using PowerShell without having to specify the filename on download.

This definately falls into the category of “why is this so hard in PowerShell?”. Looks like some other folks agree: github.com/PowerShell/issues/11671.

Usually you would need to use -Outfile to download a file, for example:

Invoke-WebRequest -Uri "https://go.microsoft.com/fwlink/?linkid=2109047&Channel=Stable&language=en&consent=1" -Outfile "MicrosoftEdgeSetup.exe"

How does the browser know what file to give the download though?

Edge Download

Let’s find out:

$download = Invoke-WebRequest -Uri "https://go.microsoft.com/fwlink/?linkid=2109047&Channel=Stable&language=en&consent=1"

$download.Headers

With that we can see the name of the download:

Download

To get the file name out:

$content = [System.Net.Mime.ContentDisposition]::new($download.Headers["Content-Disposition"])
$content

Show Filename

Now we could take that file name and run another Invoke-WebRequest with a -Outfile parameter, but that would involve downloading the entire file again.

Let’s save the contents of our $download variable to disk.

$fileName = $content.FileName

$file = [System.IO.FileStream]::new($fileName, [System.IO.FileMode]::Create)
$file.Write($download.Content, 0, $download.RawContentLength)
$file.Close()

Now we have MicrosoftEdgeSetup.exe saved.

Finally

Here is the Save-Download function which makes this process easier: