2017-07-29 66 views
0

我可以知道如何將此腳本正確導出爲CSV?如何使用Powershell正確導出爲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

出口-CSV命令不能正常工作。它輸出一組不同的數據。 enter image description here

+0

你說的 「不正常」 呢?我希望Format-Csv可以輸出對象的所有屬性,而Format-Table通常會顯示一個適合屏幕的子集。 Format-Csv將採用不受屏幕寬度限制的格式,因此它可以(也應該)包含所有內容。 –

回答

2

Format-Table這樣的格式化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

它工作!謝謝。加上使腳本更短的點,我不知道你可以使用Where-Object那樣:) – KentMarionVG

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 
} 
+0

我沒有想到在try塊中引入Export-CSV命令。這次真是萬分感謝! +1 – KentMarionVG