2012-02-22 62 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 
相关问题