VMware Cloud Community
Oatcake
Contributor
Contributor

Output to a CSV File

Hello - I have the following script that was kindly supplied to me sometime ago to tell me the connection state of all of the NIC's on our hosts. The script works great but what I would like to do is output the contents to a CSV for easier reading. I've tried piping it out but it doesn't work and I can only assume it is because it is a script. So is it possible to output the contents of this to a CSV file?

$VMs = Get-VM
$Nics
$Nics = $VMs | Get-NetworkAdapter
foreach ( $VM in $VMs )
{
Write-Host $VM.Name
foreach ( $Nic in ( $Nics | Where-Object { $_.ParentID -eq $VM.ID } ) )
{
if( $Nic.ConnectionState.Connected )
{
Write-Host ( "`t Connected - {0} - {1} - {2} - {3} - {4}" -f $VM, $Nic.Name, $Nic.NetworkName, $Nic.Type, $Nic.MacAddress )
}
else
{
Write-Host ( "`t Disconnected - {0} - {1} - {2} - {3}- {4}" -f $VM, $Nic.Name, $Nic.NetworkName, $Nic.Type, $Nic.MacAddress )
}
}
}

Many Thanks

Julian

0 Kudos
3 Replies
harkamal
Expert
Expert

$nic = @()

Get-VM | % {

     $vm = $_

     Write-Host "Processing $($_.Name)"

     Get-NetworkAdapter -VM $_.Name | % {

          $out = "" | Select VM, Nic, State, NetworkName, Type, Mac

          $out.VM = $vm.Name

          $out.Nic = $_.Name

          $out.State = $_.ConnectionState.Connected

          $out.NetworkName = $_.NetworkName

          $out.Type = $_.Type

          $out.Mac = $_.MacAddress

          $nic += $out

     }

}

$nic | ft -AutoSize

$nic | Export-Csv -NoTypeInformation -Path c:\abc.csv

0 Kudos
Oatcake
Contributor
Contributor

WOW - Thankyou very much, works an absolute treat.

0 Kudos
LucD
Leadership
Leadership

Try something like this

$report = @()
$VMs = Get-VM 
$Nics = $VMs | Get-NetworkAdapter
foreach ( $VM in $VMs ) {     foreach ( $Nic in ( $Nics | Where-Object { $_.ParentID -eq $VM.ID } ) )     {         $row = "" | Select VMname, NicName,NicState, NetworkName,NicType,MAC         $row.VMname = $VM.Name         $row.NicName = $Nic.Name         $row.NicState = if( $Nic.ConnectionState.Connected){"Connected"} else{"Disconnected"}         $row.NetworkName = $Nic.NetworkName         $row.NicType = $Nic.Type         $row.MAC = $Nic.MacAddress         $report += $row    } } $report | Export-Csv "C:\Nic-Report.csv" -NoTypeInformation


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos