Short answer
For the PowerShell newbs (where .NET methods may look a bit scary), try the following (case insensitive) code:
Invoke-WebRequest -Uri "http://icanhazip.com" | Select-Object -ExpandProperty "Content"
The above is the simplest (in my humble opinion) way to obtain one's external/public/WAN IP address via PowerShell (also known as "PoSh").
Long answer
This technique relies on a helpful website (there are several, in fact) that returns only the public IP address of the connection that you're connecting from.
We use the handy Invoke-WebRequest
cmdlet, which gives us a bunch of info about the website. In this case though, we actually want the raw HTML of the webpage (which happens to be just your public IP address). The Select-Object
cmdlet will allow us to do just that, and discard the rest of the information returned.
Having said that, as the other answerers have highlighted, this approach actually returns, not one, but two lines:
One line containing the IP address, and one line containing white space.
If this causes an issue (for simple requirements, such as printing the IP address to the screen, this is not likely to cause an issue), you will need to delve into the aforementioned .NET method world, ever so slightly.
Again, case insensitive:
( Invoke-WebRequest -Uri "http://icanhazip.com" | Select-Object -ExpandProperty "Content" ).Trim( "" )
The Trim() method will "trim" anything matching the characters specified in between the double-quote marks (which are actually optional in this case) from the beginning or the end of the returned data (or string, technically speaking). Being that in this example there is actually nothing between the double-quote marks, PowerShell will interpret this as "white space" and trim anything from the start or end that's considered white space.
The initial pair of brackets is required when using .NET methods with PowerShell cmdlets, and the second pair of brackets is part of the method itself.
This combination of PowerShell cmdlets and .NET method leaves you with just the IP address you seek.
Can you explain why you need this info? Trying to find a server's external IP address is really tricky. – splattered bits – 2014-08-28T03:33:51.567
2I want to run this script which will check if my external IP changed. if it does then it will send me notification on my iPhone. – user206168 – 2014-08-28T11:31:19.283