2

PowerShell 5.1 on Win10 Pro, from home, on Comcast.
I want to get my external IP.
My first request gets 403 Forbidden.
But then i just repeat the request (using the keyboard UpArrow), and it works - i get my IP as expected. But if i pause for awhile (several minutes) i'll get the 403 again, and then it works

PS>  (Invoke-WebRequest -uri "icanhazip.com").Content

Invoke-WebRequest : The remote server returned an error: (403) Forbidden.
At line:1 char:2
+ (Invoke-WebRequest -uri "icanhazip.com").Content
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

PS>  (Invoke-WebRequest -uri "icanhazip.com").Content
xx.xx.xx.xx  (obscured, but IP as expected)

I can put the WebRequest line into a file and invoke it, and it fails first time, works second time.

I can put the WebRequest line twice into a file, and invoke it - it fails once then then works, just like at the command line. I have not had this problem with PS 7, which makes it seem like a PS5 problem. But i also don't get the issue when i use "https://wtfismyip.com/text", which makes it seem like a icanhazip.com problem.

RMurp
  • 33
  • 1
  • 1
  • 4
  • 1
    Interestingly, I get the same outcome. With every new PS5 session I get forbidden the first time and then it works each time after that in the same session. Open a new PS5 session, same thing - forbidden and then works. No forbidden on PS7. Works first and every time. – Daniel Mar 18 '21 at 04:16
  • Could be some issue with the website where they're probably maintaining a session for every user, but after a while - along with ending the session, the user access temporarily goes away as well. Doesn't seem to be a PowerShell issue. – Yash Gupta Mar 18 '21 at 06:06
  • Yash, it doesn't seem likely that the website is answering the first request with a 403 and allowing subsequent requests. This doesn't happen in a browser (unless the browser is discarding the 403 and trying again?). Also doesn't explain the diff between PS 5.1 and 7. – RMurp Mar 18 '21 at 13:54

1 Answers1

1

The default method of Invoke-WebRequest is 'Get'. Specify the method as 'Post' and the error is not returned.

$response = (Invoke-WebRequest -uri "icanhazip.com" -method Post).Content
Darrell
  • 154
  • 4
  • Yes, this works, thanks. At least, i can get the job done without running the same code twice and discarding an answer. it feels a bit like a workaround. I don't have an understanding of the problem. – RMurp Mar 18 '21 at 13:47