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
}
CodePudding user response:
csv is not designed to support properties with multivalues (e.g. 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, e.g.
$ReportDetails.ip-address = ($nic.IpConfigurations.PrivateIpAddress -join "|")
CodePudding user response:
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:
# 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 { $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
}
}
}