Invoke WebRequests via Powershell

It’s quite simple to invoke WebRequests via Powershell if you have Powershell Version 3.0 or higher:

Invoke-WebRequest ""

If you have Powershell Version 2.0 or 1.0 , you’ll receive the following error:

invoke-webrequest : The term ‘invoke-webrequest’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:18
+ invoke-webrequest <<<< “”
+ CategoryInfo : ObjectNotFound: (invoke-webrequest:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

Because you need the Powershell Version 3.0 or higher as described here:

There are two ways how to solve this.
You can install a newer version of Powershell (Version 5.1: If this is not possible (on the customer server), then you can use the following Powershell script to invoke a web request:

$webrequest = [System.Net.WebRequest]::Create("")
$response = $webrequest.GetResponse()

If you just want to download the page, then it’s a bit simpler:

(New-Object System.Net.WebClient).DownloadString("")

if you want to use webrequest and read the output – then use a streamreader as in the following script:

function InvokeWebRequest ([string]$url)
        $webrequest = [System.Net.WebRequest]::Create($url)
        $response = $webrequest.GetResponse()
        $stream = $response.GetResponseStream()
        $sr = new-object System.IO.StreamReader($stream)
        $content = $sr.ReadToEnd();
        return $content
    catch { Write-Error $_.Exception.Message }
        if($sr -ne $null) { $sr.Close(); }
        if($response -ne $null) { $response.Close(); }

$content = InvokeWebRequest("")
write-host $content


Leave a Reply

Your email address will not be published. Required fields are marked *