How to get all Windows service names starting with a common word?

Command LineWindows ServicesCommandCommand Prompt

Command Line Problem Overview


There are some windows services hosted whose display name starts with a common name (here NATION). For example:

  • NATION-CITY
  • NATION-STATE
  • NATION-Village

Is there some command to get all the services like 'NATION-'. Finally I need to stop, start and restart such services using the command promt.

Command Line Solutions


Solution 1 - Command Line

sc queryex type= service state= all | find /i "NATION"
  • use /i for case insensitive search
  • the white space after type= is deliberate and required

Solution 2 - Command Line

Using PowerShell, you can use the following

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Select name

This will show a list off all services which displayname starts with "NATION-".

You can also directly stop or start the services;

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Stop-Service
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Start-Service

or simply

Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Restart-Service

Solution 3 - Command Line

Another way of doing it, if you don't like the old PowerShell version.

# Create an array of all services running
$GetService = get-service
    
# Iterate throw each service on a host
foreach ($Service in $GetService)
{
    # Get all services starting with "MHS"
    if ($Service.DisplayName.StartsWith("MHS"))
    {
        # Show status of each service
        Write-Host ($Service.DisplayName, $Service.Status, $Service.StartType) -Separator "`t`t`t`t`t|`t"
        
        # Check if a service is service is RUNNING.  
        # Restart all "Automatic" services that currently stopped
		if ($Service.StartType -eq 'Automatic' -and $Service.status -eq 'Stopped' )
        {
            Restart-Service -Name $Service.DisplayName
            Write-Host $Service.DisplayName "|`thas been restarted!"   
		}
    }
}

Solution 4 - Command Line

Save it as a .ps1 file and then execute

powershell -file "path\to your\start stop nation service command file.ps1"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChandan KumarView Question on Stackoverflow
Solution 1 - Command LineChandan KumarView Answer on Stackoverflow
Solution 2 - Command LinewimhView Answer on Stackoverflow
Solution 3 - Command LineSerge VoloshenkoView Answer on Stackoverflow
Solution 4 - Command LineblairstarkView Answer on Stackoverflow