【问题标题】:Assistance w/ Export-Csv in PowerShell [duplicate]在 PowerShell 中使用 Export-Csv 提供帮助 [重复]
【发布时间】:2019-03-13 13:58:26
【问题描述】:

我正在使用下面的脚本来引用一个包含计算机名称列表的 txt 文件,以了解每台计算机的操作系统和操作系统版本。我可以让它在 PowerShell 中显示,但我将它导出到 CSV 文件的所有尝试都失败了。我在这里使用了其他推荐使用 Write-output 和 Export-csv 的文章,但我得到的只是错误(取决于位置),或者我得到一个显示长度和字符数的 CSV 文件。我不介意投入工作,但我觉得我不明白应该在哪里放置管道并将结果保存到 CSV 文件中。

$Computers = Import-Csv -Path "c:\Scripts\computers.txt" -Header "Name"
foreach ($Computer in $Computers) {
    try {
        Get-ADComputer -Identity $Computer.Name -Properties Name, operatingSystem, operatingSystemVersion |
            Select Name, operatingSystem, operatingSystemVersion
    } catch {
        $Computer.Name + " not in AD" |
            Export-Csv -Path .\computers-results.csv -NoTypeInformation
    }
}

【问题讨论】:

    标签: powershell export-csv


    【解决方案1】:

    试试这个:

    $Computers = Import-CSV -Path "c:\Scripts\computers.txt" -Header "Name"
    
    $Result = ForEach ($Computer In $Computers)
    {
      Try
      {
          Get-ADComputer -Identity $Computer.Name -Properties Name, operatingSystem, operatingSystemVersion | Select Name, operatingSystem, operatingSystemVersion
      }
      Catch
      {
          Write-Warning $Computer.Name + " not in AD"
      }
    }
    
    $Result | Export-CSV .\computers-results.csv -NoTypeInformation
    

    这是通过将ForEach 循环的结果整理到$Result 变量中来实现的,这是因为Get-ADComputer 行的结果正在返回到管道中。

    循环完成后,$Result 是一组对象,我们可以将其发送到 Export-CSV 以转换为 CSV 文件。

    请注意,我还将Catch 部分更改为使用Write-Warning,因此您只会在控制台中看到无法访问的机器,它们根本不会出现在您的输出文件中。

    【讨论】:

    • 马克,就是这样。感谢您花时间分解解释。我肯定会将您所说的所有内容添加到我的笔记中,以便我可以更好地进行尽职调查。这是简化的响应,完全有道理。再次感谢。
    • 不客气!
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 2011-10-01
    • 2017-12-15
    • 2019-07-18
    • 1970-01-01
    相关资源
    最近更新 更多