【问题标题】:How to Properly Export to CSV Using Powershell如何使用 Powershell 正确导出为 CSV
【发布时间】:2018-01-05 13:52:24
【问题描述】:

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

结果:

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

【问题讨论】:

  • “无法正常工作”是什么意思?我希望 Format-Csv 输出对象的所有属性,而 Format-Table 通常会显示适合屏幕的子集。 Format-Csv 将采用一种不受屏幕宽度限制的格式,因此它可以(并且应该)包含所有内容。

标签: windows powershell csv server


【解决方案1】:

格式化像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
}

【讨论】:

  • 成功了!谢谢你。使脚本更短的加分点,我不知道你可以像这样使用 Where-Object :)
【解决方案2】:

试试这个

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
}

【讨论】:

  • 我没有考虑将 Export-CSV 命令带入 try 块中。这次真是万分感谢! +1
猜你喜欢
  • 2019-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-25
  • 2016-02-23
  • 2013-07-15
  • 1970-01-01
相关资源
最近更新 更多