数据无法从PowerShell脚本正确导出到.csv

w6lpcovy  于 2023-06-23  发布在  Shell
关注(0)|答案(1)|浏览(161)

虽然我可以把所有的数据显示到终端上;导出时,Hostname列将填充System.Object[]。我需要添加到更多的列,但在以前的尝试你也填充示例:oUTPUT_eXAMPLE

获取主机信息

$hosts = Get-VMHost

初始化一个空数组来存储数据

$serviceTags = @()

遍历每台主机

foreach ($hostsname in $hosts) 
 {
    **#Retrieve Datacenter, hostName and Model**
    $mydatacenter = Get-Datacenter -VMHost $hosts
    write-host "Completed Datacenter..."
    $vhostName = $hosts.Name
    write-host "Completed Hosts..."
    $model = $hosts.ExtensionData.Summary.Hardware.Model
    write-host "Completed Model..."   
    $serviceTag = ($hostsname| Get-View).Hardware.SystemInfo.OtherIdentifyingInfo |
        Where-Object { $_.IdentifierType.Key -eq "ServiceTag" } |
        Select-Object -ExpandProperty IdentifierValue
    write-host "Completed ServiceTag"

   # Create a custom object with Datacenter, host name Model and service tag

    $serviceTagInfo = [PSCustomObject]@{
       DataCenter = $mydatacenter
       HostName = $vhostName
       Model = $model
       ServiceTag = $serviceTag
       }

    # Add the object to the array
    $serviceTags += $serviceTagInfo

}
# Export the data to CSV
$serviceTags | Export-Csv -Path "c:\Users\myuser\Documents\ServiceTags2.csv" -NoTypeInformation
6qfn3psc

6qfn3psc1#

那条线

$vhostName = $hosts.Name

通过将$hosts数组的Name字段扩展为所有名称的字符串的数组来工作。相当于

$vhostName = $hosts | foreach {$_.Name}

它被称为member-access-enumeration
由于$vhostName是一个数组,因此在输出中它被扩展为System.Object[]。因为你已经迭代了$hosts,所以只需要使用当前的$hostname结构:

$vhostName = $hostname.Name

相关问题