powershell - 在 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
}
}
解决方案
尝试这个:
$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
因此您只会在控制台中看到无法访问的机器,它们根本不会出现在您的输出文件中。
推荐阅读
- avro - Avro 工具失败预期启动联合。收到 VALUE_STRING
- python - 在同一行中删除特定单词及其后面的所有字符,并使用python从文本文件中删除下一行
- java - Java中是否有等效于T-SQL的 HASHBYTES('SHA1', VARBINARY(MAX)) ?
- mysql - MySQL查询 - 派生表与左连接在哪里
- manatee.json - 验证失败但缺少错误消息
- oracle - Oracle dbms_job 在 5 秒内执行具有不同延迟的作业。如何让它以指定的时间间隔无延迟地运行作业?
- spring-boot - 如何在 Flyway 迁移运行的插入语句中转义 Freemarker 模板?
- laravel - 如何将 Laravel 中的资产{{}} 设置为项目外的文件夹
- python - 使用 PostgresSQL 连接时出现 Flask 和 SQLAlchemy 错误
- c# - C#中的JSON格式问题