Save File out of return value from invoke-webrequest

Viewed 2013

I am trying to download a file from a website with powershell and save it in a C:\temp dir with it's original name

if i try Invoke-WebRequest -Uri ("uri to file download") -Method Get with the "-OutFile" Parameter i can save the file but not with the original name. if i save the WebRequest return value in a parameter i find the original filename under $r.Headers.'Content-Disposition' but i don't know how to output "the file" out of this variable.

can any one help me ?

Kind regards Florian

1 Answers

I just created a quick snippet that should help you. Sadly, I couldn't test it without a valid URL :(

# Vars
$url = ""
$outputDir = $PSScriptRoot

# Invoke request
$result = Invoke-WebRequest -Method GET -Uri $url

# Extract name
$contentDisposition = $result.Headers.'Content-Disposition'
$fileName = $contentDisposition.Split("=")[1].Replace("`"","")
$path = Join-Path $outputDir $fileName

# Write into file
$file = [System.IO.FileStream]::new($path, [System.IO.FileMode]::Create)
$file.write($result.Content, 0, $result.RawContentLength)
$file.close()
Related