itye1970
itye1970

Reputation: 1995

how do i get the ip addresses and names of vm in avariable

I want to retrieve a list of all the vms which have the name "server" in them and also the ip addresses of these machines. The below works great for getting the names, however how can i add the private ip address of each vm into the variable?

$machines = Get-AzureRmVM -ResourceGroupName $resourcegroup | where {$_.Name -like server" + "*"}

Upvotes: 0

Views: 999

Answers (1)

Vincent K
Vincent K

Reputation: 1346

Get-AzureRmVM Cmdlet doesn't get the IP Address info of any VM.

You have to get the NetworkInterface Name from the Get-AzureRmVM and then pass the value to Get-AzureRmNetworkInterface Cmdlet to get the Private IP .

Get-AzureRmVM -ResourceGroupName TestRG | Where-Object {$_.Name -like '*server*'} | ForEach-Object {
    $NIC = $_.NetworkProfile.NetworkInterfaces.id -replace '^.*/'
    $RGName = $_.NetworkProfile.NetworkInterfaces.id -replace '^.*resourceGroups/(.*)/providers.*','$1'    
    $IP = (Get-AzureRmNetworkInterface -Name $NIC -ResourceGroupName $RGName).IpConfigurations.PrivateIpAddress
    [PSCustomObject]@{VMName = $_.Name ; PrivateIpAddress = $IP}
}

Or You can directly call the Get-AzureRmNetworkInterface and filter VM with the VirtualMachine.ID property

$Resourcegroup = 'TestRG'; $VmName = 'server'
Get-AzureRmNetworkInterface | Where-Object { $_.VirtualMachine.ID -match "^.*resourceGroups/$Resourcegroup.*virtualMachines/.*$VmName.*" } | 
    Select-Object @{L='VMName';ex = {$_.VirtualMachine.Id -replace '^.*/'}}, @{L='PrivateIpAddress';ex = {$_.IpConfigurations.PrivateIpAddress}}

Upvotes: 1

Related Questions