Created
April 11, 2021 13:03
-
-
Save MattHodge/c102c75d65420852fe8424ba8e75ba25 to your computer and use it in GitHub Desktop.
Save-Download.ps1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If the download link contains Chinese, it will fail. You can test the replay with this command:
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!😀