However, this does require setting up the ARM cmdlets to the machine first.

Another way to get the public IP is by going to an external site, but there are no guarantees the external site is available.

There’s an even easier way that is generally available (in preview for Azure Government, Azure China, Azure Germany as of now). This is through the Azure Instance Metadata service for Azure VMs.

The Azure Instance Metadata service is a REST endpoint (well-known non-routable IP address) useful for all IaaS VMs created through Azure Resource Manager and is only accessible to the VM for which you want to get configuration information (e.g., public IP). The information available includes SKU, network configuration, and maintenance events. The response returned from the call is in the standard JSON format.

Here’s what it looks like to get the public IP from within a Windows VM in Azure and set it to a variable through PowerShell:

Note that you can also get the private IP address by changing to “.privateIpAddress.” How I usually debug the values of the JSON returned is by adding a breakpoint into the line of code at the Invoke-RestMethod line and then type in PowerShell, $jsonBody to view the full response back and then start manually parsing to find the appropriate value.