Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Location header when URL redirected using Invoke-WebRequest in powershell

  • 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 ?

like image 688
Etay Gudai 972-522-3322-47 Avatar asked Oct 31 '25 15:10

Etay Gudai 972-522-3322-47


2 Answers

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
like image 191
Etay Gudai 972-522-3322-47 Avatar answered Nov 02 '25 11:11

Etay Gudai 972-522-3322-47


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.

like image 21
Jat Avatar answered Nov 02 '25 13:11

Jat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!