-
Notifications
You must be signed in to change notification settings - Fork 14
/
Get-Web.ps1
1481 lines (1225 loc) · 62.7 KB
/
Get-Web.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
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function Get-Web {
<#
.Synopsis
Gets content from the web, or parses web content.
.Description
Gets content from the web.
If -Tag is passed, extracts out tags from within the document.
If -AsByte is passed, returns the response bytes
.Example
# Download the Microsoft front page and extract out links
Get-Web -Url http://microsoft.com/ -Tag a
.Example
# Extract the rows from ConvertTo-HTML
$text = Get-ChildItem | Select Name, LastWriteTime | ConvertTo-HTML | Out-String
Get-Web "tr" $text
.Example
# Extract all PHP elements from a directory of .php scripts
Get-ChildItem -Recurse -Filter *.php |
Get-Web -Tag .\?php, \?
.Example
# Extract all asp tags from .asp files
Get-ChildItem -Recurse |
Where-Object { '.aspx', '.asp'. '.ashx' -contains $_.Extension } |
Get-Web -Tag .\%
.Example
# Get a list of all schemas from schema.org
$schemasList = Get-Web -Url http://schema.org/docs/full.html -Tag a |
Where-Object { $_.Xml.href -like '/*' } |
ForEach-Object { "http://schema.org" + $_.xml.Href }
.Example
# Extract out the example of a schema from schema.org
$schema = 'http://schema.org/Event'
Get-Web -Url $schema -Tag pre |
Where-Object { $_.Xml.Class -like '*prettyprint*' } |
ForEach-Object {
Get-Web -Html $_.Xml.InnerText -AsMicrodata -ItemType $schema
}
.Example
# List the top 1000 sites on the web:
Get-Web "http://www.google.com/adplanner/static/top1000/" -Tag 'a' |
where-Object {$_.Tag -like "*_blank*" } |
ForEach-Object {
([xml]$_.StartTag.Replace('"t', '" t')).a.href
}
.Link
http://schema.org
#>
[CmdletBinding(DefaultParameterSetName='HTML')]
[OutputType([PSObject],[string])]
param(
# The tags to extract.
[Parameter(
ValueFromPipelineByPropertyName=$true)]
[string[]]$Tag,
# If used with -Tag, -RequireAttribute will only match tags with a given keyword in the tag
[string[]]$TextInTag,
# The source HTML.
[Parameter(Mandatory=$true,
ParameterSetName='HTML',
ValueFromPipelineByPropertyName=$true)]
[string]$Html,
# The Url
[Parameter(Mandatory=$true,
Position=0,
ParameterSetName='Url',
ValueFromPipelineByPropertyName=$true)]
[Alias('Uri')]
[string]$Url,
# The root of the website.
# All images, css, javascript, related links, and pages beneath this root will be downloaded into a hashtable
[Parameter(Mandatory=$true,
ParameterSetName='WGet',
ValueFromPipelineByPropertyName=$true)]
[string]$Root,
# Any parameters to the URL
[Parameter(ParameterSetName='Url',
Position=1,
ValueFromPipelineByPropertyName=$true)]
[Hashtable]$Parameter,
# Filename
[Parameter(Mandatory=$true,
ParameterSetName='FileName',
ValueFromPipelineByPropertyName=$true)]
[Alias('Fullname')]
[ValidateScript({$ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($_)})]
[string]$FileName,
# The User Agent
[Parameter(ParameterSetName='Url',
ValueFromPipelineByPropertyName=$true)]
[string]$UserAgent = "PowerShellPipeworks/Get-Web (1.0 powershellpipeworks.com)",
# If set, will not show progress for long-running operations
[Switch]$HideProgress,
# If set, returns resutls as bytes
[Alias('Byte', 'Bytes')]
[Switch]$AsByte,
# If set, returns results as XML
[Alias('Xml')]
[Switch]$AsXml,
# If set, returns results as json
[Switch]$AsJson,
# If set, extracts Microdata out of a page
[Alias('Microdata')]
[Switch]$AsMicrodata,
# If set, will get back microdata from the page that matches an itemtype
[string[]]$ItemType,
# If set, extracts OpenGraph information out of a page
[Switch]$OpenGraph,
# If set, will extract all meta tags from a page
[Switch]$MetaData,
# The MIME content type you're requesting from the web site
[string]$ContentType,
# The credential used to connect to the web site
[Parameter(ParameterSetName='Url',
ValueFromPipelineByPropertyName=$true)]
[Management.Automation.PSCredential]
$WebCredential,
# If set, will use the default user credential to connect to the web site
[Parameter(ParameterSetName='Url',
ValueFromPipelineByPropertyName=$true)]
[switch]
$UseDefaultCredential,
# The HTTP method to use
[Parameter(ParameterSetName='Url',
ValueFromPipelineByPropertyName=$true)]
[ValidateSet('GET','POST', 'PUT', 'DELETE', 'OPTIONS', 'HEAD', 'TRACE', 'CONNECT', 'MERGE')]
[string]$Method = "GET",
# a hashtable of headers to send with the request.
[Hashtable]$Header,
# The Request Body. This can be either a string, or bytes
$RequestBody,
# Any request ascii data. Data will be joined together with &, and will be sent in the request body.
[string[]]
$Data,
# If set, will use a the Net.WebRequest class to download. Otherwise, will use the xmlhttprequest.
# Xmlhttprequest adds some extra headers and caches GET requests, so, if you wish to avoid this, -UseWebRequest.
[Switch]
$UseWebRequest,
# A Progress Identifier. This is used to show progress inside of an existing layer of progress bars.
[int]
$ProgressIdentifier,
# If set, the server error will be turned into a result.
# This is useful for servers that provide complex error information inside of XML or JSON.
[Switch]
$UseErrorAsResult,
# If set, then a note property will be added to the result containing the response headers
[Switch]
$OutputResponseHeader,
# The amount of time before a web request times out.
[Timespan]
$Timeout,
# If set, will request the web site asynchronously, and return the results
[Switch]
$Async
)
begin {
#region Escape Special Characters
$replacements = @{
"<BR>" = "<BR />"
"<HR>" = "<HR />"
" " = " "
'¯'='¯'
'Ð'='Ð'
'¶'='¶'
'¥'='¥'
'º'='º'
'¹'='¹'
'ª'='ª'
'­'=''
'²'='²'
'Ç'='Ç'
'Î'='Î'
'¤'='¤'
'½'='½'
'§'='§'
'Â'='â'
'Û'='Û'
'±'='±'
'®'='®'
'´'='´'
'Õ'='Õ'
'¦'='¦'
'£'='£'
'Í'='Í'
'·'='·'
'Ô'='Ô'
'¼'='¼'
'¨'='¨'
'Ó'='Ó'
'°'='°'
'Ý'='Ý'
'À'='À'
'Ö'='Ö'
'"'='"'
'Ã'='Ã'
'Þ'='Þ'
'¾'='¾'
'¿'='¿'
'×'='×'
'Ø'='Ø'
'÷'='÷'
'¡'='¡'
'³'='³'
'Ï'='Ï'
'¢'='¢'
'©'='©'
'Ä'='Ä'
'Ò'='Ò'
'Å'='Å'
'È'='È'
'Ü'='Ü'
'Á'='Á'
'Ì'='Ì'
'Ñ'='Ñ'
'Ê'='Ê'
'¸'='¸'
'Ù'='Ù'
'ß'='ß'
'»'='»'
'ë'='ë'
'É'='É'
'µ'='µ'
'¬'='¬'
'Ú'='Ú'
'Æ'='Æ'
'€'= "€"
'—' = '—'
}
#endregion Escape Special Characters
$quotes = '"', "'"
function Convert-Json
{
<#
.Synopsis
Inline JSON converter
.Description
Converts JSON into PowerShell hashtables using regular expressions
#>
param(
# The JSON
[Parameter(ValueFromPipeline=$true)]
[string]$Json,
# If set, will use full language mode when parsing the data.
# If not set, the data will be parsed in "data-language" mode, which allows for the declaration of hashtables but prevents the execution of code
[switch]$FullLanguage)
begin {
function ConvertFrom-Hashtable
{
param($results)
$psObject = New-Object PSObject
foreach ($key in $results.Keys) {
$result = $null
if ($results[$key] -is [Hashtable]) {
$result = ConvertFrom-Hashtable $results[$key]
} elseif ($results[$key] -is [Array]) {
$result = foreach ($result in $results[$key]){
if ($result -is [Hashtable]) {
ConvertFrom-Hashtable $result
} else {
$result
}
}
} else {
$result = $results[$key]
}
if ($key) {
$psObject.psObject.Properties.Add(
(New-Object Management.Automation.PSNoteProperty $key, $result)
)
}
}
$psobject
}
}
process {
$json = [Regex]::Replace($Json,
"\\u([\dabcdefABCDEF]{4,4})", {
("0x" + $args[0].Groups[1].Value) -as [Uint32] -as [Char]
})
$json = $Json.Replace('$', '$ ')
$script =
$json -replace
'“|”', '`"' -replace
'"\s{0,}:', '"=' -replace
"\\{2,2}", "\" -replace
"\[", "$([Environment]::NewLine)@(" -replace
"\]", ")" -replace
',\[', ", $([Environment]::NewLine)@(" -replace
"\],",")," -replace
'\{"', "@{$([Environment]::NewLine)`"" -replace
"\[\]", "@()" -replace
"=(\w)*(\[)", '=@(' -replace
"=(\d{1,}),",'=$1;' -replace
"=(\d{1,}.\d{1,}),",'=$1;' -replace
"=-(\d{1,}.\d{1,}),",'=-$1;' -replace
"true", "`$true" -replace
"false", "`$false" -replace
"null", '$null' -replace
"\]}", ")}" -replace
"{", "@{" -replace
'\\"', '`"' -replace
"@@", "@" -replace
'(["})]),', "`$1$([Environment]::NewLine)" -replace
'(\$true),', "`$1$([Environment]::NewLine)" -replace
'(\$false),', "`$1$([Environment]::NewLine)" -replace
'(\$null),', "`$1$([Environment]::NewLine)" -replace
"(-{0,1})(\d{1,}),", "`$1`$2$([Environment]::NewLine)" -replace
"\\/","/" -replace
'\$true(\w{1,})', 'true$1' -replace
'\$false(\w{1,})', 'false$1' -replace
'\$null(\w{1,})', 'null$1'
$replacements = @(@{
Find = '}\s{1,}@{'
Replace = '},@{'
})
foreach ($r in $replacements) {
foreach ($f in $r.find) {
$regex =New-Object Regex $f, "Multiline, IgnoreCase"
$script = $regex.Replace($script , $r.Replace)
}
}
if ($script.Startswith("["))
{
$script = "@(" + $script.Substring(1).TrimEnd("]") + ")"
}
$results = $null
Write-Verbose $script
if ($FullLanguage) {
$results = Invoke-Expression "$script"
} else {
$results = Invoke-Expression "data { $script }"
}
if ($results) {
foreach ($result in $results) {ConvertFrom-Hashtable $result }
}
}
}
# Add system.web, in case it's not loaded
Add-Type -AssemblyName System.Web
if ($ProgressIdentifier) {
$script:CachedProgressId = $ProgressIdentifier
}
if (-not $script:CachedProgressId) {
$script:CachedProgressId = Get-Random
}
$progressId = $script:CachedProgressId
}
process {
if ($psCmdlet.ParameterSetName -eq 'WGet') {
if (-not $script:cachedContentTypes) {
$script:cachedContentTypes = @{}
$ctKey = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("MIME\Database\Content Type")
$ctKey.GetSubKeyNames() |
ForEach-Object {
$extension= $ctKey.OpenSubKey($_).GetValue("Extension")
if ($extension) {
$script:cachedContentTypes["${extension}"] = $_
}
}
}
$currentRoot = "$Root"
if ($currentRoot -like "http*//*" -and $currentRoot -notlike "http*//*/") {
$currentRoot+= '/'
}
$hostname = ([uri]$currentRoot).DnsSafeHost
$followMeDown = New-OBject Collections.Queue
$null = $followMeDown.Enqueue($currentRoot)
$pages = @{}
$pagedata = @{}
while ($followMeDown.Count -gt 0) {
$pageRoot = $followMeDown.Dequeue()
$pageHost = ([uri]$pageRoot).DnsSafeHost
if ($pageHost -ne $hostname) {
continue
}
$relativeRoot = $pageRoot.Substring(0, $pageRoot.LastIndexOf("/"))
$pageMimetype=
if ($pageRoot -like "http*//*/*.*") {
$extension = $pageRoot.Substring($pageRoot.LastIndexOf("."))
if ($script:cachedContentTypes[$extension]) {
$script:cachedContentTypes[$extension]
} else {
"unknown/unknown"
}
} elseif ($pageRoot -like "http*//*/") {
"text/html"
} else {
"unknown/unknown"
}
$pageHtml = ""
if ($pageMimetype -like "text/*") {
$pageHtml = Get-Web -Url $pageRoot -UseWebRequest
$pagedata[$pageRoot] = $pageHtml
} else {
$pagedata[$pageRoot] = Get-Web -Url $pageRoot -UseWebRequest -AsByte
}
if (-not $pageHtml) {
continue
}
$linksCssAndImagesAndScripts = Get-Web -Html $pageHtml -Tag a, link, img, script
# Enqueue relative links
$relativeLinks = $linksCssAndImagesAndScripts |
Where-Object {
$_.Xml.Name -eq 'a'
} |
Where-Object {
$x = $_.Xml
$startTag = $x.SelectSingleNode("/*")
$startTag.Href -and (
($startTag.Href -like "/*" -or $startTag.Href -notlike "*://*") -or
(([uri]$startTag.Href).DnsSafeHost -eq "$hostname")
) -and ($startTag.Href -notlike "javascript:*")
}
<#
$requiredScripts = $linksCssAndImagesAndScripts |
Where-Object {
$_.Xml.Name -eq 'Script' -and $_.Xml.src
}#>
$links = $linksCssAndImagesAndScripts |
Where-Object {
$_.Xml.Name -eq 'link'
}
$images = $linksCssAndImagesAndScripts |
Where-Object {
($_.StartTag -like "*img*" -or $_.StartTag -like "*script*") -and
$_.StartTag -match "src=['`"]{0,1}([\w\:/\.-]{1,})"
} |ForEach-Object {
$Matches.'1'
}
$potentialHrefs = @()
$potentialHrefs +=
foreach ($img in $images) {
$img
}
foreach ($r in $relativeLinks) {
$potentialHrefs += $r.Xml.Href
}
foreach ($href in $potentialHrefs) {
if (-not $href) { continue }
if ($href -like "$relativeRoot*") {
if (-not $followMeDown.Contains($href) -and -not $pagedata.Contains($href)) {
$null = $followMeDown.Enqueue($href)
}
} if (-not ([uri]$href).DnsSafeHost) {
if (-not $followMeDown.Contains($href) -and -not $pagedata.Contains($href)) {
if ($href -like "/*") {
$null = $followMeDown.Enqueue(([uri]$currentRoot).Scheme+ "://" + $hostname + $href)
} else {
$null = $followMeDown.Enqueue($relativeRoot + '/' + $href)
}
}
} else {
$null = $null
}
}
}
if ($GetStory) {
$story = @{}
foreach ($pd in $pagedata.GetEnumerator()) {
if ($pd.value -is [string]) {
$partsOfStory = @(
Get-Web -Tag 'div', 'p' -Html $pd.Value |
ForEach-Object {
$firsttagEnd = $_.StartTag.IndexOfAny(' >')
$tagName = $_.StartTag.Substring(1, $firsttagEnd - 1)
$newTag= $_.Tag.Substring($_.StartTag.Length)
$changeindex = $newTag.IndexOf("*</$tagName>", [stringcomparison]::OrdinalIgnoreCase)
if ($changeindex -ne -1) {
$newTag = $newTag.Substring(0, $changeindex)
}
$strippedTags = [Regex]::Replace($newTag, "<[^>]*>", [Environment]::NewLine);
$strippedTags
})
if ($partsOfStory -ne '') {
$segments = ([uri]$pd.Key).Segments
if ($segments.Count -le 1) {
$newPath = '/'
} else {
$newPath = (([uri]$pd.Key).Segments -join '' -replace '/', '_').Trim('_')
}
$story[$newPath] = $partsOfStory -ne '' -join ([Environment]::NewLine * 4)
}
}
}
$pagedata += $story
}
$pagedata
} elseif ($psCmdlet.ParameterSetName -eq 'URL') {
#Region Download URL
$fullUrl = "$url"
if ($Data -and -not $RequestBody) {
$RequestBody = $data -join '&'
$UseWebRequest = $true
if (-not $psBoundParameters.Method) {
$Method = 'POST'
}
}
$xmlHttp = New-Object -ComObject Microsoft.xmlhttp
if ($useWebRequest) {
if ($Parameter -and ('PUT', 'POST' -notcontains $method)) {
$fullUrl += "?"
foreach ($param in $parameter.GetEnumerator()) {
$fullUrl += "$($param.key)=$([Web.HttpUtility]::UrlEncode($param.Value.ToString()))&"
}
}
$req = [Net.WebRequest]::Create("$fullUrl")
$req.UserAgent = $UserAgent
$req.Method = $Method;
if ($psBoundParameters.ContentType) {
$req.ContentType = $ContentType
}
if ($psBoundParameters.WebCredential) {
$req.Credentials = $WebCredential.GetNetworkCredential()
} elseif ($psBoundParameters.UseDefaultCredential) {
$req.Credentials = [net.credentialcache]::DefaultNetworkCredentials
}
if ($header) {
foreach ($kv in $header.GetEnumerator()) {
if ($kv.Key -eq 'Accept') {
$req.Accept = $kv.Value
} elseif ($kv.Key -eq 'content-type') {
$req.ContentType = $kv.Value
} else {
$null = $req.Headers.add("$($kv.Key)", "$($kv.Value)")
}
}
}
if ($timeout) {
$req.Timeout = $timeout.TotalMilliseconds
}
$RequestTime = [DateTime]::Now
if (-not $HideProgress) {
Write-Progress "Sending Web Request" $url -Id $progressId
}
$requestStream = try {
if ($Parameter -and ('PUT', 'POST' -contains $method)) {
if (-not $RequestBody) {
$RequestBody = ""
}
$RequestBody +=
(@(foreach ($param in $parameter.GetEnumerator()) {
"$($param.key)=$([Uri]::EscapeDataString($param.Value.ToString()))"
}) -join '&')
} else {
$paramStr = ""
}
if ($ContentType) {
$req.ContentType = $ContentType
}
if ($requestBody) {
if ($RequestBody -is [string]) {
if (-not $ContentType) {
$req.ContentType = 'application/x-www-form-urlencoded'
}
$bytes = [Text.Encoding]::UTF8.GetBytes($RequestBody)
$postDataBytes = $bytes -as [Byte[]]
$req.ContentLength = $postDataBytes.Length
$requestStream = $req.GetRequestStream()
$requestStream.Write($postDataBytes, 0, $postDataBytes.Count)
$requestStream.Close()
} elseif ($RequestBody -as [byte[]]) {
if (-not $ContentType) {
$req.ContentType = 'application/x-www-form-urlencoded'
}
$postDataBytes = $RequestBody -as [Byte[]]
$req.ContentLength = $postDataBytes.Length
$requestStream = $req.GetRequestStream()
if ($req.ContentLength -gt 256kb) {
if (-not $HideProgress) {
Write-Progress "Uploading" $url -Id $progressId
}
#$requestStream.Write($postDataBytes, 0, $postDataBytes.Count)
$tLen = 0
$chunkTotal = [Math]::Ceiling($postDataBytes.Count / 256kb)
for ($chunkCount = 0; $chunkCount -lt $chunkTotal; $chunkCount++) {
if ($chunkCount -ne ($chunkTotal -1 )) {
$arr = $postDataBytes[($chunkCount * 256kb)..(([uint32]($chunkCount + 1) * 256kb) - 1)]
$tLen+=$arr.Length
} else {
$arr = $postDataBytes[($chunkCount * 256kb)..($postDataBytes.Length - 1)]
$tLen+=$arr.Length
}
$requestStream.Write($arr, 0 , $arr.Length)
if (-not $HideProgress) {
$perc = $chunkCount * 100 / $chunkTotal
Write-Progress "Uploading" $url -Id $progressId -PercentComplete $perc
}
}
if (-not $HideProgress) {
Write-Progress "Uploading" $url -Id $progressId -Completed
}
} else {
$requestStream.Write($postDataBytes, 0, $postDataBytes.Count)
}
$requestStream.Close()
}
} elseif ($paramStr) {
$postData = "$($paramStr -join '&')"
$postDataBytes = [Text.Encoding]::UTF8.GetBytes($postData)
$req.ContentLength = $postDataBytes.Length
$requestStream = $req.GetRequestStream()
$requestStream.Write($postDataBytes, 0, $postDataBytes.Count)
$requestStream.Close()
} elseif ($method -ne 'GET' -and $method -ne 'HEAD') {
$req.ContentLength = 0
}
} catch {
if (-not ($_.Exception.HResult -eq -2146233087)) {
$_ | Write-Error
return
}
}
Write-Verbose "Getting $fullUrl"
$responseIsError = $false
if ($Async) {
return New-Object PSObject -Property @{
WebRequest = $req
AsyncOperation = $req.BeginGetResponse({}, $null)
}
}
$webresponse =
try {
$req.GetResponse()
} catch {
$ex = $_
if ($ex.Exception.InnerException.Response) {
$streamIn = New-Object IO.StreamReader $ex.Exception.InnerException.Response.GetResponseStream()
$strResponse = $streamIn.ReadToEnd();
$streamIn.Close();
if (-not $UseErrorAsResult) {
Write-Error $strResponse
return
} else {
$html = $strResponse
}
} else {
$ex | Write-Error
return
}
#
}
if ($webResponse) {
$rs = $webresponse.GetResponseStream()
$responseHeaders = $webresponse.Headers
$responseHeaders = if ($responseHeaders -and $responseHeaders.GetEnumerator()) {
$reHead = @{}
foreach ($r in $responseHeaders.GetEnumerator()) {
$reHead[$r] = $responseHeaders[$r]
}
$reHead
} else {
$null
}
$unexpectedResponseType = $false
if ($psBoundParameters.ContentType -and
$webresponse.ContentType -and
$webResponse.ContentType -ne $ContentType) {
if ($webresponse.ContentType -notlike "text/*" -and $webresponse.ContentType -notlike "*xml*") {
$pageRoot = "$($WebResponse.ResponseUri)"
$relativeRoot = $pageRoot.Substring($pageRoot.LastIndexOf("/") + 1)
$unexpectedResponseType = $true
$AsByte = $true
}
}
if ($AsByte) {
$byteBuffer = new-object byte[] $webresponse.ContentLength;
[int]$ToRead = $webresponse.ContentLength
[int]$TotalRead = 0
[Int]$bytesRead = 0
while ($toRead -gt 0 -and ($toRead -ge $TotalRead)) {
try {
$amountToRead =
if (($ToRead - $TotalRead) -gt .25kb) {
.25kb
} else {
$ToRead - $TotalRead
}
$bytesRead = $rs.Read($byteBuffer, $TotalRead, $amountToRead )
} catch {
$global:LastStreamReadError = $_
}
if ($bytesRead -eq 0) {
break
}
$TotalRead += $bytesRead
if (($byteBuffer.Length -gt 256kb) -and -not $hideProgress) {
$perc = ($totalRead / $byteBuffer.Length) * 100
Write-Progress "Downloading" $url -Id $progressId -PercentComplete $perc
}
}
if (-not $HideProgress) {
$perc = $totalRead / $byteBuffer.Length
Write-Progress "Download Completed" $url -Id $progressId -Complete
}
#$null = $rs.CopyTo($ms)
$outBytes = $byteBuffer
#New-Object byte[] $ms.Length
#$null = $ms.Write($outBytes, 0, $ms.Length);
} else {
$streamIn = New-Object IO.StreamReader($rs);
$strResponse = $streamIn.ReadToEnd();
$html = $strResponse
$streamIn.Close();
}
$rs.close()
$rs.Dispose()
if ($AsByte) {
if ($unexpectedResponseType) {
return @{$relativeRoot= $outBytes}
} else {
return $outBytes
}
}
if ($unexpectedResponseType -and $Html) {
return @{$relativeRoot= $Html}
}
}
}
# $req.CookieContainer
if (! $html -and -not $UseWebRequest) {
if ($WebCredential) {
$xmlHttp.open("$Method",
$fullUrl,
$false,
$WebCredential.GetNetworkCredential().Username,
$WebCredential.GetNetworkCredential().Password)
} else {
$xmlHttp.open("$Method", $fullUrl, $false)
}
$xmlHttp.setRequestHeader("UserAgent", $userAgent)
if ($header) {
foreach ($kv in $header.GetEnumerator()) {
$xmlHttp.setRequestHeader("$($kv.Key)", $kv.Value)
}
}
if (-not $HideProgress) {
Write-Progress "Sending Web Request" $url -Id $progressId
}
if ($parameter -and ('PUT', 'POST' -contains $method)) {
$paramStr = foreach ($param in $parameter.GetEnumerator()) {
"$($param.key)=$([Web.HttpUtility]::UrlEncode($param.Value.ToString()))"
}
if ($header -and $Header.ContainsKey('ContentType')) {
$ContentType = $Header['ContentType']
} elseif ($header -and$Header.ContainsKey('Content-Type')) {
$ContentType = $Header['Content-Type']
}
if ($ContentType) {
$xmlHttp.SetRequestHeader("Content-Type","$ContentType")
} else {
$xmlHttp.SetRequestHeader("Content-Type","application/x-www-form-urlencoded")
}
if ($requestBody) {
$xmlHttp.Send("$requestBody")
} else {
$xmlHttp.Send("$($paramStr -join '&')")
}
} else {
$xmlHttp.Send($RequestBody)
}
$requestTime = [Datetime]::Now
while ($xmlHttp.ReadyState -ne 4) {
if (-not $hideProgress) {
Write-Progress "Waiting for response" $url -id $progressId
}
Start-Sleep -Milliseconds 10
}
}
$ResponseTime = [Datetime]::Now - $RequestTime
if (-not $hideProgress) {
Write-Progress "Response received" $url -id $progressId
}
if ($xmlHttp.Status -like "2*") {
Write-Verbose "Server Responded with Success $($xmlHttp.Status)"
} elseif ($xmlHttp.Status -like "1*") {
Write-Debug "Server Responded with Information $($xmlHttp.Status)"
} elseif ($xmlHttp.Status -like "3*") {
Write-Warning "Server wishes to redirect: $($xmlHttp.Status)"
} elseif ($xmlHttp.Status -like "4*") {
$errorWithinPage =
Get-Web -Html $xmlHttp.responseText -Tag span |
Where-Object { $_.Tag -like '*ui-state-error*' } |
ForEach-Object {
$short = $_.Tag.Substring($_.Tag.IndexOf(">") + 1);
$short.Substring(0, $short.LastIndexOf("</"))
}
$errorText = if ($errorWithinPage) {
$errorWithinPage
} else {
$xmlHttp.MessageText
}
Write-Error "Server Responded with Error: $($xmlHttp.Status) - $($errorText)"
return
}
#endregion Download URL
if ($AsByte) {
return $xmlHttp.ResponseBody
} elseif (-not $UseWebRequest) {
$html = $xmlHttp.ResponseText
}
} elseif ($psCmdlet.ParameterSetName -eq 'FileName') {
if ($AsByte) {
[IO.File]::ReadAllBytes($ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($FileName))
return
}
$html = [IO.File]::ReadAllText($ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($FileName))
}
if (-not $html) { return }