如何使用Powershell正确导出为CSV

时间:2017-07-29 16:10:12

标签: windows powershell csv server

我是否知道如何将此脚本正确导出为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
}

结果:  enter image description here

最后添加时,Export-CSV命令无法正常工作。它输出一组不同的数据。 enter image description here

2 个答案:

答案 0 :(得分:2)

格式化像Format-Table这样的cmdlet不会改变对象的显示方式,它会将对象本身更改为显示您想要的方式。这是为什么通常建议不要在脚本或函数中使用格式化cmdlet的原因之一。

相反,您应该使用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
}

答案 1 :(得分:1)

试试这个

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
}

或者可能只是这样:

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
}