List Services Running on Remote Servers
As I wrote earlier, Lake Quincy Media’s AdSignia ad platform is utilizing services and a message-based architecture to decouple the system from the database and improve performance and reliability of the servers. It’s proven useful to quickly work with the services across multiple nodes in the web cluster, and PowerShell is the obvious choice for automating some of these tasks. When building up a collection of PowerShell scripts to support an application, I recommend that you store them in source control with the application itself. It’s also worth following the Don’t Repeat Yourself principle, which you can do by using PowerShell functions to return results from one PowerShell script file to another.
In my case, since I have a number of servers involved in the application, it makes sense to store the list of server names in their own file. I only need the names, so returning a simple array of strings does the trick:
ListServers.ps1
# List Production Servers
function ListServers
{
return "server1","server2","server3","yetanotherserver"
}
Now the next step is to get a list of services running on each of these machines. I found a post that showed how to list remote services using PowerShell, which led me to this code:
ListServices.ps1
# List DataPump Services and Status on Production Servers
if (-not ([appdomain]::CurrentDomain.getassemblies() |? {$_.ManifestModule -like "system.serviceprocess"})) {[void][System.Reflection.Assembly]::LoadWithPartialName('system.serviceprocess')}
. ./ListServers.ps1; $servers=ListServers
function ListServices
{
$all = $null
foreach($s in $servers)
{
if ($all -eq $null) { $all = [System.ServiceProcess.ServiceController]::GetServices($s) }
else
{
$all = $all + [System.ServiceProcess.ServiceController]::GetServices($s) | ? {$_.DisplayName -like "AdSignia*"}
}
}
return $all
}
ListServices | Format-Table -AutoSize -Property MachineName,DisplayName,Status
You can run this from the command line directly by calling .\ListServices.ps1, or you can call the ListServices function from another script, which proves useful when you want to Start or Stop a Remote Service using a Powershell script.
Calling it directly results in something like this:
MachineName DisplayName Status
----------- ----------- ------
server1 AdSignia.Service1 Running
server2 AdSignia.Service1 Running
server3 AdSignia.Service1 Running
yetanotherserver AdSignia.Service2 Running
So there you have it – how to list the services running on a remote server using PowerShell. Note that if you want to list *all* of the services, simply remote this bit from the foreach loop:
| ? {$_.DisplayName -like "AdSignia*"}