正如评论中已经提到的,您正在寻找Export-Csv
cmdlet which 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
文件。您可以查看此内容以获取更多信息。