2012-02-22 83 views

回答

7

一票出口-CSV

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

考慮一個哈希表文件:

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

迭代所有的按鍵,並添加哈希表鍵和值到一個文件:

$ht.keys | % { add-content -path myFile.csv -value $("{0},{1}" -f $_, $ht.Item($_)) } 
+1

當您的散列表鍵包含「,」時,您將會遇到此解決方案的問題, – 2012-02-22 10:33:01

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

請記住,Excel進程需要在任務管理器中被殺害或使用該功能:

function Release-Ref ($ref) { 

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

並修改最後的劇本的臺詞是這樣的:

Release-Ref $workbook 
Release-Ref $sheet 

$excel.Quit() 

release-Ref $excel 
相關問題