Search code examples
powershellazure-devopsazure-powershellinventory

Is there any Powershell script or how can i modify this script to import multiple ips as a csv file if a vm has multiple ip addresses?


Is there any Powershell script or how can i modify this script to import multiple ips as a csv file if a vm has multiple ip addresses ? This is my existing script

# Create Report Array
$report = @()

# Get all the VMs from the selected subscription
$vms = Get-AzVM

# Get all the Network Interfaces
$nics = Get-AzNetworkInterface | Where-Object { $_.VirtualMachine -NE $null } 

foreach ($nic in $nics) {

$ReportDetails = "" | Select-Object  ip-address, vm_name, interface_name

$vm = $vms | Where-Object -Property Id -eq $nic.VirtualMachine.id 

$ReportDetails.vm_name = $vm.Name 
$ReportDetails.ip-address = [String]$nic.IpConfigurations.PrivateIpAddress
$ReportDetails.interface_name = $nic.Name 
$report += $ReportDetails 

}

$report | Sort-Object VMName | Format-Table ip-address, vm_name, interface_name
$report | Export-Csv -NoTypeInformation -Path $reportFile

}


Solution

  • As a general recommendation, you should try to avoid using the increase assignment operator (+=) to create a collection, besides $null` should be on the left side of the equality comparison.

    For the concerned script and expanding the ip_address property this would mean:

    # Get all the VMs from the selected subscription
    $vms = Get-AzVM
    
    # Get all the Network Interfaces
    $nics = Get-AzNetworkInterface | Where-Object { $Null -ne $_.VirtualMachine } 
    
    $ReportDetails = foreach ($nic in $nics) {
        $vm = $vms | Where-Object -Property Id -eq $nic.VirtualMachine.id 
        $nic.IpConfigurations.PrivateIpAddress.foreach{
            [PSCustomObject]@{
                vm_name = $vm.Name 
                ip_address = $_
                interface_name = $nic.Name
            }
        }
    }