We help IT Professionals succeed at work.

Checking the status of multiple windows services using powershell.

nav2567
nav2567 asked
on
Hello,

I am working on a script to read list of computer names and inventory the status of two windows services on each computer.  Does anyone know what to put after the Get-WMIOBJECT command?  Thanks.

$compArray = get-content C:\Servers.txt

foreach($strComputer in $compArray)
{
Get-WMIObject Win32_Service -ComputerName $strComputer | ....
}
Comment
Watch Question

Most Valuable Expert 2019
Most Valuable Expert 2018

Commented:
You should filter as early as possible, that is, in the WMI query.
This will query two services and export selected properties of the results to a csv:
$compArray = get-content C:\Servers.txt
$compArray | ForEach-Object {
	Get-WMIObject Win32_Service -Filter "(Name='RemoteAccess') or (Name='RemoteRegistry')" -ComputerName $_ |
		Select-Object -Property PSComputerName, Name, DisplayName, State, StartMode, StartName
} | Export-Csv -NoTypeInformation -Path C:\Temp\services.csv

Open in new window

Author

Commented:
Thanks,  oBdA,

I need to see those computers which do not have the services running.

Your script only lists status of computers which have the services running.
Most Valuable Expert 2019
Most Valuable Expert 2018
Commented:
Based on your comment, I can only assume that you mean "computers which do not have the services installed", as the script definitely shows whether the services are running or not.
PS C:\> gwmi Win32_Service -Filter "(Name='WSearch') or (Name='RemoteRegistry')" | select Name, Display*, State | ft -au

Name           DisplayName     State
----           -----------     -----
RemoteRegistry Remote Registry Stopped
WSearch        Windows Search  Running

Open in new window


Anyway, this will show as well which of the services are installed:
$compArray = Get-Content -Path C:\Servers.txt
$services = @(
	'RemoteAccess'
	'RemoteRegistry'
)

$filter = ($services | ForEach-Object {"(Name='$($_)')"}) -join ' or '
$services = $services | Sort-Object
$compArray | ForEach-Object {
	$computer = $_
	$result = [ordered]@{}
	$services | ForEach-Object {
		$result[$_] = [PSCustomObject]@{
			'PSComputerName' = $computer
			'Name' = $_
			'Installed' = $false
		}
	}
	Get-WMIObject Win32_Service -Filter $filter -ComputerName $computer |
		Select-Object -Property *, @{n='Installed'; e={$true}} |
		ForEach-Object {$result[$_.Name] = $_}
	$result.Values | Select-Object -Property PSComputerName, Name, Installed, DisplayName, State, StartMode, StartName
} | Export-Csv -NoTypeInformation -Path C:\Temp\services.csv

Open in new window

Author

Commented:
It works.  Thank you!