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

此生再无相见时 提交于 2019-12-25 03:12:43

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/51099068/powershell-system-object-in-export-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!