How to Get the Azure VM’s Public IP Address Using PowerShell

Table of Contents

Get the Azure VM’s Public IP Address

Sometimes, you may need to obtain the public IP address of an Azure VM, such as when you wish to connect to the VM via remote desktop automatically after its creation with PowerShell.

Unfortunately, Get-AzVM doesn’t provide the Public IP address of VM, but we can scrape its Network Interface Name and make a wildcard search of it through all assigned Public IPs which NIC name are matched. It’s not fast but will provide with correct results.

$vm         = Get-AzVM -Name 'vm-63424851'
$vmNicName  = $vm.NetworkProfile.NetworkInterfaces.Id.Split("/")[8]
$ipAddress  = Get-AzPublicIpAddress | Where-Object {$_.IpConfiguration.Id -like "*$vmNicName*"}
$rdpip      = $ipAddress.IpAddress
$rdpip

cmdkey /generic:$rdpip /user:"bonguides" /pass:"Pass@ord123"
mstsc /v:$rdpip /w:1366 /h:768

If you’ve a list of VMs. You can build a custom report using the PowerShell foreach loop as follows:

$array = @()
foreach ($vm in Get-AzVM) {
    $vmNicName = $vm.NetworkProfile.NetworkInterfaces.Id.Split("/")[8]
    $ipAddress = Get-AzPublicIpAddress | Where-Object {$_.IpConfiguration.Id -like "*$vmNicName*"}
    if ($null -ne $ipAddress) {
        $pipInput = New-Object -TypeName PSObject -Property $([ordered]@{
            VMName          = $vm.Name
            PublicIP        = $ipAddress.IpAddress
            ResourceGroup   = $vm.ResourceGroupName
            Location        = $vm.Location
        })
        $array += $pipInput
    }
}

$array

The output:

VMName        PublicIP        ResourceGroup Location
------        --------        ------------- --------
vm-1370231801 172.191.6.31    RG-1370231801 eastus
vm-1773859037 40.80.145.204   RG-1773859037 eastus
vm-63424851   172.171.237.199 RG-63424851   eastus

Leave a Comment

Required fields are marked *