我正在编写一个脚本,将所有计算机名称和型号输出到 excel 文件。代码在没有 Export-Csv 管道的情况下也能工作,但我不知道如何创建 excel 文件。如果我去掉循环并只使用一台带有 Export-Csv 的计算机,它也能正常工作。
#Query AD
$Computers = Get-ADComputer -Filter * -searchbase "DC=domain,DC=org"
#loop
foreach ($computer in $Computers) {
$comp=$computer.Name
Get-WmiObject -Class Win32_ComputerSystem -ComputerName $comp | Where-Object {$_.model -like "*G2*"} | Select-Object Name, Model | Export-Csv "C:\User\xxxxxx\Desktop\8200s.csv" -NoTypeInformation -Encoding UTF8 -Append
}
答案1
我建议您将其移出Export-CVS
循环并使用,Foreach-Object
这样您就可以使用管道。
# Query AD for computers
Get-ADComputer -Filter * -searchbase "DC=domain,DC=org" |
ForEach-Object {
$comp=$_.Name
# return name,model for all G2 computers
Get-WmiObject -Class Win32_ComputerSystem -ComputerName $comp |
Where-Object {$_.model -like "*G2*"} |
Select-Object Name, Model
} | Export-Csv "C:\User\xxxxxx\Desktop\8200s.csv" -NoTypeInformation -Encoding UTF8
答案2
听取了您的一些建议并经过进一步思考,我终于解决了这个问题。我们创建了一个数组和一个对象,将信息写入数组,然后写入文件。我能够导出数据,然后不得不付出更多努力来找出所有电脑故障导致脚本运行非常缓慢的错误。下面是我们使用的。
查询广告
$ErrorActionPreference="Continue"
$Computers = Get-ADComputer -Filter * -searchbase "OU=TechDepartment,OU=Workstations,DC=domain,DC=org"
$OurArray=@()
$firstObject = New-Object PSObject
Add-Member -InputObject $firstObject -MemberType NoteProperty -Name Name -Value ""
Add-Member -InputObject $firstObject -MemberType NoteProperty -Name Model -Value ""
#loop
foreach ($computer in $Computers) {
$comp=$computer.Name
If(Test-Connection $comp -count 1 -Quiet)
{
#Successful Ping
Write-Host "$comp"
try{
$firstObject = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $comp -ErrorAction Stop | Select-Object Name, Model | Where-Object {$_.model -like "*8200*"}
$OurArray += $firstObject
}catch { "$comp RPC is Down"}
}
Else
{Write-Host "$comp is offline"}
}
$OurArray | Export-Csv 8200s.csv -NoTypeInformation -Encoding UTF8