Powershell: System.Object[] in export-csv file

2019-08-21 15:39发布

I wrote this script to generate a csv file:

$VMs = Get-AzureRmVM
$vmOutput = @()
$VMs | ForEach-Object { 
  $tmpObj = New-Object -TypeName PSObject
  $tmpObj | Add-Member -MemberType Noteproperty -Name "VM Name" -Value $_.Name
  $tmpObj | Add-Member -MemberType Noteproperty -Name "VM Type" -Value $_.StorageProfile.osDisk.osType
  $tmpObj | Add-Member -MemberType Noteproperty -Name "VM Profile" -Value $_.HardwareProfile.VmSize
  $tmpObj | Add-Member -MemberType Noteproperty -Name "VM OS Disk Size" -Value $_.StorageProfile.OsDisk.DiskSizeGB
  $tmpObj | Add-Member -MemberType Noteproperty -Name "VM Data Disk Size" -Value $_.StorageProfile.DataDisks.DiskSizeGB
  $vmOutput += $tmpObj
}
$vmOutput | export-csv C:\Users\***\data.csv -delimiter ";" -force -notypeinformation

But as the last column VM Data Disk Size stores one than more data (there can be multiple disks) in file they're presented as System.Object[]. How can I force powershell to join this data into a single string?

I tried to add -join parameter after $tmpObj in line 9 ad after $vmoutput in last line, but there were no satisfactory results.

2条回答
beautiful°
2楼-- · 2019-08-21 16:22

It's always tricky to try to convert hierarchical data into structured data. Something like this should actually work:

$VMs = Get-AzureRmVM
$vmOutput = $VMs | ForEach-Object { 
    [PSCustomObject]@{
        "VM Name" = $_.Name
        "VM Type" = $_.StorageProfile.osDisk.osType
        "VM Profile" = $_.HardwareProfile.VmSize
        "VM OS Disk Size" = $_.StorageProfile.OsDisk.DiskSizeGB
        "VM Data Disk Size" = ($_.StorageProfile.DataDisks.DiskSizeGB) -join ','
    }
}
$vmOutput | export-csv C:\Users\***\data.csv -delimiter ";" -force -notypeinformation

I just cannot test - sorry.

查看更多
做自己的国王
3楼-- · 2019-08-21 16:41

I cannot test this either but can this also work?

$VMs = Get-AzureRmVM
$vmOutput = $VMs | ForEach-Object { 
    [PSCustomObject]@{
        "VM Name" = $_.Name
        "VM Type" = $_.StorageProfile.osDisk.osType
        "VM Profile" = $_.HardwareProfile.VmSize
        "VM OS Disk Size" = $_.StorageProfile.OsDisk.DiskSizeGB
        "VM Data Disk Size" = $_.StorageProfile.DataDisks.DiskSizeGB | Out-String
    }
}
$vmOutput | export-csv C:\Users\***\data.csv -delimiter ";" -force -notypeinformation
查看更多
登录 后发表回答