Skip to content

Instantly share code, notes, and snippets.

@MattHodge
Created April 11, 2021 13:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save MattHodge/c102c75d65420852fe8424ba8e75ba25 to your computer and use it in GitHub Desktop.
Save MattHodge/c102c75d65420852fe8424ba8e75ba25 to your computer and use it in GitHub Desktop.
Save-Download.ps1
function Save-Download {
<#
.SYNOPSIS
Given a the result of WebResponseObject, will download the file to disk without having to specify a name.
.DESCRIPTION
Given a the result of WebResponseObject, will download the file to disk without having to specify a name.
.PARAMETER WebResponse
A WebResponseObject from running an Invoke-WebRequest on a file to download
.EXAMPLE
# Download Microsoft Edge
$download = Invoke-WebRequest -Uri "https://go.microsoft.com/fwlink/?linkid=2109047&Channel=Stable&language=en&consent=1"
$download | Save-Download
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline)]
[Microsoft.PowerShell.Commands.WebResponseObject]
$WebResponse,
[Parameter(Mandatory = $false)]
[string]
$Directory = "."
)
$errorMessage = "Cannot determine filename for download."
if (!($WebResponse.Headers.ContainsKey("Content-Disposition"))) {
Write-Error $errorMessage -ErrorAction Stop
}
$content = [System.Net.Mime.ContentDisposition]::new($WebResponse.Headers["Content-Disposition"])
$fileName = $content.FileName
if (!$fileName) {
Write-Error $errorMessage -ErrorAction Stop
}
if (!(Test-Path -Path $Directory)) {
New-Item -Path $Directory -ItemType Directory
}
$fullPath = Join-Path -Path $Directory -ChildPath $fileName
Write-Verbose "Downloading to $fullPath"
$file = [System.IO.FileStream]::new($fullPath, [System.IO.FileMode]::Create)
$file.Write($WebResponse.Content, 0, $WebResponse.RawContentLength)
$file.Close()
}
@GanZhiXiong
Copy link

If the download link contains Chinese, it will fail. You can test the replay with this command:

Invoke-WebRequest -Uri "https://transfer.sh/0woMhf/奥图数据上传工具.exe" | Save-Download

I feel like using UTF-8 encoding would work, but invoke-WebreQuest doesn't seem to support it.

Looking forward to your reply, thank you!😀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment