3

I have a hash table which consists of Component name and Codecount like this:

Name            Value
-----           ------
Comp1           2000
Comp2           3000

If it is exported into Excel, it will be easy to present.

How do I export this hash table from PowerShell into Excel?

StackzOfZtuff
  • 2,534
  • 1
  • 28
  • 25
Samselvaprabu
  • 16,830
  • 32
  • 144
  • 230

4 Answers4

12

Another vote for export-csv

&{$hash.getenumerator() |
  foreach {new-object psobject -Property @{Component = $_.name;Codecount=$_.value}}
 } | export-csv codecounts.csv -notype
mjolinor
  • 66,130
  • 7
  • 114
  • 135
  • `Export-CSV` converts to one column and not several. One should use `export-excel` or a solution from @cb. – Timo Jun 04 '20 at 07:31
6

To create an Excel file use something like this:

$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()

Remember that the Excel process need to be killed in task manager or use this function:

function Release-Ref ($ref) {

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

And modify last script's lines like this:

Release-Ref $workbook
Release-Ref $sheet

$excel.Quit()

release-Ref $excel
Adi Inbar
  • 12,097
  • 13
  • 56
  • 69
CB.
  • 58,865
  • 9
  • 159
  • 159
1

Use Export-CSV and open that CSV file with Excel

Ocaso Protal
  • 19,362
  • 8
  • 76
  • 83
  • The question is about exporting a hashtable and I would have expected to get info about the export of this specific data structure. `Export-CSV` converts to one column and not several. – Timo Jun 04 '20 at 07:29
1

Consider a hashtable:

$ht = @{"c1" = 100; "c2" = 200}

Iterate all the keys and add hashtable key and value into a file:

$ht.keys | % { add-content -path myFile.csv -value $("{0},{1}" -f $_, $ht.Item($_)) }
vonPryz
  • 22,996
  • 7
  • 54
  • 65