Powershell: Invoke-WebRequest aborts with httpcode 301/308 permanent redirect

Hi,

the powershell command-let Invoke-WebRequest does not follow an http redirect.

The solution is to call Invoke-WebRequest recursivly with the redirect URL from the location header field when http code 301 or 308 is returned.

$sURL = "https://visualstudio.com/"
$sRedirectTo=$null
do {
    $oWebResponse = $null
    try
    {
        $oWebResponse = Invoke-WebRequest $sURL 
    }
    catch 
    {
        $oWebResponse=$_.Exception.Response
        write-host ("Exception: {0}" -f $_.Exception.Message)
    }
	if($oWebResponse.StatusCode -ne 200)
	{
		$aRedirectTo=$oWebResponse.Headers.GetValues("location")
		if($aRedirectTo.Count -ge 1)
		{
			$sRedirectTo=$aRedirectTo[0]
		}
		else
		{
			write-host ("No location URL in header")
			break
		}
		if (-not [string]::IsNullOrEmpty($sRedirectTo))
		{
			write-host ("Redirect to {0}" -f ($sRedirectTo))
			$sURL = $sRedirectTo
		}
		else
		{
			write-host ("location URL Null")
			break
		}
	}
    else
    {
        Write-Output ("OK Location = {1} HttpCode = {0}" -f $oWebResponse.StatusCode,$sRedirectTo )
        break
    }
	
} 
while ($true)

Michael

Advertisment to support michlstechblog.info

Visual Studio: Set proxy server for update

Hi,

the update process of Visual Studio uses the .NET class Webclient which takes not care about the proxy set by Internet Explorer or Edge.
Continue reading Visual Studio: Set proxy server for update

vSphere VCSA: Cannot add a (http) https proxy


Hi,

with the VCSA Gui it is not possible to to enter a http proxy for https target URLs. An error: HTTPS Cannot connect to proxy server occurs.

The most linux tools accept http URLs in the HTTPS_PROXY variable and this also works with the VCSA.
Continue reading vSphere VCSA: Cannot add a (http) https proxy

ESP32: Interesting projects

Hi,

this post is a link collector for some intressting ESP32 projects
Continue reading ESP32: Interesting projects

Windows: Capture (Main) Screen and Audio with free software

Hi,

there are a lot of tools which does this task.
Continue reading Windows: Capture (Main) Screen and Audio with free software

My Knowledgebase for things about Linux, Windows, VMware, Electronic and so on…