2
  • Calling a URL which permanently moved or redirected, does not return Location http header or the correct location.
  • it seems that URL redirection is being performed during URL call ( http status code : 302, 301 etc ).

How do I overcome this ?

2 Answers2

3

Found this answer by Alec Collier

Add the following to your URL call : -MaximumRedirection 0 -ErrorAction Ignore

Example :

$url="https://jigsaw.w3.org/HTTP/300/301.html"

$resp = Invoke-WebRequest $url -MaximumRedirection 0 -ErrorAction Ignore

$resp.Headers.Location
2

Just use -MaximumRedirection 0 -SkipHttpErrorCheck (and add -ErrorAction:SilentlyContinue if you want to suppress the warning):

(Invoke-WebRequest -Uri "https://www.google.com/ncr" -MaximumRedirection 0 -SkipHttpErrorCheck -ErrorAction:SilentlyContinue).Headers.Location

https://www.google.com/

Note that the data type of return value is an array and it only has a single item.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Jat
  • 21
  • 3