Last active
May 3, 2025 12:23
-
-
Save scriptingstudio/ef27443e748da7f25f33b27fbff9d104 to your computer and use it in GitHub Desktop.
Simple Webclient wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function Get-HtmlContent { | |
| [CmdletBinding()] | |
| [alias('ghc')] | |
| param ( | |
| [Parameter(Mandatory,ValueFromPipeLine)] | |
| [Uri[]]$Uri, | |
| [alias('ua')][string]$UserAgent, | |
| [System.Text.Encoding]$Encoding, | |
| [alias('wait')][int] $TimeOutMs = -1 | |
| ) | |
| begin { | |
| if ($UserAgent -eq '%ie') {$UserAgent = '%InternetExplorer'} | |
| if ($UserAgent -match '^%(chrome|FireFox|Opera|Safari|InternetExplorer)') {$UserAgent = [Microsoft.PowerShell.Commands.PSUserAgent]::($matches[1])} | |
| $webclient = [System.Net.Webclient]::New() | |
| if ($Encoding) {$webclient.Encoding = $Encoding} | |
| $webclient.Headers['UserAgent'] = if ($UserAgent) {$UserAgent} else {'Mozilla/5.0 (Windows NT 10.0; Win64; x64; en-US) AppleWebKit/534.6 (KHTML, like Gecko) Chrome/7.0.500.0 Safari/534.6'} | |
| if ($TimeOutMs -lt 1) {$TimeOutMs = -1} | |
| } | |
| process { | |
| #try { | |
| $Uri | Where-Object {$_} | ForEach-Object { | |
| $path = if ($_ -notmatch '^.+://') {"http://$_"} else {$_} | |
| $webclient.DownloadStringTaskAsync($path) | ForEach-Object { | |
| if ($_.AsyncWaitHandle.WaitOne($timeoutMs)) {$_.GetAwaiter().GetResult()} | |
| } | |
| } | |
| #} catch {} | |
| } | |
| end {$webclient.Dispose()} | |
| } # END Get-HtmlContent |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment