首页 > 解决方案 > 在 PowerShell 中使用 Export-Csv 提供帮助

问题描述

我正在使用下面的脚本来引用一个包含计算机名称列表的 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
    }
}

标签: powershellexport-csv

解决方案


尝试这个:

$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因此您只会在控制台中看到无法访问的机器,它们根本不会出现在您的输出文件中。


推荐阅读