PowerShell - 从哈希表转置结果

时间:2017-06-12 12:24:17

标签: powershell csv hashtable

我需要检查许多服务器的保修,但我在https://www.powershellgallery.com/packages/HPWarranty/2.6.2中找到的模块返回的输出似乎是一个哈希表,第一列包含我想要的行。

下面的脚本将返回此字段重复的每5行 - output1.csv:

  

TYPE System.Management.Automation.PSCustomObject

     

“组件”,“代码”   “SerialNumber”,“CZ36092P5H”
  “ProductNumber”,“727021-B21”
  “OverallEntitlementStartDate”,“2016-03-04”
  “OverallEntitlementEndDate”,“2019-04-02”
  “ActiveEntitlement”,“true”
  “SerialNumber”,“CZ36092P5K”
  “ProductNumber”,“727021-B21”
  “OverallEntitlementStartDate”,“2016-03-04”
  “OverallEntitlementEndDate”,“2019-04-02”
  “ActiveEntitlement”,“true”

如何转置输出以使SerialNumber,ProductNumber,OverallEntitlementStartDate,OverallEntitlementEndDate和ActiveEntitlement成为列?

# variables
$dest_path = "C:\Scripts\HPE\HPWarranty"
$export_date = Get-Date -Format o | ForEach-Object {$_ -replace ":", "-"}
$myScriptName = $MyInvocation.MyCommand.Name
$transcriptPath = $dest_path + "\" + $myScriptName + "_transcript_" + $export_date + ".txt"
$csvPath = $dest_path + "\" + "hpe_list1.csv"

#Start transcript of script activities and set transcript location
start-transcript -append -path $transcriptPath | Out-Null

# import serials & part numbers to be processed
$csv_info = Import-Csv $csvPath

foreach ($line in $csv_info) {
    $hash = (Get-HPEntWarrantyEntitlement -ProductNumber $line.ProductNumber -SerialNumber $line.SerialNumber)
    &{$hash.getenumerator() |
        ForEach-Object {new-object psobject -Property @{Component = $_.name;Codecount=$_.value}}
    } | Export-Csv "C:\Scripts\HPE\HPWarranty\output1.csv" -Append
}

# Stop Transcript
Stop-Transcript | Out-Null

hpe_list1.csv脚本进程包含两个服务器的详细信息:

  

ProductNumber,SerialNumber
  727021-B21,CZ36092P5H
  727021-B21,CZ36092P5K

1 个答案:

答案 0 :(得分:2)

将输出哈希表投射到[pscustomobject]

$WarrantyInfo = foreach ($line in $csv_info) {
    [pscustomobject](Get-HPEntWarrantyEntitlement -ProductNumber $line.ProductNumber -SerialNumber $line.SerialNumber)
}
$WarrantyInfo | Export-Csv "C:\Scripts\HPE\HPWarranty\output1.csv"