Skip to content

Instantly share code, notes, and snippets.

@MVKozlov
Created May 30, 2016 10:34
Show Gist options
  • Save MVKozlov/c6e34d70c463b844cebb1063ba66d308 to your computer and use it in GitHub Desktop.
Save MVKozlov/c6e34d70c463b844cebb1063ba66d308 to your computer and use it in GitHub Desktop.
param(
$Uri,
$Body,
$Certificate,
$CertificateThumbprint,
$ContentType,
$Credential,
$DisableKeepAlive,
$Headers,
$InFile,
$MaximumRedirection,
$Method,
$OutFile,
$PassThru,
$Proxy,
$ProxyCredential,
$ProxyUseDefaultCredentials,
$SessionVariable,
$TimeoutSec,
$TransferEncoding,
$UseBasicParsing,
$UseDefaultCredentials,
$UserAgent,
$WebSession
)
#Invoke-WebRequest [-Uri] <Uri> [-Body <Object>] [-Certificate <X509Certificate>] [-CertificateThumbprint <String>]
#[-ContentType <String>] [-Credential <PSCredential>] [-DisableKeepAlive] [-Headers <IDictionary>] [-InFile <String>
#] [-MaximumRedirection <Int32>] [-Method <WebRequestMethod>] [-OutFile <String>] [-PassThru] [-Proxy <Uri>] [-Proxy
#Credential <PSCredential>] [-ProxyUseDefaultCredentials] [-SessionVariable <String>] [-TimeoutSec <Int32>] [-Transf
#erEncoding <String>] [-UseBasicParsing] [-UseDefaultCredentials] [-UserAgent <String>] [-WebSession <WebRequestSess
#ion>] [<CommonParameters>]
$savedMaximumRedirection = $PSBoundParameters['MaximumRedirection']
$redirections = 0
$PSBoundParameters['MaximumRedirection']=0
$session = $PSBoundParameters['WebSession']
do {
$uri = [uri]$PSBoundParameters['Uri']
$site = $uri.Scheme+'://'+$uri.Authority
$r = Invoke-WebRequest @PSBoundParameters -ErrorAction SilentlyContinue # to mask maxredirection 'error'
if (-not $session) { write-host 'no-session'; break; }
if ($r.StatusCode -eq 302) {
$redirections++
if ($redirections -gt $savedMaximumRedirection) {
break;
}
if ($r.Headers['Set-Cookie']) {
$cookies = $r.Headers['Set-Cookie']
$paths = $cookies -split '\s*;\s*' | Foreach-Object { if ($_ -match 'path=(.*)') { $matches[1] } } | Sort-Object -Unique
foreach ($path in $paths) {
$session.Cookies.SetCookies($site + $path, $cookies)
}
}
if ($r.Headers['Location'] -match '^/') {
$PSBoundParameters['Uri'] = $site + $r.Headers['Location']
}
else {
$PSBoundParameters['Uri'] = $r.Headers['Location']
}
$PSBoundParameters['Method'] = 'Get'
}
} until ($r.StatusCode -ne 302)
$r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment