Get azure disk info csv - azure

Hi I'm trying to get disk information alongside network information for azure virtual machines.
I'm probably doing something silly, but I thought it would be a case of adding the vm into the network foreach loop.
I've put the script below, can anyone see where I'm going wrong?
$reportName = "sample.csv"
$report = #()
$vms = Get-AzVM
$publicIps = Get-AzPublicIpAddress
$nics = Get-AzNetworkInterface | ?{ $_.VirtualMachine -NE $null}
foreach ($nic in $nics) {
$info = "" | Select VmName, ResourceGroupName, Region, VmSize, VirturalNetwork, Subnet, DnsServers, NicDns, PrivateIpAddress, OsType, OSDisk, DiagDisk, DataDisk, PublicIPAddress, vCPU, Memory
$vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id
foreach($publicIp in $publicIps) {
if($nic.IpConfigurations.id -eq $publicIp.ipconfiguration.Id) {
$info.PublicIPAddress = $publicIp.ipaddress
}
}
#$location = $vm.location
$info.OsType = $vm.StorageProfile.OsDisk.OsType
$info.VMName = $vm.Name
$info.ResourceGroupName = $vm.ResourceGroupName
$info.Region = $vm.Location
$info.VmSize = $vm.HardwareProfile.VmSize
$size = $info.VmSize = $vm.HardwareProfile.VmSize
$info.vCPU = (Get-AzVMSize -Location $location | ? {$_.name -eq $size}).NumberOfCores
$info.Memory = (Get-AzVMSize -Location $location | ? {$_.name -eq $size}).MemoryInMB
$info.VirturalNetwork = $nic.IpConfigurations.subnet.Id.Split("/")[-3]
$info.Subnet = $nic.IpConfigurations.subnet.Id.Split("/")[-1]
$info.PrivateIpAddress = $nic.IpConfigurations.PrivateIpAddress
$vm = get-azvm | ? {$_.name -eq $vm}
foreach ($vms in $vm) {
$info.OSDiskSizeGB = $vm.StorageProfile.OsDisk.DiskSizeGB
$info.OSDisk = $vm.StorageProfile.OsDisk.Vhd.uri
$info.DiagDisk = $vm.DiagnosticsProfile.BootDiagnostics.StorageUri
$info.DataDisk = $vm.StorageProfile.DataDisks.vhd.uri -join "**"
}
$report+=$info
}
$report | ft VmName, ResourceGroupName, Region, VmSize, VirturalNetwork, Subnet, DnsServers, NicDns, PrivateIpAddress, OsType, OSDisk, DiagDisk, DataDisk, PublicIPAddress, vCPU, Memory
$report | Export-CSV "c:\temp\$reportName"
Thanks in advance :)
EDIT:
This is the output I get, no disk infor for any VM
VmName ResourceGroupName Region VmSize VirturalNetwork Subnet DnsServers NicDns PrivateIpAddress OsType OSDisk DiagDisk DataDisk PublicIPAddress vCPU Memory
------ ----------------- ------ ------ --------------- ------ ---------- ------ ---------------- ------ ------ -------- -------- --------------- ---- ------
vmr1-sec1 DEPLOYRG1 westeurope Standard_D2_v4 av-vnet av-sub2 172.0.2.4 Windows 2 8192
vmr2-sec1 DEPLOYRG1 westeurope Standard_D2_v4 av-vnet av-sub2 172.0.2.5 Windows 2 8192
cks-cp1 K8S westeurope Standard_B2s K8S-vnet default 10.0.0.4 Linux 20.71.120.71 2 4096

At the moment, Azure uses Azure managed disk in default. Azure managed disks are no longer stored into blob storage by default. For more details, please refer to here and here. if you want to get the vhd URL of Azure managed disk, you need to run the command Grant-AzDiskAccess to get it. But please note that the URL has a life cycle and will expire after a period of time
So I suggest you store your disk name or disk id in your CSV file

Related

Assistance with looping through multiple subscriptions

I'm using the below script from http://vcloud-lab.com/entries/microsoft-azure/get-azure-virtual-machine-backup-reports-using-powershell to pull Azure VM backup details. Currently I have to run the script against each subscription, I would love to have it loop though all subscriptions.
I've been trying to get it working using this example https://www.jpaul.me/2019/05/azure-automation-how-to-quickly-work-with-many-subscriptions/ but I'm new to powershell and am struggling. Any suggestions would be really appreciated.
[CmdletBinding(SupportsShouldProcess=$True,
ConfirmImpact='Medium',
HelpURI='http://vcloud-lab.com',
DefaultParameterSetName = 'AllVirtualMachines'
)]
<#
.SYNOPSIS
Collect Azure VM Backup Information
.DESCRIPTION
This Script collects Azure Virtual Machine Backup Recovery service vault information, This report includes the complete backup status Information of VM.
.PARAMETER AllVirtualMachines
Collect Backup information of the all Azure Virtual Machines, This is default parameter.
.PARAMETER VirtualMachineList
You can specify for which virtual machine you want backup information.
.INPUTS
None. Provides virtual machine information.
.OUTPUTS
Generate Backup information. You can pipe information to Export-CSV.
.EXAMPLE
PS> .\Get-AzVMBackupInformation.ps1
VM_Name : vcloud-lab-vm01
VM_Location : uksouth
VM_ResourceGroupName : VCLOUD-LAB.COM
VM_BackedUp : True
VM_RecoveryVaultName : vault828
VM_RecoveryVaultPolicy : DailyPolicy-kosrnox0
VM_BackupHealthStatus : Passed
VM_BackupProtectionStatus : Healthy
VM_LastBackupStatus : Completed
VM_LastBackupTime : 27-05-2021 19:32:34
VM_BackupDeleteState : NotDeleted
VM_BackupLatestRecoveryPoint : 27-05-2021 19:32:37
VM_Id : /subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/VCLOUD-LAB.COM/providers/Microsoft.Compute/virtualMachines/vcloud-lab-vm01
RecoveryVault_ResourceGroupName : vCloud-lab.com
RecoveryVault_Location : uksouth
RecoveryVault_SubscriptionId : /subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vCloud-lab.com/providers/Microsoft.RecoveryServices/vaults/vault828
.EXAMPLE
PS> .\Get-AzVMBackupInformation.ps1 -AllVirtualMachines
This produces same result as .\Get-AzVMBackupInformation.ps1 from all VMs
.EXAMPLE
PS> .\Get-AzVMBackupInformation.ps1 -VirtualMachineList
Provide either single virtual machine name or in list
.LINK
Online version: http://vcloud-lab.com
.LINK
Get-AzVMBackupInformation.ps1
#>
Param
(
[parameter(Position=0, ParameterSetName = 'AllVMs' )]
[Switch]$AllVirtualMachines,
[parameter(Position=0, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName = 'VM' )]
[alias('Name')]
[String[]]$VirtualMachineList
) #Param
Begin
{
#Collecing Azure virtual machines Information
Write-Host "Collecing Azure virtual machine Information" -BackgroundColor DarkGreen
if (($PSBoundParameters.ContainsKey('AllVirtualMachines')) -or ($PSBoundParameters.Count -eq 0))
{
$vms = Get-AzVM
} #if ($PSBoundParameters.ContainsKey('AllVirtualMachines'))
elseif ($PSBoundParameters.ContainsKey('VirtualMachineList'))
{
$vms = #()
foreach ($vmname in $VirtualMachineList)
{
$vms += Get-AzVM -Name $vmname
} #foreach ($vmname in $VirtualMachineList)
} #elseif ($PSBoundParameters.ContainsKey('VirtualMachineList'))
#Collecing All Azure backup recovery vaults Information
Write-Host "Collecting all Backup Recovery Vault information" -BackgroundColor DarkGreen
$backupVaults = Get-AzRecoveryServicesVault
} #Begin
Process
{
$vmBackupReport = [System.Collections.ArrayList]::new()
foreach ($vm in $vms)
{
$recoveryVaultInfo = Get-AzRecoveryServicesBackupStatus -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Type 'AzureVM'
if ($recoveryVaultInfo.BackedUp -eq $true)
{
Write-Host "$($vm.Name) - BackedUp : Yes"
#Backup Recovery Vault Information
$vmBackupVault = $backupVaults | Where-Object {$_.ID -eq $recoveryVaultInfo.VaultId}
#Backup recovery Vault policy Information
$container = Get-AzRecoveryServicesBackupContainer -ContainerType AzureVM -VaultId $vmBackupVault.ID -FriendlyName $vm.Name #-Status "Registered"
$backupItem = Get-AzRecoveryServicesBackupItem -Container $container -WorkloadType AzureVM -VaultId $vmBackupVault.ID
} #if ($recoveryVaultInfo.BackedUp -eq $true)
else
{
Write-Host "$($vm.Name) - BackedUp : No" -BackgroundColor DarkRed
$vmBackupVault = $null
$container = $null
$backupItem = $null
} #else if ($recoveryVaultInfo.BackedUp -eq $true)
[void]$vmBackupReport.Add([PSCustomObject]#{
VM_Name = $vm.Name
VM_Location = $vm.Location
VM_ResourceGroupName = $vm.ResourceGroupName
VM_BackedUp = $recoveryVaultInfo.BackedUp
VM_RecoveryVaultName = $vmBackupVault.Name
VM_RecoveryVaultPolicy = $backupItem.ProtectionPolicyName
VM_BackupHealthStatus = $backupItem.HealthStatus
VM_BackupProtectionStatus = $backupItem.ProtectionStatus
VM_LastBackupStatus = $backupItem.LastBackupStatus
VM_LastBackupTime = $backupItem.LastBackupTime
VM_BackupDeleteState = $backupItem.DeleteState
VM_BackupLatestRecoveryPoint = $backupItem.LatestRecoveryPoint
VM_Id = $vm.Id
RecoveryVault_ResourceGroupName = $vmBackupVault.ResourceGroupName
RecoveryVault_Location = $vmBackupVault.Location
RecoveryVault_SubscriptionId = $vmBackupVault.ID
}) #[void]$vmBackupReport.Add([PSCustomObject]#{
} #foreach ($vm in $vms)
} #Process
end
{
$vmBackupReport
} #end
You can try this sample script from the MS doc for looping through multiple subscriptions.
Connect-AzAccount
$SubscriptionList = Get-AzSubscription
foreach ($Id in $SubscriptionList)
{
#Provide the subscription Id where the VMs reside
$subscriptionId = $Id
#Provide the name of the csv file to be exported
$reportName = "myReport.csv"
Select-AzSubscription $subscriptionId
$report = #()
$vms = Get-AzVM
$publicIps = Get-AzPublicIpAddress
$nics = Get-AzNetworkInterface | ?{ $_.VirtualMachine -NE $null}
foreach ($nic in $nics)
{
$info = "" | Select VmName, ResourceGroupName, Region, VmSize, VirtualNetwork, Subnet, PrivateIpAddress, OsType, PublicIPAddress, NicName, ApplicationSecurityGroup, subscriptionId
$vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id
foreach($publicIp in $publicIps)
{
if($nic.IpConfigurations.id -eq $publicIp.ipconfiguration.Id)
{
$info.PublicIPAddress = $publicIp.ipaddress
}
}
$info.subscriptionId = $subscriptionId
$info.OsType = $vm.StorageProfile.OsDisk.OsType
$info.VMName = $vm.Name
$info.ResourceGroupName = $vm.ResourceGroupName
$info.Region = $vm.Location
$info.VmSize = $vm.HardwareProfile.VmSize
$info.VirtualNetwork = $nic.IpConfigurations.subnet.Id.Split("/")[-3]
$info.Subnet = $nic.IpConfigurations.subnet.Id.Split("/")[-1]
$info.PrivateIpAddress = $nic.IpConfigurations.PrivateIpAddress
$info.NicName = $nic.Name
$info.ApplicationSecurityGroup = $nic.IpConfigurations.ApplicationSecurityGroups.Id
$report+=$info
}
$report | ft subscriptionId, VmName, ResourceGroupName, Region, VmSize, VirtualNetwork, Subnet, PrivateIpAddress, OsType, PublicIPAddress, NicName, ApplicationSecurityGroup
$report | Export-CSV "$home/$reportName"
}
References: Collect details about all VMs in a subscription with PowerShell - Azure Virtual Machines | Microsoft Docs , Iterate through subscriptions using an Array to avoid manual work · Issue #50670 · MicrosoftDocs/azure-docs · GitHub and powershell - How to loop through multiple Azure subscriptions on Azure Pipelines Yaml? - Stack Overflow

Output of Azure subnets with links to attached VNet, route table and NSG

I'm currently working on a script that gives me the output of every Subnet in an Azure Subscription, with links to the VNet, NSG, and the Route Table. The Route Table Name is currently missing in the script, but I want to focus on fixing the NSG right now.
This is what my Script looks like:
$VNets = Get-AzVirtualNetwork
$NSG = Get-AzNetworkSecurityGroup
$VNets | ForEach-Object {
$VNettemp = $_
$result = $_.Subnets | Select-Object #{Label="Subnet Name";Expression={$_.Name}},#{Label="Subnet";Expression={$_.AddressPrefix}}
$_ | ForEach-Object {
$result | Add-Member -Name "VNet Name" -Value $_.Name -MemberType NoteProperty
}
if ($_.Subnets.NetworksecurityGroup -ne "null"){
$NSG | ForEach-Object{
if ($VNettemp.Subnets.Id -contains $_.Subnets.Id ){
$result | Add-Member -Name "NSG Name" -Value $_.name -MemberType NoteProperty -Force
}
}
}
return $result
}
The output looks like this:
Subnet Name Subnet VNet Name NSG Name
----------- ------ --------- --------
default-subnet 10.10.10.0/28 vnet-ine-test test-nsg
vnet-ine-test-snet-test 10.10.0.0/24 vnet-ine-test test-nsg
default 10.0.0.0/24 vnet-chn-docker vnet-chn-docker-nsg
vnet-test-subnet 10.0.1.0/24 vnet-chn-docker vnet-chn-docker-nsg
The desired output would look like this because 'default-subnet' and 'vnet-test-subnet' have no NSG attached:
Subnet Name Subnet VNet Name NSG Name
----------- ------ --------- --------
default-subnet 10.10.10.0/28 vnet-ine-test
vnet-ine-test-snet-test 10.10.0.0/24 vnet-ine-test test-nsg
default 10.0.0.0/24 vnet-chn-docker vnet-chn-docker-nsg
vnet-test-subnet 10.0.1.0/24 vnet-chn-docker
Does anybody know how to fix the output? I tried it with an else statement that fills in an empty value for "NSG Name" but then the name gets canceled entirely for the whole VNet.
Thanks for the Help!
Regarding the issue, please refer to the following script
$VNets = Get-AzVirtualNetwork
$NSG = Get-AzNetworkSecurityGroup
$resports=#()
$info = #{ "Subnet Name"=""; "Subnet"=""; "VNet Name"="" ; "NSG Name"=""}
foreach($VNet in $VNets){
$info.'VNet Name'=$VNet.Name
$info.'NSG Name'=$null
Foreach($sub in $VNet.Subnets){
$info.'Subnet Name' =$sub.Name
$info.Subnet=$sub.AddressPrefix
if($sub.NetworkSecurityGroup -ne $null){
$NSG | ForEach-Object{
if ($VNet.Subnets.Id -contains $_.Subnets.Id ){
$info.'NSG Name'=$_.Name
}
}
}
$obj=New-Object PSObject -Property $info
$resports +=$obj
}
}

Azure / Powershell / Get VM IPs with subscription names

I have a script that outputs all of my subscription's VM IPs. The problem I want to solve is getting the subscription name in the output. Currently, the script goes through all subscriptions and returns VM Name, resource group, internal/external IPs, etc. But no matter what I try, I can't get the output to also return the subscription name. I can get the field to populate with the subscription heading, but the fields are blank.
My ultimate goal is to get all VMs with public addresses use to audit NSG rules, but include subscription names as well.
Any ideas?
$reportName = "AzVMIPs.csv"
Get-AzSubscription | Select-AzSubscription | ForEach-Object {$_
$report = #()
$vms = Get-AzVM
$publicIps = Get-AzPublicIpAddress
$nics = Get-AzNetworkInterface | ?{ $_.VirtualMachine -NE $null}
foreach ($nic in $nics) {
$info = "" | Select-Object VmName, ResourceGroupName, Region, VirturalNetwork, Subnet, PrivateIpAddress, OsType, PublicIPAddress
$vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id
foreach($publicIp in $publicIps) {
if($nic.IpConfigurations.id -eq $publicIp.ipconfiguration.Id) {
$info.PublicIPAddress = $publicIp.ipaddress
}
}
$info.OsType = $vm.StorageProfile.OsDisk.OsType
$info.VMName = $vm.Name
$info.ResourceGroupName = $vm.ResourceGroupName
$info.Region = $vm.Location
$info.VirturalNetwork = $nic.IpConfigurations.subnet.Id.Split("/")[-3]
$info.Subnet = $nic.IpConfigurations.subnet.Id.Split("/")[-1]
$info.PrivateIpAddress = $nic.IpConfigurations.PrivateIpAddress
$report+=$info
}
$report | Export-CSV "$home\$reportName" -NoTypeInformation -Append
}
Thanks,
If you want to get subscription Name in your report, please refer to the following script
$reportName = "AzVMIPs.csv"
(Get-AzSubscription)|ForEach-Object{
Select-AzSubscription $_
$report = #()
$vms = Get-AzVM
$publicIps = Get-AzPublicIpAddress
$nics = Get-AzNetworkInterface | ?{ $_.VirtualMachine -NE $null}
foreach ($nic in $nics) {
$info = "" | Select-Object VmName, ResourceGroupName, Region, VirturalNetwork, Subnet, PrivateIpAddress, OsType, PublicIPAddress, SubscriptionName
$vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id
foreach($publicIp in $publicIps) {
if($nic.IpConfigurations.id -eq $publicIp.ipconfiguration.Id) {
$info.PublicIPAddress = $publicIp.ipaddress
}
}
$info.OsType = $vm.StorageProfile.OsDisk.OsType
$info.VMName = $vm.Name
$info.ResourceGroupName = $vm.ResourceGroupName
$info.Region = $vm.Location
$info.VirturalNetwork = $nic.IpConfigurations.subnet.Id.Split("/")[-3]
$info.Subnet = $nic.IpConfigurations.subnet.Id.Split("/")[-1]
$info.PrivateIpAddress = $nic.IpConfigurations.PrivateIpAddress
$info.SubscriptionName=$_.Name
$report+=$info
}
$report | Export-CSV "$home\$reportName" -NoTypeInformation -Append
}
I modified the code a bit and it reports Subscription name also. Please try it yourself
$reportName = "D:\AzVMIPs.csv"
Get-AzSubscription | Select-AzSubscription | ForEach-Object {$_
$report = #()
$vms = Get-AzVM
$publicIps = Get-AzPublicIpAddress
$nics = Get-AzNetworkInterface | ?{ $_.VirtualMachine -NE $null}
foreach ($nic in $nics) {
$info = "" | Select-Object VmName, ResourceGroupName, Region, VirturalNetwork, Subnet, PrivateIpAddress, OsType, PublicIPAddress, SubscriptionName
$vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id
foreach($publicIp in $publicIps) {
if($nic.IpConfigurations.id -eq $publicIp.ipconfiguration.Id) {
$info.PublicIPAddress = $publicIp.ipaddress
}
}
$info.OsType = $vm.StorageProfile.OsDisk.OsType
$info.VMName = $vm.Name
$info.ResourceGroupName = $vm.ResourceGroupName
$info.Region = $vm.Location
$info.VirturalNetwork = $nic.IpConfigurations.subnet.Id.Split("/")[-3]
$info.Subnet = $nic.IpConfigurations.subnet.Id.Split("/")[-1]
$info.PrivateIpAddress = $nic.IpConfigurations.PrivateIpAddress
$info.SubscriptionName = (Get-AzContext).Name
$report+=$info
}
$report | Export-CSV "D:\1.CSV" -NoTypeInformation -Append
}
Thanks,
Manu
Azure Resource Graph (ARG) can be used as well. Its main advantage is that it will output all the VMs across all subscriptions within a tenant, quite fast. Eg for several thousand VMs across hundreds of subscriptions, it takes a matter of seconds to have the output file.
The script further down will report correctly on multiple vmNics and multiple IP configurations per vmNic. If running from either a local Powershell session or Cloud Shell, make sure you have the Az.ResourceGraph module installed first.
A sample report ran against my test tenant:
The script will only report the first 5,000 VMs in the tenant in its current form. For a version that doesn't have such limitations, including being able to report across more than 1,000 Azure subscriptions, the script here can be used, by just swapping out the ARG query with the one seen below.
As for building a very similar Azure Resource Graph query like the one used in the script - which might look cryptic at first - this is described at length here.
$reportName = "AzVMIPs.csv"
$ARG_query = #"
resourcecontainers
| where type =~ 'microsoft.resources/subscriptions'
| project id, subscriptionId, subscriptionName = name
| join (Resources
| where type =~ 'microsoft.compute/virtualmachines'
| project vmId = tolower(tostring(id)), vmName = name, subscriptionId
| join (Resources
| where type =~ 'microsoft.network/networkinterfaces'
| mv-expand ipconfig=properties.ipConfigurations
| project vmId = tolower(tostring(properties.virtualMachine.id)), privateIp = ipconfig.properties.privateIPAddress, publicIpId = tostring(ipconfig.properties.publicIPAddress.id)
| join kind=leftouter (Resources
| where type =~ 'microsoft.network/publicipaddresses'
| project publicIpId = id, publicIp = properties.ipAddress
) on publicIpId
| project-away publicIpId, publicIpId1
| summarize privateIps = make_list(privateIp), publicIps = make_list(publicIp) by vmId
) on vmId
| project-away vmId1
| sort by vmName asc
) on subscriptionId
| project-away subscriptionId1
"#
$results = Search-AzGraph -Query $ARG_query -First 5000
$results | Select-Object -ExcludeProperty ResourceId | Export-CSV "$home\$reportName" -NoTypeInformation

How to export Virtual Machine Names and IP Addresses from within multiple azure subscriptions

I have been able to export out VM Names and IP Addresses from within a single azure subscription using the following script.
$report = #()
$vms = get-azvm
$nics = get-aznetworkinterface | ?{ $_.VirtualMachine -NE $null}
foreach($nic in $nics)
{
$info = "" | Select VmName, ResourceGroupName, HostName, IpAddress
$vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id
$info.VMName = $vm.Name
$info.ResourceGroupName = $vm.ResourceGroupName
$info.IpAddress = $nic.IpConfigurations.PrivateIpAddress
$info.HostName = $vm.OSProfile.ComputerName
$report+=$info
}
$report | Export-Csv -Path "c:\Azure\VMIPs.csv"
However I have tried using the below to export the same data from an azure account that has multiple subscriptions but all I get is a blank CSV file.
$report = #()
$vms = get-azvm
$azureSubs = get-azsubscription
$azureSubs.foreach{
Select-AzSubscription $_ # << change active subscription
$nics = get-aznetworkinterface | ?{ $_.VirtualMachine -NE $null}
foreach($nic in $nics)
{
$info = "" | Select VmName, ResourceGroupName, HostName, IpAddress
$vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id
$info.VMName = $vm.Name
$info.ResourceGroupName = $vm.ResourceGroupName
$info.IpAddress = $nic.IpConfigurations.PrivateIpAddress
$info.HostName = $vm.OSProfile.ComputerName
$report+=$info
}
}
$report | Export-Csv -Path "c:\Azure\VMIPs.csv"
Can anyone assist?
I think you need to move Get-AzVm right after the Select-AzSubscription? because right now you only get vms once (in default subscription)
$azureSubs.foreach{
Select-AzSubscription $_ # << change active subscription
$nics = get-aznetworkinterface | ?{ $_.VirtualMachine -NE $null}
$vms = get-azvm
...
}

Easier way of retrieving an Azure VM's Public IP address

Using the name/resource group of a specific VM, I'm trying to get the VM's public IP address.
This code works but it seems unwieldy in comparison to other AzureRM cmdlets.
$VM = Get-AzureRmVM -ResourceGroupName MyResourceGroup -Name MyVMName
$NIC = $VM.NetworkProfile.NetworkInterfaces[0].Id -replace '.*\/'
$NI = Get-AzureRmNetworkInterface -Name $NIC -ResourceGroupName MyResourceGroup
$NIIC = Get-AzureRmNetworkInterfaceIpConfig -NetworkInterface $NI
$PIP = $NIIC.PublicIpAddress.Id -replace '.*\/'
$PIP = Get-AzureRmPublicIpAddress -Name $PIP -ResourceGroupName MyResourceGroup
$PIP.IpAddress
Is there a quicker/easier/shorter way of accessing this information?
As far as i know, Not Yet for PowerShell. But you can use Azure CLI
az vm list-ip-addresses -n <VMName> -g <ResourceGroup> | grep publicIpAddresses
Try the Azure CLI command:
az vm list-ip-addresses -g groupName -n vmName --query "[].virtualMachine.network.publicIpAddresses[*].ipAddress" -o tsv
Or the PowerShell command just filter with your vm name:
$ipAddress= (Get-AzureRmPublicIpAddress -ResourceGroupName groupName | Where-Object { $_.IpConfiguration.Id -like "*vmName*" }
)
$ipAddress.IpAddress
It's possible. This script will list all VMs PIP in your Azure cloud.
OLD
$VM_int = Get-AzureRmResource -ODataQuery "`$filter=resourcetype 'Microsoft.Compute/virtualMachines'"
foreach($int in $VM_int){
$vmName = $int.Name
$ipAddress= (Get-AzureRmPublicIpAddress -ResourceGroupName $int.ResourceGroupName | Where-Object { $_.IpConfiguration.Id -like "*$vmName*" })
$vmName + ' --- ' + $ipAddress.IpAddress
}
UPDATE
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.
$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 psobject -Property #{
VM = $vm.Name
PublicIP = $ipAddress.IpAddress
}
$array += $pipInput
}
}
The way i got the value for my Linux VM's was using below code.
Get-AzureRmPublicIpAddress -ResourceGroupName <yourRG> -Name <yourVMName> | Select-Object {$_.IpAddress}
This will return something of this sort:
$_.IpAddress
------------
52.170.56.60
This outputs a bit of information however the public IP address is in there.
Get-AzPublicIpAddress -ResourceGroupName MyResourceGroup | Where-Object {$_.name -like "*MyVMName*" }
Or you can do this to just get the IP address:
Get-AzPublicIpAddress -ResourceGroupName MyResourceGroup | Where-Object {$_.name -like "*MyVMName*" } | Select-Object { $_.IpAddress }
Output is like:
$_.IpAddress
--------------
13.255.162.33
You can also match the AzPublicIpAddress IpConfiguration.Id with the VM's NetworkInterfaces.Id:
Get-AzPublicIpAddress | ?{$_.IpConfiguration.Id -match "$((Get-AzVM -Name $computername).NetworkProfile.NetworkInterfaces.Id).*" }
#Get the VM object
$vm = Get-AzVM -Name $vmName -Status
#Get name of network adapter object attached to VM
$NetworkInterfaceName = $vm.NetworkProfile.NetworkInterfaces.Id.Split("/") | Select -Last 1
#Get network adaptor object attached to VM
$NetworkInterfaceObject = Get-AzNetworkInterface -Name $NetworkInterfaceName
#Get public IP Address object name attached to network adaptor object
$ipObjectName = $NetworkInterfaceObject.IpConfigurations.PublicIpAddress.Id.Split("/") | Select -Last 1
#get publivc IP Address attached to public IP Address object
$ipObject = Get-AzPublicIpAddress -ResourceGroupName $resourceGroupName -Name $ipObjectName
Write-Output $ipObject.IpAddress
Yet another method from within a Linux VM.
First, install the Azure command-line tools in the VM, see Azure docs
Second, execute the following in a shell on the VM:
az network public-ip list --query "[?dnsSettings.domainNameLabel=='MY_VM']"
where MY_VM is (hopefully) the host name of your VM. The command returns a multiline JSON string which is a list. Example is shown below:
[
{
"dnsSettings": {
"domainNameLabel": "MY_VM",
"fqdn": "my_vm.westeurope.cloudapp.azure.com"
},
"etag": "W/\"some_uuid...\"",
...
"ipAddress": "AAA.BBB.CCC.DDD",
},
...
]
How to parse the FQDN and the public IP out of this is left as an exercise to the reader :-)

Resources