forked from brianary/scripts
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Save-WebRequest.ps1
67 lines (55 loc) · 2.01 KB
/
Save-WebRequest.ps1
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<#
.SYNOPSIS
Downloads a given URL to a file, automatically determining the filename.
.INPUTS
Object with System.Uri property named Uri.
.FUNCTIONALITY
HTTP
.LINK
https://tools.ietf.org/html/rfc2183
.LINK
http://test.greenbytes.de/tech/tc2231/
.LINK
https://msdn.microsoft.com/library/system.net.mime.contentdisposition.filename.aspx
.LINK
https://msdn.microsoft.com/library/system.io.path.getinvalidfilenamechars.aspx
.LINK
Invoke-WebRequest
.LINK
Invoke-Item
.LINK
Move-Item
.EXAMPLE
Save-WebRequest.ps1 https://www.irs.gov/pub/irs-pdf/f1040.pdf -Open
Saves f1040.pdf (or else a filename specified in the Content-Disposition header) and opens it.
#>
[CmdletBinding()][OutputType([void])] Param(
# The URL to download.
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[Alias('Url','Href','Src')][uri] $Uri,
# Sets the creation time on the file to the given value.
[datetime] $CreationTime,
# Sets the creation time on the file to the given value.
[datetime] $LastWriteTime,
# When present, invokes the file after it is downloaded.
[switch] $Open
)
Begin
{
function Get-ValidFileName([string]$filename)
{($filename -replace '(\A.*[\\/])?','').Split([IO.Path]::GetInvalidFileNameChars()) -join ''}
}
Process
{
$filename = Get-ValidFileName $Uri.Segments[-1]
$response = Invoke-WebRequest $Uri -OutFile $filename -PassThru
if(([Collections.IDictionary]$response.Headers).Contains('Content-Disposition'))
{
[Net.Mime.ContentDisposition]$disposition = $response.Headers['Content-Disposition']
$suggestedFilename = Get-ValidFileName $disposition.FileName
if($filename -cne $suggestedFilename) {Move-Item $filename $suggestedFilename; $filename = $suggestedFilename}
}
if($PSBoundParameters.ContainsKey('CreationTime')) {(Get-Item $filename).CreationTime = $CreationTime}
if($PSBoundParameters.ContainsKey('LastWriteTime')) {(Get-Item $filename).LastWriteTime = $LastWriteTime}
if($Open) {Invoke-Item $filename}
}