-
Notifications
You must be signed in to change notification settings - Fork 63
/
FastWebRequest.psm1
66 lines (57 loc) · 1.86 KB
/
FastWebRequest.psm1
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
$ErrorActionPreference = "Stop"
# Nano server does not include Invoke-WebRequest
function Invoke-FastWebRequest
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline=$true,Position=0)]
[System.Uri]$Uri,
[Parameter(Position=1)]
[string]$OutFile
)
PROCESS
{
if(!([System.Management.Automation.PSTypeName]'System.Net.Http.HttpClient').Type)
{
$assembly = [System.Reflection.Assembly]::LoadWithPartialName("System.Net.Http")
}
[Environment]::CurrentDirectory = (pwd).Path
if(!$OutFile)
{
$OutFile = $Uri.PathAndQuery.Substring($Uri.PathAndQuery.LastIndexOf("/") + 1)
if(!$OutFile)
{
throw "The ""OutFile"" parameter needs to be specified"
}
}
$client = new-object System.Net.Http.HttpClient
$task = $client.GetAsync($Uri)
$task.wait()
$response = $task.Result
$status = $response.EnsureSuccessStatusCode()
$outStream = New-Object IO.FileStream $OutFile, Create, Write, None
try
{
$task = $response.Content.ReadAsStreamAsync()
$task.Wait()
$inStream = $task.Result
$contentLength = $response.Content.Headers.ContentLength
$totRead = 0
$buffer = New-Object Byte[] 1MB
while (($read = $inStream.Read($buffer, 0, $buffer.Length)) -gt 0)
{
$totRead += $read
$outStream.Write($buffer, 0, $read);
if($contentLength)
{
$percComplete = $totRead * 100 / $contentLength
Write-Progress -Activity "Downloading: $Uri" -PercentComplete $percComplete
}
}
}
finally
{
$outStream.Close()
}
}
}