
close
close
You might be familiar with the concept about trying to prove a negative, which is to say, it’s very hard. For an IT pro, this might come up more often than you think. That’s the question I found in an online PowerShell forum asked, “How can I show if something exists or not?” There were two scenarios that he was working with, so let’s use them as learning opportunities.
First, given a list of servers, he want to check for the existence of a service and indicate via a Boolean value if the service exists or not using PowerShell. For my demonstration, I’m going to use Get-CimInstance instead of Get-Service, because I’m trying to get in the habit of not using legacy protocols.
I also have a variable that contains 11 server names that I know are running and that I can access. I’ll forego error handling to keep this as simple as possible. So let’s say I want to report on which servers have the Spooler service installed. It is simple enough to list those that do.
get-ciminstance win32_service -filter "name = 'spooler'" -ComputerName $servers | Select Name,Status,PSComputername
Listing servers with the spooler service (Image Credit: Jeff Hicks)
advertisment
$servers | foreach { $obj = [pscustomobject]@{ Computername = $_.ToUpper() Service = "Spooler" Verified = "Unknown" } $s = get-ciminstance win32_service -filter "name = 'spooler'" -ComputerName $_ if ($s) { $obj.Verified = $True } else { $obj.verified = $False } #write the object to the pipeline $obj }
In the ForEach loop I’m creating a custom object with three properties. Next, I attempt to get the service. If the command succeeds, $s will have a value, which means I can set Verified to True. Otherwise, I set it to False.
Here are my results:
True/False results (Image Credit: Jeff Hicks)
A missing service exception (Image Credit: Jeff Hicks)
advertisment
$servers | foreach { $computername = $_ #Write-Host "Processing $computername" -ForegroundColor green Try { $s = Get-Service -Name spooler -ComputerName $computername -ErrorAction Stop $Verified = $True } Catch { $Verified = $False } Finally { [pscustomobject]@{ Computername = $Computername Service = "Spooler" Verified = $Verified } } }
Using Try/Catch/Finally results (Image Credit: Jeff Hicks)
Invoke-Command -scriptblock { Try { $s = Get-Service -Name spooler -ErrorAction Stop $Verified = $True } Catch { $Verified = $False } Finally { [pscustomobject]@{ Service = "Spooler" Verified = $Verified } } } -computer $servers | Select PSComputername,Service,Verified | sort Verified
Notice that I simplified the code inside the scriptblock to skip getting the computername. I get that from Invoke-Command.
Sorted remote results (Image Credit: Jeff Hicks)
advertisment
More in PowerShell
Microsoft’s New PowerShell Crescendo Tool Facilitates Native Command-Line Wraps
Mar 21, 2022 | Rabia Noureen
Most popular on petri