0

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

}

John
  • 9
  • 3

2 Answers2

0

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 "|")
Toni
  • 1,738
  • 1
  • 3
  • 11
  • Okay thats great. But how can i fetch all the ip addresses of a vm incase a vm has multiple ip addresses. – John Oct 04 '22 at 17:17
0

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
        }
    }
}
iRon
  • 20,463
  • 10
  • 53
  • 79
  • Thankyou for the help and tips. After modification i am getting this error. At line:16 char:15 + ip-address = $_ + ~ Missing '=' operator after key in hash literal. At line:11 char:42 + $ReportDetails = foreach ($nic in $nics) { + ~ Missing closing '}' in statement block or type definition. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingEqualsInHashLiteral – John Oct 04 '22 at 17:16
  • The script suggestion was based on your own properties where `ip-address` is either a typo or should be quoted (I have changed it in my answer). – iRon Oct 04 '22 at 18:06