PowerShell Quick Tip 03 – What’s my external IP address? (Windows command-line)

Posted: 22/12/2012 in PowerShell
Tags: ,

At work this week I was working with one of our Linux engineers and he used the command “cURL ifconfig.me” which promptly provided him with the external IP of the system. I thought to myself, “I wonder if this is possible from PowerShell” and sure enough it is.

Using the Invoke-WebRequest cmdlet we can send http(s) requests to a web service. Note that this is a PowerShell 3.0 only cmdlet.

Let’s give it a try:

Invoke-WebRequest ifconfig.me

Get-ExternalIP-01

Not quite what we’re looking for. On inspection of the website http://ifconfig.me/ we can see that there are many command line options, lets try just the /IP option

Invoke-WebRequest ifconfig.me/ip

Get-ExternalIP-02

Much better and we can clearly see that the IP address is returned in Content which it fine for a quick check at the command line but not so great if your using it for scripting. To collect just the external IP we could wrap the command in parentheses, for example:

(Invoke-WebRequest ifconfig.me/ip).Content

Nice.

I thought that this would make a handy addition to my PowerShell Profile so I created a quick function


function Get-ExternalIP {
(Invoke-WebRequest ifconfig.me/ip).Content
}

Get-ExternalIP-03

Perfect!

An alternative to ifconfig.me is available at http://www.whatismyip.com/ip-faq/automation-rules/, for example

(Invoke-WebRequest http://automation.whatismyip.com/n09230945.asp).Content

Thanks for reading

Regards,

jfrmilner

Comments
  1. […] I learned a very nice PowerShell cmdlet thanks to Mr. John Miller post. This cmdlet helps me find my external IP. usually I used to go to the search engine and type whats […]

  2. […] API provides an example on how to use the service with cURL so as before I will be converting this simple format to use the PowerShell Invoke-WebRequest cmdlet and wrap […]

  3. Hi

    If you are interested in other code samples that retreives your ip, you can try out http://www.softraven com. It provides samples for c#, vb script, vb.net, java and off course powershell. And its not only the wan ip, but a whole bunch of other information that you can retrive over the wan. Its all there.

  4. spook says:

    (Invoke-WebRequest ifconfig.me/ip).Content.Trim()

  5. […] the resource group name, server name, rule name, and an IP address range. For this, we will use a trick I picked up from John Milner(@JFRMilner) to get our external IP and create a firewall rule for […]

Leave a reply to jfrmilner Cancel reply