简体   繁体   中英

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

}

csv is not designed to support properties with multivalues (eg array). you could use json instead:

$report | convertto-json | set-content -path $reportFile

Or if it has to be a csv you can flattern the structure or join the array to a delimited string, eg

$ReportDetails.ip-address = ($nic.IpConfigurations.PrivateIpAddress -join "|")

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
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM