Repository navigation
Expand file tree
/
Copy pathInvokeWeb.psm1
More file actions
249 lines (217 loc) · 11 KB
/
Copy pathInvokeWeb.psm1
File metadata and controls
249 lines (217 loc) · 11 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
#Requires -Version 2
###############################################################################
## Copyright (c) 2013 by Joel Bennett, all rights reserved.
## Free for use under MS-PL, MS-RL, GPL 2, or BSD license. Your choice.
###############################################################################
## InvokeWeb.psm1 defines a subset of the Invoke-WebRequest functionality
## On PowerShell 3 and up we'll just use the built-in Invoke-WebRequest
if(!(Get-Command Invoke-WebReques[t])) {
# FULL # BEGIN FULL: Don't include this in the installer script
$PoshCodeModuleRoot = Get-Variable PSScriptRoot -ErrorAction SilentlyContinue | ForEach-Object { $_.Value }
if(!$PoshCodeModuleRoot) {
$PoshCodeModuleRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
}
. $PoshCodeModuleRoot\Constants.ps1
# FULL # END FULL
function Invoke-WebRequest {
<#
.Synopsis
Downloads a file or page from the web, or sends web API posts/requests
.Description
Creates an HttpWebRequest to download a web file or post data. This is a restricted
.Example
Invoke-Web http://PoshCode.org/PoshCode.psm1
Downloads the latest version of the PoshCode module to the current directory
.Example
Invoke-Web http://PoshCode.org/PoshCode.psm1 ~\Documents\WindowsPowerShell\Modules\PoshCode\
Downloads the latest version of the PoshCode module to the default PoshCode module directory...
.Example
$RssItems = @(([xml](Invoke-WebRequest http://poshcode.org/api/)).rss.channel.GetElementsByTagName("item"))
Returns the most recent items from the PoshCode.org RSS feed
#>
[CmdletBinding(DefaultParameterSetName="NoSession")]
param(
# The URL of the file/page to download
[Parameter(Mandatory=$true,Position=0)]
[System.Uri][Alias("Url")]$Uri, # = (Read-Host "The URL to download")
# Specifies the method used for the web request. Valid values are Default, Delete, Get, Head, Options, Post, Put, and Trace. Default value is Get.
[ValidateSet("Default", "Get", "Head", "Post", "Put", "Delete", "Trace", "Options", "Merge", "Patch")]
[String]$Method = "Get",
# Sends the results to the specified output file. Enter a path and file name. If you omit the path, the default is the current location.
# By default, Invoke-WebRequest returns the results to the pipeline. To send the results to a file and to the pipeline, use the Passthru parameter.
[Parameter()]
[Alias("OutPath")]
[string]$OutFile,
# Text to include at the front of the UserAgent string
[string]$UserAgent = "Mozilla/5.0 (Windows NT; Windows NT $([Environment]::OSVersion.Version.ToString(2)); $PSUICulture) WindowsPowerShell/$($PSVersionTable.PSVersion.ToString(2)); PoshCode/4.0; http://PoshCode.org",
# Specifies the client certificate that is used for a secure web request. Enter a variable that contains a certificate or a command or expression that gets the certificate.
# To find a certificate, use Get-PfxCertificate or use the Get-ChildItem cmdlet in the Certificate (Cert:) drive. If the certificate is not valid or does not have sufficient authority, the command fails.
[System.Security.Cryptography.X509Certificates.X509Certificate[]]
$ClientCertificate,
# Pass the default credentials
[switch]$UseDefaultCredentials,
# Specifies a user account that has permission to send the request. The default is the current user.
# Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet.
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
[Alias("")]$Credential = [System.Management.Automation.PSCredential]::Empty,
# Specifies that Authorization: Basic should always be sent. Requires $Credential to be set, and should only be used with https
[ValidateScript({if(!($Credential -or $WebSession)){ throw "ForceBasicAuth requires the Credential parameter be set"} else { $true }})]
[switch]$ForceBasicAuth,
# Uses a proxy server for the request, rather than connecting directly to the Internet resource. Enter the URI of a network proxy server.
# Note: if you have a default proxy configured in your internet settings, there is no need to set it here.
[Uri]$Proxy,
# Pass the default credentials to the Proxy
[switch]$ProxyUseDefaultCredentials,
# Pass specific credentials to the Proxy
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$ProxyCredential= [System.Management.Automation.PSCredential]::Empty
)
process {
$EAP,$ErrorActionPreference = $ErrorActionPreference, "Stop"
$request = [System.Net.HttpWebRequest]::Create($Uri)
if($DebugPreference -ne "SilentlyContinue") {
Set-Variable WebRequest -Scope 2 -Value $request
}
$ErrorActionPreference = $EAP
# And override session values with user values if they provided any
$request.UserAgent = $UserAgent
# Authentication normally uses EITHER credentials or certificates, but what do I know ...
if($ClientCertificate) {
$request.ClientCertificates.AddRange($ClientCertificate)
}
if($UseDefaultCredentials) {
$request.UseDefaultCredentials = $true
} elseif($Credential -ne [System.Management.Automation.PSCredential]::Empty) {
$request.Credentials = $Credential.GetNetworkCredential()
}
# You don't have to specify a proxy to specify proxy credentials (maybe your default proxy takes creds)
if($Proxy) { $request.Proxy = New-Object System.Net.WebProxy $Proxy }
if($request.Proxy -ne $null) {
if($ProxyUseDefaultCredentials) {
$request.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
} elseif($ProxyCredentials -ne [System.Management.Automation.PSCredential]::Empty) {
$request.Proxy.Credentials = $ProxyCredentials
}
}
if($ForceBasicAuth) {
if(!$request.Credentials) {
throw "ForceBasicAuth requires Credentials!"
}
$request.Headers.Add('Authorization', 'Basic ' + [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($request.Credentials.UserName+":"+$request.Credentials.Password )));
}
try {
$response = $request.GetResponse();
if($DebugPreference -ne "SilentlyContinue") {
Set-Variable WebResponse -Scope 2 -Value $response
}
} catch [System.Net.WebException] {
Write-Error $_.Exception -Category ResourceUnavailable
return
} catch { # Extra catch just in case, I can't remember what might fall here
Write-Error $_.Exception -Category NotImplemented
return
}
Write-Verbose "Retrieved $($Response.ResponseUri): $($Response.StatusCode)"
if((Test-Path variable:response) -and $response.StatusCode -eq 200) {
Write-Verbose "OutFile: $OutFile"
# Magics to figure out a file location based on the response
if($OutFile) {
$EAP,$ErrorActionPreference = $ErrorActionPreference, "Stop"
# When you need to convert a path that might not exist yet ...
$OutFile = New-Item -Path $OutFile -Type File -Force | Convert-Path
$ErrorActionPreference = $EAP
}
if(!$OutFile) {
$Headers = @{}
foreach($h in $response.Headers){ $Headers.$h = $response.GetResponseHeader($h) }
$Result = @{
BaseResponse = $response
Headers = $Headers
RawContentStream = New-Object System.IO.MemoryStream $response.ContentLength
RawContentLength = $response.ContentLength
Content = $null
StatusCode = [int]$response.StatusCode
StatusDescription = $response.StatusDescription
}
if($response.CharacterSet) {
$encoding = [System.Text.Encoding]::GetEncoding( $response.CharacterSet )
$Result.Content = ""
} else {
$encoding = $null
$Result.Content = New-Object 'byte[]' $response.ContentLength
}
}
try {
[int]$goal = $response.ContentLength
$reader = $response.GetResponseStream()
$ms =
if($OutFile) {
try {
$writer = New-Object System.IO.FileStream $OutFile, "Create"
} catch { # Catch just in case, lots of things could go wrong ...
Write-Error $_.Exception -Category WriteError
return
}
}
[byte[]]$buffer = new-object byte[] 1mb
[int]$total = [int]$count = 0
do
{
$count = $reader.Read($buffer, 0, $buffer.Length);
if($OutFile) {
$writer.Write($buffer, 0, $count)
} else {
$Result.RawContentStream.Write($buffer, 0, $count)
if($encoding) {
$Result.Content += $encoding.GetString($buffer,0,$count)
}
}
# This is unecessary, but nice to have
if(!$quiet) {
$total += $count
if($goal -gt 0) {
Write-Progress -Activity "Downloading $Uri" -Status "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100)
} else {
Write-Progress -Activity "Downloading $Uri" -Status "Saving $total bytes..." -id 0
}
}
} while ($count -gt 0)
} catch [Exception] {
$PSCmdlet.WriteError( (New-Object System.Management.Automation.ErrorRecord $_.Exception, "Unexpected Exception", "InvalidResult", $_) )
Write-Error "Could not download package from $Url"
} finally {
if(Test-Path variable:Reader) {
$Reader.Close()
$Reader.Dispose()
}
if(Test-Path variable:Writer) {
$writer.Flush()
$Writer.Close()
$Writer.Dispose()
}
}
if(!$Outfile -and !$encoding) {
[Array]::Copy( $Result.RawContentStream.GetBuffer(), $Result.Content, $response.ContentLength )
}
Write-Progress -Activity "Finished Downloading $Uri" -Status "Saved $total bytes..." -id 0 -Completed
# I have a fundamental disagreement with Microsoft about what the output should be
if($OutFile) {
Get-Item $OutFile
} elseif(Test-Path variable:local:Result) {
$Result = New-Object PSObject -Property $Result
$Result.PSTypeNames.Insert(0, "Microsoft.PowerShell.Commands.WebResponseObject")
$Result.PSTypeNames.Insert(0, "Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject")
return $Result
}
}
if(Test-Path variable:response) {
$response.Close();
# HttpWebResponse doesn't have Dispose (in .net 2?)
# $response.Dispose();
}
}
}
Export-ModuleMember Invoke-WebRequest
}