如何将哈希表名称和值导出到Excel列中?

Sam*_*abu 2 powershell powershell-2.0

我有一个哈希表,其中包含组件名称Codecount,如下所示:

Name            Value
-----           ------
Comp1           2000
Comp2           3000
Run Code Online (Sandbox Code Playgroud)

如果将其导出到Excel中,则很容易呈现.

如何将此哈希表从PowerShell导出到Excel?

mjo*_*nor 10

另一个对export-csv的投票

&{$hash.getenumerator() |
  foreach {new-object psobject -Property @{Component = $_.name;Codecount=$_.value}}
 } | export-csv codecounts.csv -notype
Run Code Online (Sandbox Code Playgroud)


CB.*_*CB. 5

要创建Excel文件,请使用以下内容:

$ht = @{"comp1"="2000";"comp2"="3000"}
$excel = new-Object -comobject Excel.Application
$excel.visible = $true # set it to $false if you don't need monitoring the actions...
$workBook = $excel.Workbooks.Add()
$sheet =  $workBook.Sheets.Item(1)
$sheet.Name = "Computers List"
$sheet.Range("A1","A2").ColumnWidth = 40
$sheet.range('A:A').VerticalAlignment = -4160 #align is center (TOP -4108 Bottom -4107 Normal)

$sheet.Cells.Item(1,1) = "Name"
$sheet.cells.Item(1,2) = "Value"

$index = 2

$ht.keys | % {  

    $sheet.Cells.Item($index,1) = $_
    $sheet.Cells.Item($index,2) = $ht.item($_)
    $index++
}

$workBook.SaveAs("C:\mylist.xls")
$excel.Quit()
Run Code Online (Sandbox Code Playgroud)

请记住,需要在任务管理器中终止Excel进程或使用此函数:

function Release-Ref ($ref) {

    [System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) | out-null
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()
}
Run Code Online (Sandbox Code Playgroud)

并修改上一个脚本的行,如下所示:

Release-Ref $workbook
Release-Ref $sheet

$excel.Quit()

release-Ref $excel
Run Code Online (Sandbox Code Playgroud)