Invoke WebRequests via Powershell

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

Invoke-WebRequest "https://arminreiter.com"

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 <<<< “http://www.codehollow.com”
+ CategoryInfo : ObjectNotFound: (invoke-webrequest:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

Because you need the Powershell Version 3.0 or higher as described here: https://technet.microsoft.com/en-us/library/hh849901.aspx

There are two ways how to solve this.


You can install a newer version of Powershell (Version 5.1: https://www.microsoft.com/en-us/download/details.aspx?id=54616). 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("https://arminreiter.com")
$response = $webrequest.GetResponse()
$response

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

(New-Object System.Net.WebClient).DownloadString("https://arminreiter.com")

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

function InvokeWebRequest ([string]$url)
{
    try
    {
        $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 }
    finally
    {
        if($sr -ne $null) { $sr.Close(); }
        if($response -ne $null) { $response.Close(); }
    }
}
 
$content = InvokeWebRequest("https://arminreiter.com")
write-host $content

Categories:

Leave a Reply

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

About
about armin

Armin Reiter
Blockchain/Web3, IT-Security & Azure
Vienna, Austria

Reiter ITS Logo

Cryptix Logo

Legal information