Skip to content

Instantly share code, notes, and snippets.

@scriptingstudio
Last active May 3, 2025 12:23
Show Gist options
  • Select an option

  • Save scriptingstudio/ef27443e748da7f25f33b27fbff9d104 to your computer and use it in GitHub Desktop.

Select an option

Save scriptingstudio/ef27443e748da7f25f33b27fbff9d104 to your computer and use it in GitHub Desktop.
Simple Webclient wrapper
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