The script below successfully obtains the manufacturer, model, serial number, and operating system from each computer I provide in hostnames.txt
. However, it is slow because it must connect to WMI on each computer three times.
$OS = Get-WmiObject Win32_OperatingSystem -ComputerName $Computer
$CS = Get-WmiObject Win32_ComputerSystem -ComputerName $Computer
$BIOS = Get-WmiObject Win32_Bios -ComputerName $Computer
Using PowerShell, how can I connect to the remote-computer's WMI once and execute the three queries using the same connection?
$Array = @() ## Create Array to hold the Data
$Computers = Get-Content -Path .\hostnames.txt
foreach ($Computer in $Computers)
{
$Result = "" | Select HostPS,Mfg,Model,Serial,OS
$Result.HostPS = $Computer
$ErrorActionPreference = "SilentlyContinue" ## Don't output errors for offline computers
$OS = Get-WmiObject Win32_OperatingSystem -ComputerName $Computer
$CS = Get-WmiObject Win32_ComputerSystem -ComputerName $Computer
$BIOS = Get-WmiObject Win32_Bios -ComputerName $Computer
$ErrorActionPreference = "Continue"
$Result.Mfg = $CS.Manufacturer
$Result.Model = $CS.Model
$Result.Serial = $BIOS.SerialNumber
$Result.OS = $OS.Caption
$Array += $Result ## Add the data to the array
}
$Array | Export-Csv file.csv -NoTypeInformation
You can use CIM (which has a session option), more on CIM vs WMI ("WMI is the Microsoft implementation of CIM for the Windows platform")
$CIMSession = New-CimSession -ComputerName $RemoteComputer
Get-CimInstance win32_OperatingSystem -CimSession $CIMSession -Property Caption
Get-CimInstance Win32_ComputerSystem -CimSession $CIMSession -Property Manufacturer,Model
Get-CimInstance Win32_Bios -CimSession $CIMSession -Property SerialNumber