简体   繁体   English

如何使用Powershell正确导出为CSV

[英]How to Properly Export to CSV Using Powershell

May I know how to properly export this script to CSV? 我可以知道如何将该脚本正确导出为CSV吗?

Try {

    Invoke-Command -scriptblock {Get-EventLog System -After "7/8/2017" -Before "07/28/2017" | 
    Where-Object {$_.EventID -eq "50" -or $_.EventID -eq "51" -or $_.EventID -eq "55" -or $_.EventID -eq "57" -or $_.EventID -eq "6008"} | 
    FT -Property Machinename, TimeWritten, EntryType, Source, EventID, Message -AutoSize -wrap }  -computername $computer -ErrorAction Stop  
}
Catch {
    Write-Host $Computer "Error/RDC Problem" -ForegroundColor Red
}

Result: 结果: 在此处输入图片说明

Export-CSV command is not working properly when added at the end. 最后添加时,Export-CSV命令无法正常工作。 It outputs a different set of data. 它输出一组不同的数据。 在此处输入图片说明

Formatting cmdlets like Format-Table don't just change the way the object is displayed, it changes the object itself into something that will display how you want it to. 格式化cmdlet(例如Format-Table不仅会更改对象的显示方式,还会将对象本身更改为可以显示所需内容的内容。 This is part of why it's commonly recommended not to use the formatting cmdlets in scripts or functions. 这就是为什么通常建议不要在脚本或函数中使用格式化cmdlet的原因。

Instead, you should use the Select-Object cmdlet to limit the number of properties passed to Export-Csv . 相反,应该使用Select-Object cmdlet限制传递给Export-Csv的属性的数量。

Invoke-Command -ComputerName $computer -ErrorAction Stop -ScriptBlock {
    Get-EventLog System -After "7/8/2017" -Before "07/28/2017" | 
    Where-Object { 50, 51, 55, 57, 6008 -contains $_.EventID } | 
    Select-Object -Property MachineName, TimeWritten, EntryType, Source, EventID, Message
}

try this 尝试这个

Try {

    Invoke-Command -scriptblock {Get-EventLog System -After "7/8/2017" -Before "07/28/2017" | 
    Where EventID -in ("50", "51", "55", "57", "6008") | 
    select Machinename, TimeWritten, EntryType, Source, EventID, Message }  -computername $computer -ErrorAction Stop |export-csv "c:\temp\result.csv"  
}
Catch {
    Write-Host $Computer "Error/RDC Problem" -ForegroundColor Red
}

or may be simply like this : 或者可能只是这样:

Try 
{
    Get-EventLog System -After "7/8/2017" -Before "07/28/2017" -ComputerName $computer | 
    Where EventID -in ("50", "51", "55", "57", "6008") | 
    select Machinename, TimeWritten, EntryType, Source, EventID, Message |export-csv "c:\temp\result.csv" -NoType
}
Catch 
{
    Write-Host $Computer "Error/RDC Problem" -ForegroundColor Red
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM