We help IT Professionals succeed at work.

Powershell arrays?


I wonder if there is a better way to get all model types of active computers.
Today i run the following

Get-ADComputer -Filter {name -like "STO*"} | ft Name

foreach($c in $com){if(Test-Connection -Count 1 -ComputerName $c -Quiet){Test-Connection -Count 1 -ComputerName $c}}

Get-WmiObject -computer $active win32_computersystem| fl name,model

Open in new window

However it feels like I'm wasting poweshells potential here.
I also have to manually edit the output from the first and command
All our computers in 1 area start with STO in the name.

I then ping all of them to get the active ones then i ask for the name and model.
Can this be done in a better more automatic way way?

i also wonder if the first output could be put in to an array
Watch Question

Most Valuable Expert 2019
Most Valuable Expert 2018
That can be done in one line: get the computers, ping each one, get the WMI information if ping is successful, otherwise create a custom object, and finally format the list returned:
Get-ADComputer -Filter {name -like "STO*"} | ForEach {If (Test-Connection -Count 1 -ComputerName $_.DNSHostName -Quiet) {Get-WmiObject -Class Win32_ComputerSystem -ComputerName $_.DNSHostName} Else {$_ | Select-Object -Property Name, @{Name="Model"; Expression={"<offline>"}}}} | Format-List Name, Model

Open in new window

Edit: added information about offline computers.


Just what i was looking for, Thanks!

Accepted solution. As a follow up on the offline handling. Sometimes a computers RPC service is not responding, this generates an error:
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

Is it possible to add error handling in this one-liner?!
Most Valuable Expert 2019
Most Valuable Expert 2018

Well, technically it's still a one-liner, but it's starting to get out of hand:
Get-ADComputer -Filter {Name -like "STO*"} | ForEach {$Name = $_.Name; Try {If (Test-Connection -Count 1 -ComputerName $_.DNSHostName -Quiet) {Get-WmiObject -Class Win32_ComputerSystem -ComputerName $_.DNSHostName -ErrorAction Stop} Else {Throw "Offline"}} Catch {$_ | Select-Object -Property @{N="Name"; E={$Name}}, @{N="Model"; E={"<$($_.Exception.Message)>"}}}} | Format-List Name, Model

Open in new window

So here's the expanded version:
Get-ADComputer -Filter {Name -like "STO*"} | ForEach {
	$Name = $_.Name
	Try {
		If (Test-Connection -Count 1 -ComputerName $_.DNSHostName -Quiet) {
			Get-WmiObject -Class Win32_ComputerSystem -ComputerName $_.DNSHostName -ErrorAction Stop
		} Else {
			Throw "Offline"
	} Catch {
		$_ | Select-Object -Property @{Name="Name"; Expression={$Name}}, @{Name="Model"; Expression={"<$($_.Exception.Message)>"}}
} | Format-List Name, Model

Open in new window


Thanks for your time to reply, you helped me tremendously.

yes you are right, it does get very much out of hand here. I better get in to building scripts for this, i think.