How do I combine the two results of the array?
$computers=Get-content "<network path to text file>\slist.txt"
foreach($computer in $computers) {
$tc=Test-Connection -ComputerName $computer -Count 1 -Quiet
if ($tc -eq $false) {
$report=[PSCustomObject]@{
'Computer Name' = $computer
'Computer Status' = $tc
'OS' = $null
'Manufacturer' = $null
'Model' = $null
'Cores' = $null
}
}
else {
$obj=systeminfo /s $computer /fo csv | findstr /c:'OS Name' /c:'System Manufacturer' /c:'Model'
$proc=Get-WmiObject -class Win32_Processor -ComputerName BBCSRV | select @{LABEL='NumberofCores';EXPRESSION={$_.numberofcores}}
$report=[PSCustomObject]@{
'Computer Name' = $computer
'Computer Status' = $tc
'OS' = $obj.OSName
'Manufacturer' = $obj.SystemManufacturer
'Model' = $obj.Model
'Cores' = $proc.NumberofCores
}
}
}
$report | Export-Csv "<path to save outputfile>\VirPhys.csv" -Append -NoTypeInformation
Answers (1)
You don't need separate objects for $report, PSCustomObject is a collection already, so it appends dynamically. I refactored your script to use the more modern Cim Instance classes and a few other tweaks, but thiis will return the same as yours.
Computer Name : localhost
Computer Status : True
OS : Microsoft Windows 10 Enterprise
Manufacturer : Dell Inc.
Model : XPS 13 9370
Cores : 4
Computer Name : localhost
Computer Status : True
OS : Microsoft Windows 10 Enterprise
Manufacturer : Dell Inc.
Model : XPS 13 9370
Cores : 4
Computer Name : computerA
Computer Status : False
OS :
Manufacturer :
Model :
Cores :
Computer Name : computerB
Computer Status : False
OS :
Manufacturer :
Model :
Cores :
Comments:
-
I'm still learning how to use powershell, so please bear with me, but....is there a way when using a function to put the text file of servers in the code instead of running another line to input them? How do I output this to a csv? - milo2 5 years ago
-
Sure, you just call your function like this, then pipe it to a csv.
myServers.txt has one hostname per line and no whitespace.
Get-ComputerInformation -ComputerName (Get-Content -Path 'C:\temp\myServers.txt') |
Export-Csv -Path 'C:\temp\myOutput.csv' -NoTypeInformation -Append
Alternately, you can define the servers in the code itself using a string array.
$myServers=@(
'server01'
'server02'
)
...
Get-ComputerInformation -ComputerName $myServers |
Export-Csv -Path 'C:\temp\myOutput.csv' -NoTypeInformation -Append
NOTE: If you have machines with more than one socket, you will need to convert your $CPU.NumberofCores prior to export, as CSV does not know how to handle PS objects. [string]$CPU.NumberOfCores should work in that case. - isudothings 5 years ago