Powershell v1 and v2 friendly version of Invoke-WebRequest

If you need to use the Invoke-Webrequest on machines that are still running an older Powershell version, this function will help you out.

It sets a script-wide variable called ‘cookiejar’, which will persist any cookies during subsequent calls to this function. You can add customHeaders as a hashtable if you need to. By default the function will also attempt to respond to 401 challenges with the current user credentials.


function JosL-WebRequest{
    Param(
        $uri,
        $method="GET",
        $body,
        $trySSO=1,
        $customHeaders
    )
    if($script:cookiejar -eq $Null){
        $script:cookiejar = New-Object System.Net.CookieContainer     
    }
    $maxAttempts = 3
    $attempts=0
    while($true){
        $attempts++
        try{
            $retVal = @{}
            $request = [System.Net.WebRequest]::Create($uri)
            $request.TimeOut = 5000
            $request.Method = $method
            if($trySSO -eq 1){
                $request.UseDefaultCredentials = $True
            }
            if($customHeaders){
                $customHeaders.Keys | % { 
                    $request.Headers[$_] = $customHeaders.Item($_)
                }
            }
            $request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E)"
            $request.ContentType = "application/x-www-form-urlencoded"
            $request.CookieContainer = $script:cookiejar
            if($method -eq "POST"){
                $body = [byte[]][char[]]$body
                $upStream = $request.GetRequestStream()
                $upStream.Write($body, 0, $body.Length)
                $upStream.Flush()
                $upStream.Close()
            }
            $response = $request.GetResponse()
            $retVal.StatusCode = $response.StatusCode
            $retVal.StatusDescription = $response.StatusDescription
            $retVal.Headers = $response.Headers
            $stream = $response.GetResponseStream()
            $streamReader = [System.IO.StreamReader]($stream)
            $retVal.Content = $streamReader.ReadToEnd()
            $streamReader.Close()
            $response.Close()
            return $retVal
        }catch{
            if($attempts -ge $maxAttempts){Throw}else{sleep -s 2}
        }
    }
}
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
nahouto
nahouto
6 years ago

great !
just one remark : I think you should name the first parameter Uri instead of Url, to be same as Invoke-Webrequest syntax

Peter
Peter
6 years ago

How would you implement support for the -OutFile option?

Kevin Schweiger
3 years ago

Thank you very much!

Mashkur
Mashkur
5 years ago

How can we simulate -InFile option here?

Jorge Andres
Jorge Andres
6 years ago

Great Men, congratulations