将CSV传递到Excel工作簿(不是来自文件)

我有一个包含日志条目的CSV文件的文件夹。 对于CSV的每个条目,如果Risk属性不是Low且不是None,那么我把它放在一个累积CSV对象中。 从那里, 我想直接导入到Excel工作簿,而不必将CSV保存到文件

$CSVPaths = (Split-Path $PSCommandPath) $AccumulateExportPath = (Split-Path $PSCommandPath) $FileName="Accumulate" $Acc=@() Foreach ($csv in (Get-ChildItem C:\Scripts\Nessus\Sheets |? {$_.Extension -like ".csv" -and $_.BaseName -notlike "$FileName"})) { $Content = Import-CSV $csv.FullName Foreach ($Log in $Content) { If ($Log.Risk -ne "None" -and $Log.Risk -ne "Low") { $Acc+=$Log } } } $CSV = $ACC |ConvertTo-CSV -NoTypeInformation Add-Type -AssemblyName Microsoft.Office.Interop.Excel $Script:Excel = New-Object -ComObject Excel.Application $Excel.Visible=$True #$Excel.Workbooks.OpenText($CSV) What should replace this? 

有没有像OpenText()这样的方法,让我传递一个CSV 对象,而不是文件path到CSV文件,或者我将不得不写我自己的转换function?

有趣的问题。 我不知道一种方法,允许您传递一个CSV 对象

但是,如果您的结果CSV不是太大,而且您使用PowerShell 5.0+,则可以将该对象转换为string并利用Set-Clipboard ( 更多信息 )

 $headers = ($csv | Get-Member | Where-Object {$_.MemberType -eq "NoteProperty"}).Name $delim = "`t" # headers foreach($header in $headers){ $myString += $header + $delim } # trim delimiter at the end, and add new line $myString = $myString.TrimEnd($delim) $myString = $myString + "`n" # loop over each line and repeat foreach($line in $csv){ foreach($header in $headers){ $myString += $line.$header + $delim } $myString = $myString.TrimEnd($delim) $myString = $myString + "`n" } # copy to clipboard Set-Clipboard $myString # paste into excel from clipboard $Excel.Workbooks.Worksheets.Item(1).Paste() 

这里是另一种从PowerShell创buildExcel电子表格而不写入.csv文件的方法。

 $dirs = 'C:\src\t', 'C:\src\sql' $records = $() $records = foreach ($dir in $dirs) { Get-ChildItem -Path $dir -File '*.txt' -Recurse | Select-Object @{Expression={$_.FullName}; Label="filename"} } #open excel $excel = New-Object -ComObject excel.application $excel.visible = $false #add a default workbook $workbook = $excel.Workbooks.Add() #remove worksheet 2 & 3 $workbook.Worksheets.Item(3).Delete() $workbook.Worksheets.Item(2).Delete() #give the remaining worksheet a name $uregwksht = $workbook.Worksheets.Item(1) $uregwksht.Name = 'File Names' # Start on row 1 $i = 1 # the .appendix to $record refers to the column header in the csv file foreach ($record in $records) { $excel.cells.item($i,1) = $record.filename $i++ } #adjusting the column width so all data's properly visible $usedRange = $uregwksht.UsedRange $usedRange.EntireColumn.AutoFit() | Out-Null #saving & closing the file $outputpath = Join-Path -Path $Env:USERPROFILE -ChildPath "desktop\exceltest.xlsx" $workbook.SaveAs($outputpath) $excel.Quit()