VMware Cloud Community
BrianGordon84
Contributor
Contributor
Jump to solution

Export-CSV Help

$vms = Get-VM -Location "somehost"

foreach

($vm in $vms){

$vmobj_hds = $vm.HardDisks

foreach($vmhd in $vmobj_hds){

Write-Host $vm.Name, $vmhd.Filename}

}

I need to change this from Write-Host to Export-CSV with the following Titles, VM Name, HardDisk 1 HardDisk2, etc under HardDisk 1 should be the .HarDisk.Filename info. I've always had problems with the select -property and export-csv cmdlets. Any help would be appreciated.

Reply
0 Kudos
1 Solution

Accepted Solutions
mattboren
Expert
Expert
Jump to solution

Hello BrianGordon84-

Try something like:

## get the VMs, sort descending by number of harddisks
Get-VM | Sort @{e={($_.ExtensionData.Config.Hardware.Device | ?{$_ -is [VMware.Vim.VirtualDisk]}).count}} -Descending | %{
   
$vm = $_
   
## make an object in which to put the info
    $oInfo = New-Object -Type PSObject -Property @{VMname = $vm.Name}
   
## for each harddisk, add a property to the info object with the harddisk name and filename
    Get-HardDisk -VM $vm | %{
       
$oInfo | Add-Member -MemberType NoteProperty -Name $_.Name -Value $_.Filename
    }
## end foreach-object
    ## return the info object
    $oInfo
} |
Export-Csv -NoTypeInfo C:\temp\vmDiskInfo.csv

The Sort after the Get-VM is there to ensure that the first object exported has the most harddisks, which is what makes the exported CSV have the proper number of columns.  The headers in the CSV are made based off of the first object out.

The code could be optimized a bit using Get-View, but your question was about Export-Csv.

How does that do?

View solution in original post

Reply
0 Kudos
1 Reply
mattboren
Expert
Expert
Jump to solution

Hello BrianGordon84-

Try something like:

## get the VMs, sort descending by number of harddisks
Get-VM | Sort @{e={($_.ExtensionData.Config.Hardware.Device | ?{$_ -is [VMware.Vim.VirtualDisk]}).count}} -Descending | %{
   
$vm = $_
   
## make an object in which to put the info
    $oInfo = New-Object -Type PSObject -Property @{VMname = $vm.Name}
   
## for each harddisk, add a property to the info object with the harddisk name and filename
    Get-HardDisk -VM $vm | %{
       
$oInfo | Add-Member -MemberType NoteProperty -Name $_.Name -Value $_.Filename
    }
## end foreach-object
    ## return the info object
    $oInfo
} |
Export-Csv -NoTypeInfo C:\temp\vmDiskInfo.csv

The Sort after the Get-VM is there to ensure that the first object exported has the most harddisks, which is what makes the exported CSV have the proper number of columns.  The headers in the CSV are made based off of the first object out.

The code could be optimized a bit using Get-View, but your question was about Export-Csv.

How does that do?

Reply
0 Kudos