从Powershell中将EventViewerLogs存储在Excel电子表格中

时间:2018-04-13 04:45:38

标签: excel powershell cmdlet get-eventlog

我想存储输出:

$Application = Get-EventLog -LogName Application | Where-Object {($_.EntryType -like 'Error' -or $_.EntryType -like 'Warning')};

在Excel电子表格中。

我尝试过:$Application | Out-File E:\app.csv;

我的输出为:OUTPUT

正如您所看到的,这些列未在Excel电子表格中单独对齐,而且列值/内容也不完整,以(...)结尾。

我想正确存储每个列在Excel电子表格中保存的完整值。

2 个答案:

答案 0 :(得分:0)

正如评论中已经提到的那样,您正在寻找Export-Csv cmdlet Converts objects into a series of comma-separated (CSV) strings and saves the strings in a CSV file。你可以这样做 -

$Application = Get-EventLog -LogName Application | Where-Object {($_.EntryType -like 'Error' -or $_.EntryType -like 'Warning')};
$Application | Export-Csv -path E:\app.csv -NoTypeInformation

问题的下一步是将csv文件转换为excel文件,因为您需要存储在Excel电子表格中的数据。下面是我已经成功使用了很长时间的代码。

#Define locations and delimiter
$csv = "E:\app.csv" #Location of the source file
$xlsx = "E:\app.xlsx" #Desired location of output
$delimiter = ";" #Specify the delimiter used in the file

# Create a new Excel workbook with one empty sheet
$excel = New-Object -ComObject excel.application 
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)

# Build the QueryTables.Add command and reformat the data
$TxtConnector = ("TEXT;" + $csv)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
$query.TextFileOtherDelimiter = $delimiter
$query.TextFileParseType  = 1
$query.TextFileColumnDataTypes = ,1 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1

# Execute & delete the import query
$query.Refresh()
$query.Delete()

# Save & close the Workbook as XLSX.
$Workbook.SaveAs($xlsx,51)
$excel.Quit()

上面的代码会将csv文件转换为XLSX文件。您可以查看this以获取更多信息。

答案 1 :(得分:0)

您可以使用 - Delimiter "#seperator "导出到csv以分隔excel中的列

它可能看起来像这样

$Application | Export-Csv C:\test.csv -Delimiter ";"
相关问题