-
-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathSave-Download.ps1
More file actions
50 lines (40 loc) · 1.65 KB
/
Save-Download.ps1
File metadata and controls
50 lines (40 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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()
}