【问题标题】:Export-CSV - (Powershell)导出-CSV - (Powershell)
【发布时间】:2016-10-23 09:26:39
【问题描述】:

所以我有底部的脚本块:

Import-csv C:\file_location.csv | foreach-object {
Get-WmiObject -computername $_.computername -class Win32_ComputerSystem | select username} | `
Select-Object computername, username | Export-CSV C:\file_location.csv -notypeinformation

导出的 csv 显示计算机名称标头,但没有实际计算机,用户名标头很好。我错过了什么,从哪里漏掉了什么?

谢谢!

【问题讨论】:

标签: windows csv powershell automation


【解决方案1】:

select(它是Select-Object 的别名)返回一个您指定属性的对象。因此,当您执行第一个 select username 时,您会得到一个只有用户名的对象;所有其他属性都被丢弃,所以当第二个Select-Object 调用运行时,没有computername 可以返回。

第一个select 在那里似乎完全没有必要;只需将其取出,我认为一切都会按预期进行。

编辑:我现在看到 computername 不是返回的 WMI 对象的属性;它来自 CSV。您的 ForEach-Object 仅返回 WMI 对象,因此 CSV 行对象被丢弃。

您需要做的是将 CSV 中的 computername 添加到 WMI 对象,您可以使用 Select-Object(带有计算列)或 Add-Member

Import-csv C:\file_location.csv | 
    ForEach-Object {
        Get-WmiObject -computername $_.computername -class Win32_ComputerSystem |
        Select-Object @{Name='ComputerName';Expression={$_.computername}},username
    } | 
    Export-CSV C:\file_location.csv -notypeinformation

或者:

Import-csv C:\file_location.csv | 
    ForEach-Object {
        Get-WmiObject -computername $_.computername -class Win32_ComputerSystem |
        Add-Member -NotePropertyName computername -NotePropertyValue $_.computername -Force -PassThru
    } | 
    Select-Object computername, username
    Export-CSV C:\file_location.csv -notypeinformation

【讨论】:

  • 感谢您的回复!这两种方法我都试过了,还是一样。选择对象方法提供相同的结果,ComputerName 标题列中没有数据。 Add-Member 导出一个空白 CSV。
  • 从头开始!!我发现了我的错误。 Add-Member 工作得很好。谢谢@briantist!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-11
  • 2014-12-04
  • 2018-06-22
  • 2017-07-03
  • 2021-02-17
  • 1970-01-01
相关资源
最近更新 更多