Getting your public IP address using Powershell

I'm currently working on an issue in Powershell, where I need to get the public IP address of my home connection. There should be a simple command for that, surely!

If we wanted to get local IP address on the network, we could simply run Get-NetIPAddress, and select only the IPAddress field like so:

Get-NetIPAddress | Select-Object IPAddress
IPAddress                   
---------                   
::1                         
169.254.96.187              
169.254.193.151             
169.254.138.230             
192.168.1.99                
169.254.121.9               
127.0.0.1   

Whereas getting the public (i.e. external) IP address, requires us to use a third-party service.

Fortunately, there are lots of these:

We can then invoke a web request to one of these sites, and pull the IP address from the response:

Invoke-WebRequest -uri "https://api.ipify.org/"
StatusCode        : 200
StatusDescription : OK
Content           : 12.123.12.123
RawContent        : HTTP/1.1 200 OK
                    Connection: keep-alive
                    Vary: Origin
                    Content-Length: 14
                    Content-Type: text/plain
                    Date: Fri, 12 Mar 2021 13:13:09 GMT
                    Server: Cowboy
                    Via: 1.1 vegur
                    
                    12.123.12.123
Forms             : {}
Headers           : {[Connection, keep-alive], [Vary, Origin], [Content-Length, 14], [Content-Type, text/plain]...}
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : mshtml.HTMLDocumentClass
RawContentLength  : 14

And, to store it as a variable to use later:

$myIP = (Invoke-WebRequest -uri "https://api.ipify.org/").Content
PS C:\Users\Sean> $myIP
12.123.12.123