Find all cmdlets that working with windows services

You can manage Windows services not only from the services.msc snap-in or sc.exe command line tool, but also using PowerShell. In this article we’ll consider different scenarios of managing Windows…

You can manage Windows services not only from the services.msc snap-in or sc.exe command line tool, but also using PowerShell. In this article we’ll consider different scenarios of managing Windows services with PowerShell.

Contents:

  • PowerShell Cmdlets Used to Manage Windows Services
  • How to Check Windows Service Status with Get-Service?
  • How to Stop, Start, or Restart Service with PowerShell?
  • Using Set-Service to Change Service Settings
  • How to Create or Delete a Windows Service via PowerShell?
  • Change the User Account that Runs the Windows Service

PowerShell Cmdlets Used to Manage Windows Services

There are eight basic Service cmdlets to view the state of Windows services and manage them. To get the full list of service management cmdlets, run this command:

Get-Help *-Service

basic powershell cmdlets to manage windows services

  • Get-Service — allows to get the services on a local or remote computer both in running or stopped state;
  • New-Service – creates a service. The cmdlet creates a new entry for a Windows service in the registry and in the service database;
  • Restart-Service – restarts a service. The cmdlet sends the restart message through the Windows Service Controller;
  • Resume-Service – resumes a service. The cmdlet sends a resume message to Windows Service Manager;
  • Set-Service — changes the settings of a local or remote service, including its state, description, displayed name or startup mode. You can also use this cmdlet to start, stop or suspend a service;
  • Start-Service – starts a service;
  • Stop-Service – stops a service (the cmdlet sends a stopping message to Windows Service Manager);
  • Suspend-Service – suspends a service. A suspended service is still running, but it does not do anything till it is resumed using( for example, with the Resume-Service cmdlet).

You can get a detailed description and examples of using a particular cmdlet with Get-Help:

Get-Help Start-Service

Get-Help

How to Check Windows Service Status with Get-Service?

You can get the list of services and their state (Running/Stopped) on a local or remote computer using the Get-Service cmdlet. The –Name parameter allows to select services by name. The service name can be specified using the wildcard character *.

Check Windows Service Status with Get-Service

If you do not know the exact service name, you can find it by its displayed name using the –DisplayName parameter. You can use the list of values and wildcards.

powershell get services

Use the Get-Service cmdlet with the -ComputerName parameter to get the service status on a remote computer. You can query the service status on multiple remote computers at once by specifying their names separated by commas. For example, the command shown below gets the Spooler service status on the remote computers ny-prnt1 and ny-prnt2.

Get-Service spooler –ComputerName ny-prnt1,ny-prnt2

Status Name DisplayName
------ ---- -----------
Running spooler Print Spooler
Stopped spooler Print Spooler

To display all the properties of a service, use the Select-Object cmdlet:

Get-Service spooler | Select-Object *

Get-Service properties

The Select-Object cmdlet allows to get specific properties of a service. For example, you want to view the name, status and available options of the Spooler service:

Get-Service Spooler | Select DisplayName,Status,ServiceName,Can*

Get-Service state

The Get-Service cmdlet has two parameters that allow you to view the service dependencies:

  • -DependentServices allows to display the services dependent on the given service
  • -RequiredServices displays the services the given service depends on

The following command displays the services required to start the Spooler service:

Get-Service –Name Spooler -RequiredServices

Get-Service RequiredServices

The following command shows the services that depend on Spooler:

Get-Service –Name Spooler -DependentServices

Get-Service DependentServices

If you want to find the services with the specific state or parameters, use the Where-Object cmdlet. For example, let’s get the list of running services:

Get-Service | Where-Object {$_.status -eq 'running'}

Get-Service: list of running services

To display the services with the manual startup type, run this command:

Get-Service | Where-Object {$_.starttype -eq 'Manual'}

get service with the manual startup type

Use the following PowerShell script to check if a specific Windows service exists on a current computer:

if (Get-Service "ServiceTest" -ErrorAction SilentlyContinue)
{
Write-host "ServiceTest exists"
}

How to Stop, Start, or Restart Service with PowerShell?

You can stop a service using the Stop-Service cmdlet. To stop the Spooler, run the command:

Stop-Service -Name spooler

The Stop-Service cmdlet does not display anything after execution. To see the result, use the -PassThru parameter.

Stop-Service PassThru

Please note that not every service can be stopped. If there are any dependent services, you will see an error:

Cannot stop service because it has dependent services. It can only be stopped if force flag set.

Cannot stop service because it has dependent services. It can only be stopped if force flag set.

To force a service to stop, use the –Force parameter. You should remember that all dependent services will also stop:

Stop-Service samss –Force -Passthru

The following command will stop the specified services (bits, spooler) if they are in “Running” state:

get-service bits,spooler | where {$_.status -eq 'running'} | stop-service –passthru

stop services in the running state

Sometimes services hang up in the “Stopping” state and have to be killed forcibly.

The Start-Service cmdlet starts a stopped service:

Start-Service -Name spooler -PassThru

Start-Service

A service won’t start, if any of its dependent services is stopped. To find and start them use the following PowerShell one-liner:

get-service samss | Foreach { start-service $_.name -passthru; start-service $_.DependentServices -passthru}

powershell start a service with all dependences

The Suspend-Servce cmdlet can pause services if they support this state. To learn if a service can be suspended, use the Get-Service cmdlet with the CanPauseAndContinue property.

Get-Service samss | Format-List name, canpauseandcontinue

Get-Service canpauseandcontinue

To display the list of all services that may be paused, run this command:

Get-Service | Where-Object {$_.canpauseandcontinue -eq "True"}

get service with the canpauseandcontinue option

Let’s suspend SQLBrowser service:

Suspend-Service -Name SQLBrowser

Suspend-Service

To resume a suspended service, use the Resume-Service cmdlet:

Resume-Service -Name SQLBrowser

Resume-Service

The following command will resume all suspended services:

get-service | where-object {$_.Status -eq "Paused"} | resume-service

The Restart-Service cmdlet will restart a service:

Restart-Service -Name spooler

Restart-Service

This command starts all stopped network services on a computer:

get-service net* | where-object {$_.Status -eq "Stopped"} | restart-service

These commands do not have the –ComputerName parameter, but you can run them on a remote computer using the Invoke-Command cmdlet or a pipe.

For example, to restart a print spooler on the remote computer ny-prnt1, run the command:
Get-Service Spooler -ComputerName ny-prnt1 | Start-Service

Using Set-Service to Change Service Settings

The Set-Service cmdlet allows you to change any parameters or settings of a service on a local or remote computer. Since the state of a service is a property, you can use this cmdlet to start, stop or suspend a service. Set-Service has the -StartupType parameter that allows to change the startup type of a service.

Let’s change the Spooler startup type to automatic:

Set-Service spooler –startuptype automatic –passthru

change the startup type of the Print Spooler to Automatic

You can set the manual startup type:

Set-Service spooler –startuptype manual –passthru

set the manual startup type Set-Service

How to Create or Delete a Windows Service via PowerShell?

New-Service – is a cmdlet to create a new service in Windows. Specify the name and the executable file for the new service (you can even run a PowerShell script as a Windows service).

Let’s create a new service with the name TestSvc:

new-service -name TestSvc -binaryPathName "C:WINDOWSSystem32svchost.exe -k netsvcs"

new-service create service with powershell

Get the information about the startup type and description of the service using the Get-WmiObject cmdlet.

get-wmiobject win32_service -filter "name='testservice'"

get-wmiobject win32_service

You can change the settings of the new service using the following command:

Set-Service -Name TestSvc -Description ‘My Service’ -StartupType Manual

change service startup type to manual

To delete a service, run this command:

(Get-WmiObject win32_service -Filter ″name=′TestSvc′″).delete()

Change the User Account that Runs the Windows Service

You can use PowerShell in order to change user account used to start a service. Get the name of the account used to start TestSvc:

get-wmiobject win32_service -filter "name='TestSvc'" | Select name,startname

get the user account to run the service

To change the username and password for a Windows Service, run the following commands:

$svc = get-wmiobject win32_service -filter "name='TestSvc'"
$svc.GetMethodParameters("change")

The list of the Change() method parameters is displayed. Count where the StartName and StartPassword parameters are: they located on the 20th and 21st places respectively.

change runas user account of a windows service

$svc | Invoke-WmiMethod -Name Change –ArgumentList @ ($null,$null,$null,$null,$null,$null,$null, $null,$null,$null,$null,$null,$null,$null,$null,$null, $null,$null,$null,"Administrator","!123Pa$$w0rd")

Or you can enter the name of a gMSA account (the account password is not specified in this case).

As you can see, PowerShell makes it easy to manage Windows services. You can create, stop, start or resume services, and change their properties. Most cmdlets allow to manage services on remote computers.

Windows services is one of those topics nearly every Windows sysadmin has to work with. To manage Windows services you could fire up the services.msc MMC snap-in for one-off tasks but what if you need to build some kind of automation with PowerShell? Learn how to use PowerShell to get a service, use PowerShell start service cmdlet, use PowerShell to stop a service, and use PowerShell to restart a service in this tutorial!

It’s time to learn how to manage services with PowerShell.

In this tutorial, you’re going to learn all about the *-Service PowerShell cmdlets, how to use them and also build your own script to manage services on many computers at once.

Prerequisites

This article is going to be a walkthrough for you to hands-on learning about how PowerShell can read and manipulate Windows services. If you’d like to follow along, please be sure you have the following prerequisites in place before starting this article.

  1. At least one Windows computer. It’ll help if you have more than one to learn how to manage multiple computers at once.
  2. PowerShell 7 – Even though most of the concepts are the same as Windows PowerShell, you’re going to stick with the most recent version of PowerShell
  3. PowerShell Remoting enabled on any remote computer you’d like to query.

Using PowerShell to List Services with Get-Service

One of the most basic tasks you can accomplish with PowerShell and Windows services is simply enumerating what services exist on a local computer. For example, open up PowerShell and run Get-Service and observe the output.

Notice in the below screenshot running Get-Service by itself will list all services on the local computer and the Status, the Name and DisplayName of each service.

Using Get-Service to find Windows services
Using Get-Service to find Windows services

Like many other cmdlets, PowerShell though doesn’t return all of the properties for each service. If, for example, you’d like to see a service’s required services or perhaps the service description, you can find these properties by piping the output to Select-Object using * to represent all properties as shown in the following screenshot.

Inspecting all properties for service objects
Inspecting all properties for service objects

Finding Remote Services

Maybe you’re on a network and need to enumerate services across one or more remote Windows computers. In the Windows PowerShell days, this could have been done by using the ComputerName parameter but unfortunately that parameter doesn’t exist anymore.

With PowerShell Core though, finding remote services is still possible using two different methods; PowerShell Remoting CIM/WMI.

Get-Service and PowerShell Remoting

One way to inspect Windows services remotely is by using PowerShell Remoting (PS Remoting). By using PS Remoting, you can encapsulate any local command and invoke it in a remote session just as you were doing it locally.

Assuming you have PowerShell Remoting enabled on a remote computer, you could, for example, use Invoke-Command to run Get-Service on a remote computer like below.

Note that you don’t need the Credential parameter in an Active Directory (AD) environment.

$cred = Get-Credential
Invoke-Command -ComputerName SRV1 -ScriptBlock { Get-Service } -Credential $

Once executed, Invoke-Command passes on all of the information that Get-Service returned and services would be returned to you as expected.

Invoke Command
Invoke Command

Notice the extra PSComputerName property. This property is returned by Invoke-Command. You can also create a simple script to enumerate services across many remote computers too.

$cred = Get-Credential
 $computers = Get-Content -Path 'C:computers.txt'
 foreach ($name in $computers) {
     $services = Invoke-Command -ComputerName $name -Credential $cred -ScriptBlock {Get-Service}
     [pscustomobject]@{
         ComputerName = $name
         Services = $services
     }
 }

Finding Services with CIM/WMI

In some situations, using PowerShell and Get-Service may not be suitable. Instead, you can query CIM/WMI via a CIM session. If using a CIM session, you don’t have to use PowerShell Remoting.

To find manage services via CIM, you can:

  1. Create a PSCredential object. In the below example, the two computers are not in an AD environment so we’re required to use the Credential parameter.
  2. Create a CIM session providing the name of the computer and the credential to authenticate with.
  3. Use Get-CimInstance to make a query to the Win32_Service class.
$serverName = 'SRV1'
$cred = Get-Credential
$cimSession = New-CimSession -ComputerName $serverName -Credential $cred
Get-CimInstance -CimSession $cimSession -ClassName Win32_Service

## Don't forget to remove the CIM session when you're done
Remove-CimSession -CimSession $cimSession

You’ll see below that much of the same information is returned but is formatted a bit differently.

CIM Session
CIM Session

PowerShell Start Service and Stop Service Cmdlet

You can also start and stop services with PowerShell. There are a couple of ways to make this happen.

Using PowerShell Start-Service and Stop-Service

First, you can use the Start-Service and Stop-Service cmdlets. These cmdlets do exactly what you’d expect. To use them, you can either use the pipeline or use the Name parameter as shown below.

## Stop a service with the Name parameter
$serviceName = 'wuauserv'
Stop-Service -Name $serviceName

## Stop a service with the pipeline
Get-Service $wuauserv | Stop-Service

All of the *-Service cmdlets allow you to tab-complete service name values with the Name and DisplayName parameters. Just type -Name followed by a space and begin hitting the Tab key. You’ll see that it cycles through all of the services on the local computer.

The same concept applies to starting as service too.

## Stop a service with the Name parameter
$serviceName = 'wuauserv'
Start-Service -Name $serviceName

## Stop a service with the pipeline
Get-Service $wuauserv | Start-Service

Both the Stop-Service and Start-Service cmdlets are idempotent meaning if a service is either stopped or started and you attempt to stop or start the service when they are already in that state, the cmdlets will simply skip over the service.

To start and stop remote services with PowerShell, again, you’ll need to wrap these commands in a scriptblock and use PowerShell Remoting to invoke them remotely as shown below.

$cred = Get-Credential
$serviceName = 'wuauserv'
Invoke-Command -ComputerName SRV1 -ScriptBlock { Start-Service -Name $using:serviceName } -Credential $cred

Learn about the $using construct and how to pass local variables to remote scriptblocks in this Invoke-Command post.

Using PowerShell and CIM to Start/Stop Services

As with Get-Service, you can also use CIM to start and stop services. Although, you can’t directly use a cmdlet like Stop-Service and Start-Service. Instead, you have to invoke a method. Although a bit less intuitive, if you’re already managing some things with CIM, it might make sense to just manage service that way too.

If you’re working with local services, use Get-CimInstance again. This time though, you must limit the services down to only the services you’d like to stop or start using the Filter parameter. The Filter parameter (along with the Query parameter) is a great way to limit the results.

The below example is:

  • Querying the local computer’s CIM store’s Win32_Service class for all services that have a startup type set to automatic (StartMode='Auto')
  • Querying the local computer’s CIM store’s Win32_Service class for all services that also are stopped (State='Stopped')
  • Passing all of those objects to Invoke-CimMethod which then calls the StartService method on each of them.
Get-CimInstance -ClassName Win32_Service  -Filter "StartMode='Auto' And State='Stopped'" | Invoke-CimMethod -MethodName StartService

The same code above can also stop services too using the StopService method and perhaps changing the State in the query to Started.

The Filter parameter accept a language known as WQL. You can learn more about WQL in PowerShell’s about_WQL help topic.

Starting/Stopping Remote Services with PowerShell

So you know how to start and stop services locally, you can also extend that to remote computers too using similar code used to enumerate services.

Note that you can always use PowerShell Remoting to wrap any code in a scriptblock and execute it remotely. This tutorial will assume from here on out you are aware of this potential and will not cover this option for all scenarios.

To start and stop services remotely, you can use a CIM session again. You could either reuse the CIM session you created above or if you removed it, create another one as shown below.

$serverName = 'SRV1'
$cred = Get-Credential
$cimSession = New-CimSession -ComputerName $serverName -Credential $cred

Once you have created a CIM session, use the Invoke-CimMethod cmdlet and don’t forget to remove that CIM session when you’re done.

Get-CimInstance -CimSession $cimSession -ClassName Win32_Service  -Filter "StartMode='Auto' And State='Stopped'" | Invoke-CimMethod -MethodName StartService
Remove-CimSession -CimSession $cimSession

You don’t have to use a CIM session to manage remote Windows services. If both the local and remote computer are a member of an AD domain, you could use Get-CimInstance and the ComputerName parameter. However, if you must pass a credential to the remote computer, you must use a CIM session.

A CIM session also is a bit more efficient if you need to execute multiple CIM methods or perform CIM queries on the remote computer because it re-uses the same session instead of having to create a new one for each task.

Using PowerShell to Restart a Service

Maybe you want to restart a service that’s already started. That’s not a problem with PowerShell. Again, you’ve got two ways.

Using Start and Stop-Service

If you’d like to restart a started service, you could just stop and start the service with the Stop-Service and Start-Service cmdlets a few different ways as shown below.

## Restart a service with the Name parameter
$serviceName = 'wuauserv'
Stop-Service -Name $serviceName
Start-Service -Name $serviceName

## Restart a service with the pipeline and PassThru parameter
$serviceName = 'wuauserv'
Stop-Service -Name $serviceName -Passthru | Start-Service

If you need to pass the service object that Stop-Service or Start-Service just ran on and you’d like to perform some other kind of action on that service via the pipeline, you can use the PassThru parameter. The PassThru parameter simply tells the cmdlet to return the object to the pipeline which then allows you to pipe that object to other cmdlets.

Using the PowerShell Restart-Service cmdlet

To limit the code to restart a service with PowerShell, you’d be better off using the Restart-Service cmdlet. This cmdlet does exactly what you think and operates similarly to the othe service cmdlets.

For example, if you’d like to start the wuauserv as shown in the example above, you could save some code by just piping the output of Get-Service directly to Restart-Service as shown below.

## Restart a service with the Name parameter
$serviceName = 'wuauserv'
Get-Service -Name $serviceName | Restart-Service

Changing the Startup Type

Another popular task when managing services is changing the startup type. The startup type is the attribute that dictates what the services do when Windows boots up. You have a few options.

  • Automatic (The service automatically starts when Windows does)
  • Disabled (The service will never start)
  • Manual (The service is available to start but must be done manually)
  • Automate – Delayed (The service starts automatically but is delayed once Windows boots)

Let’s say you first just need to know what a service’s startup type is. You can find this with Get-Service or CIM.

If you’re using Get-Service to find the startup type, you’ll find that Get-Service calls it Status and is represented as the Status property.

(Get-Service -Name wuauserv).StartupType
Automatic

You can quickly get a glimpse on all of the services’ startuptype values by using Group-Object as you can see below. This screenshot shows all of the possible values (in the Name column) that a service’s startup type can be.

Group-Object Command
Group-Object Command

Once you know the current startup type, you can then change it using Set-Service.

The below example is setting the startup type to Disabled.

Set-Service -Name <some service name> -StartupType Disabled

Like the Name and DisplayName parameters, the StartupType parameter allows you to tab-complete all of the available startup types to set a service too.

Using the Registry

You can also set the service startup type via the registry via PowerShell. All Windows services are stored in the HKLMSystemCurrentControlSetServices registry key. Each service child key has a REG_DWORD value called Start that represents the startup type (excluding delayed start).

To set the startup type for a service in the registry via PowerShell, use the Set-ItemProperty cmdlet. The below snippet is changing the startup type of the wuauserv service to automatic.

$serviceName = 'wuauserv'
 Set-ItemProperty "HKLM:SystemCurrentControlSetServices$serviceName" -Name "Start" -Value 2 -Type DWORD

You will need a map to define each REG_DWORD value to the startup type you expect. Below you’ll find a handy table.

REG_DWORD Value Startup Type
0 Loaded (but not started) by the boot loader. Then started during kernel initialization.
1 Started during kernel initialization after services whose start parameter is 0.
2 Automatically. Started by smss.exe (session manager) or services.exe (services controller).
3 Manually. Started by the Service Control Manager (SCM).
4 Disabled
5 Delayed start
REG_DWORD Map

You may also set the startup type to delayed start by setting the DelayedAutoStart registry value to 1 via Set-ItemProperty -Path “HKLM:SystemCurrentControlSetServices<service name>” -Name “DelayedAutostart” -Value 1 -Type DWORD.

Next Steps

By now you should know the basics of restarting service with PowerShell along with managing them. If you’d like to learn more about managing services with PowerShell, be sure to check out PowerShell’s help content with Get-Help <cmdlet name>.

There are a lot of parameters not covered in this article so don’t fret if you didn’t see your particular use case here. Always refer to the help content and verify a parameter isn’t already there for you.

Further Reading

Provide the reader with at least two external links to other sites where the reader could find more information.

  • Set Service Logon Account with PowerShell
  • Back to Basics: The PowerShell ForEach Loop – This is great for managing services on many remote computers at once.

Manage Services using PowerShell

As a Windows administrator, you might need to deal with Services on regular basis. You mainly need to list the services, to stop them, and sometimes need to change the Startup Mode. PowerShell offers you various cmdlets which can help you deal with Services. But before start managing the Services, you need to run the PowerShell console with administrator privileges since PowerShell does not violate the Windows security policies; it respects the security policies.

To start, let’s first take a look at the PowerShell cmdlets with the noun “Service” in their name.

PS D:MyScripts> Get-Command -Noun Service

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Cmdlet          Get-Service                                        Microsoft.PowerShell.Management
Cmdlet          New-Service                                        Microsoft.PowerShell.Management
Cmdlet          Restart-Service                                    Microsoft.PowerShell.Management
Cmdlet          Resume-Service                                     Microsoft.PowerShell.Management
Cmdlet          Set-Service                                        Microsoft.PowerShell.Management
Cmdlet          Start-Service                                      Microsoft.PowerShell.Management
Cmdlet          Stop-Service                                       Microsoft.PowerShell.Management
Cmdlet          Suspend-Service                                    Microsoft.PowerShell.Management

You can use the cmdlets shown above to work with Windows Services.

List all the Services on Your Computer

To list all the services on a computer you can use Get-Service cmdlet (or gsv alias) without any parameter.

PS D:MyScripts> Get-Service

Status   Name               DisplayName
------   ----               -----------
Running  AdobeARMservice    Adobe Acrobat Update Service
Stopped  AeLookupSvc        Application Experience
Stopped  ALG                Application Layer Gateway Service
Stopped  AmmyyAdmin         Ammyy Admin
Stopped  AmmyyAdmin_690     AmmyyAdmin_690
Stopped  AppIDSvc           Application Identity
Running  Appinfo            Application Information
Stopped  AppMgmt            Application Management
Stopped  AppReadiness       App Readiness
Stopped  AppXSvc            AppX Deployment Service (AppXSVC)
Running  AudioEndpointBu... Windows Audio Endpoint Builder
Running  Audiosrv           Windows Audio
Running  AVP15.0.2          Kaspersky Small Office Security Ser...
Stopped  AxInstSV           ActiveX Installer (AxInstSV)
Stopped  BDESVC             BitLocker Drive Encryption Service
Running  BFE                Base Filtering Engine

[output cut]

Notice the default behavior of cmdlet is that it lists all the Services in a tabular format having three columns containing Status, Name and DisplayName of each service because Format-Table is the default formatting cmdlet used by Get-Service. This is pretty much satisfactory for most of administrators. But if you want to format the output in List form, you can do this by piping the output of Get-Service cmdlet to Format-List cmdlet (fl alias). The following example lists the services in list format.

PS D:MyScripts> gsv | fl

Name                : AdobeARMservice
DisplayName         : Adobe Acrobat Update Service
Status              : Running
DependentServices   : {}
ServicesDependedOn  : {}
CanPauseAndContinue : False
CanShutdown         : False
CanStop             : True
ServiceType         : Win32OwnProcess

Name                : AeLookupSvc
DisplayName         : Application Experience
Status              : Stopped
DependentServices   : {}
ServicesDependedOn  : {}
CanPauseAndContinue : False
CanShutdown         : False
CanStop             : False
ServiceType         : Win32ShareProcess

Name                : ALG
DisplayName         : Application Layer Gateway Service
Status              : Stopped
DependentServices   : {}
ServicesDependedOn  : {}
CanPauseAndContinue : False
CanShutdown         : False
CanStop             : False
ServiceType         : Win32OwnProcess

Name                : AmmyyAdmin
DisplayName         : Ammyy Admin
Status              : Stopped
DependentServices   : {}
ServicesDependedOn  : {}
CanPauseAndContinue : False
CanShutdown         : False
CanStop             : False
ServiceType         : Win32OwnProcess

[output cut]

Notice that the output is now displayed in list format. In this format some additional properties are also listed for each service. This is default behavior of Format-List cmdlet. If you want to see specific properties, use -Property parameter followed by the property name in the same order you want to list. The following example with display the all services with 3 properties (Name, DisplayName, Status) in List format.

PS D:MyScripts> gsv | fl -Property Name, DisplayName, Status

Name        : AdobeARMservice
DisplayName : Adobe Acrobat Update Service
Status      : Running

Name        : AeLookupSvc
DisplayName : Application Experience
Status      : Stopped

Name        : ALG
DisplayName : Application Layer Gateway Service
Status      : Stopped

Name        : AmmyyAdmin
DisplayName : Ammyy Admin
Status      : Stopped

To display a specific service, use Get-Service cmdlet followed by the name of service. The following example displays the Windows Update service.

PS D:MyScripts> Get-Service "Windows Update"

Status   Name               DisplayName
------   ----               -----------
Running  wuauserv           Windows Update

You can also use wildcard (*) to list multiple services starting or ending with same name. The following example lists all the services having microsoft keyword in their name.

PS D:MyScripts> Get-Service -DisplayName *microsoft*

Status   Name               DisplayName
------   ----               -----------
Stopped  MSiSCSI            Microsoft iSCSI Initiator Service
Stopped  MsKeyboardFilter   Microsoft Keyboard Filter
Stopped  odserv             Microsoft Office Diagnostics Service
Stopped  smphost            Microsoft Storage Spaces SMP
Stopped  swprv              Microsoft Software Shadow Copy Prov...
Stopped  wlidsvc            Microsoft Account Sign-in Assistant

Manipulate the Output of Get-Service

Remember that PowerShell provides a Get-Member cmdlet which helps you to list all the properties associated with any cmdlet. Taking advantage of Get-Service | Get-Member, we can refine the output so that we add extra properties, for example, CanStop and ServiceType.

PS D:MyScripts> Get-Service | Get-Member

   TypeName: System.ServiceProcess.ServiceController

Name                      MemberType    Definition
----                      ----------    ----------
Name                      AliasProperty Name = ServiceName
RequiredServices          AliasProperty RequiredServices = ServicesDependedOn
Disposed                  Event         System.EventHandler Disposed(System.Object, System.EventArgs)
Close                     Method        void Close()
Continue                  Method        void Continue()
CreateObjRef              Method        System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Dispose                   Method        void Dispose(), void IDisposable.Dispose()
Equals                    Method        bool Equals(System.Object obj)
ExecuteCommand            Method        void ExecuteCommand(int command)
GetHashCode               Method        int GetHashCode()
GetLifetimeService        Method        System.Object GetLifetimeService()
GetType                   Method        type GetType()
InitializeLifetimeService Method        System.Object InitializeLifetimeService()
Pause                     Method        void Pause()
Refresh                   Method        void Refresh()
Start                     Method        void Start(), void Start(string[] args)
Stop                      Method        void Stop()
WaitForStatus             Method        void WaitForStatus(System.ServiceProcess.ServiceControllerStatus desiredStatus), void Wa...
CanPauseAndContinue       Property      bool CanPauseAndContinue {get;}
CanShutdown               Property      bool CanShutdown {get;}
CanStop                   Property      bool CanStop {get;}
Container                 Property      System.ComponentModel.IContainer Container {get;}
DependentServices         Property      System.ServiceProcess.ServiceController[] DependentServices {get;}
DisplayName               Property      string DisplayName {get;set;}
MachineName               Property      string MachineName {get;set;}
ServiceHandle             Property      System.Runtime.InteropServices.SafeHandle ServiceHandle {get;}
ServiceName               Property      string ServiceName {get;set;}
ServicesDependedOn        Property      System.ServiceProcess.ServiceController[] ServicesDependedOn {get;}
ServiceType               Property      System.ServiceProcess.ServiceType ServiceType {get;}
Site                      Property      System.ComponentModel.ISite Site {get;set;}
Status                    Property      System.ServiceProcess.ServiceControllerStatus Status {get;}
ToString                  ScriptMethod  System.Object ToString();

The following example illustrates how we can ‘Sort’ the output based on ServiceType rather than the ‘Name’ property.

PS D:MyScripts> Get-Service | Sort-Object -Property ServiceType | Format-Table Name, ServiceType, Status, CanStop -AutoSize

Name                                                                             ServiceType  Status CanStop
----                                                                             -----------  ------ -------
Intel(R) ME Service                                                          Win32OwnProcess Running    True
Intel(R) PROSet Monitoring Service                                           Win32OwnProcess Running    True
Intel(R) Capability Licensing Service TCP IP Interface                       Win32OwnProcess Stopped   False
RpcLocator                                                                   Win32OwnProcess Stopped   False
Intel(R) Capability Licensing Service Interface                              Win32OwnProcess Running    True
LMS                                                                          Win32OwnProcess Running    True
MozillaMaintenance                                                           Win32OwnProcess Stopped   False
TrustedInstaller                                                             Win32OwnProcess Stopped   False
jhi_service                                                                  Win32OwnProcess Running    True
vds                                                                          Win32OwnProcess Stopped   False
VSS                                                                          Win32OwnProcess Stopped   False
FontCache3.0.0.0                                                             Win32OwnProcess Running    True
wampapache64                                                                 Win32OwnProcess Stopped   False
Fax                                                                          Win32OwnProcess Stopped   False
wampmysqld64                                                                 Win32OwnProcess Stopped   False

[output cut]

The -AutoSize parameter produces more sensible column widths.

Filtering the Output

If you are a System administrator, you might want to look at the services which are running and which have stopped. This can be done with the help of Where-Object cmdlet.

The following command will list the services which are stopped.

PS D:MyScripts> Get-Service | Where-Object {$_.Status -eq "Stopped"}

Status   Name               DisplayName
------   ----               -----------
Stopped  AeLookupSvc        Application Experience
Stopped  ALG                Application Layer Gateway Service
Stopped  AmmyyAdmin         Ammyy Admin
Stopped  AmmyyAdmin_690     AmmyyAdmin_690
Stopped  AppIDSvc           Application Identity
Stopped  AppMgmt            Application Management
Stopped  AppReadiness       App Readiness
Stopped  AppXSvc            AppX Deployment Service (AppXSVC)
Stopped  AxInstSV           ActiveX Installer (AxInstSV)
Stopped  BDESVC             BitLocker Drive Encryption Service
Stopped  BthHFSrv           Bluetooth Handsfree Service
Stopped  bthserv            Bluetooth Support Service
Stopped  COMSysApp          COM+ System Application
Stopped  cphs               Intel(R) Content Protection HECI Se...
Stopped  CscService         Offline Files
Stopped  defragsvc          Optimize drives
Stopped  DeviceInstall      Device Install Service
Stopped  dot3svc            Wired AutoConfig
Stopped  DsmSvc             Device Setup Manager

[output cut]

Take careful note of the syntax. The Where-Object is enclosed within curly braces. In addition, the $_ notation is used to represent the object being transferred across the pipeline. The .Status is calling the property of current service in pipeline. You can call any property which you have found using Get-Service | Get-Member command. Notice the comparison operator used is equal to (-eq). Windows PowerShell does not use the standard arithmetic comparison operators; instead, it uses operators such as:

  • -lt — Less than
  • -le — Less than or equal to
  • -gt — Greater than
  • -ge — Greater than or equal to
  • -eq — Equal to
  • -ne — Not equal to
  • -like — Like; uses wildcards for pattern matching
  • -match — Matches a string using regular expressions.
  • -contains — Tells whether a collection of reference values includes a single test value. Always returns a Boolean value TRUE or FALSE.
  • -replace — Changes the specified elements of a value.

If you want to look for the services which are Running, just replace the ‘Stopped’ keyword with Running in above command. The command is shown below:

PS D:MyScripts> Get-Service | Where-Object {$_.Status -eq "Running"}

Status   Name               DisplayName
------   ----               -----------
Running  AdobeARMservice    Adobe Acrobat Update Service
Running  Appinfo            Application Information
Running  AudioEndpointBu... Windows Audio Endpoint Builder
Running  Audiosrv           Windows Audio
Running  AVP15.0.2          Kaspersky Small Office Security Ser...
Running  BFE                Base Filtering Engine
Running  BITS               Background Intelligent Transfer Ser...
Running  BrokerInfrastru... Background Tasks Infrastructure Ser...
Running  Browser            Computer Browser

[output cut]

You can also filter the output with Select-Object cmdlet using -Property parameter of command as shown below:

PS D:MyScripts> Get-Service | Select-Object -Property DisplayName, Status

DisplayName                                                                                                                  Status
-----------                                                                                                                  ------
Adobe Acrobat Update Service                                                                                                Running
Application Experience                                                                                                      Running
Application Layer Gateway Service                                                                                           Stopped
Ammyy Admin                                                                                                                 Stopped

[output cut]

The above commands will only display DisplayName and Status properties of windows services.

Use  Get-Service on Remote Computer

You can use Get-Service cmdlet with –ComputerName parameter to retrieve and manipulate the services of remote computer as you did with local computer. You must have enough privileges on remote computer in order to run the command. Also note that Get-Service command does not use PowerShell remoting (WSMan) to retrieve data from remote computer; instead it uses dot net framework methods. So, you can run Get-Service cmdlet against any remote computer which does not have PowerShell remoting configured.

PS D:MyScripts> Get-Service -ComputerName DC1

Status   Name               DisplayName
------   ----               -----------
Running  ADWS               Active Directory Web Services
Stopped  AeLookupSvc        Application Experience
Stopped  ALG                Application Layer Gateway Service
Running  AppHostSvc         Application Host Helper Service
Stopped  AppIDSvc           Application Identity
Running  Appinfo            Application Information
Stopped  AppMgmt            Application Management
Stopped  aspnet_state       ASP.NET State Service
Stopped  AudioEndpointBu... Windows Audio Endpoint Builder
Stopped  AudioSrv           Windows Audio
Running  AVP15.0.2          Kaspersky Small Office Security Ser...
Running  BFE                Base Filtering Engine
Running  BITS               Background Intelligent Transfer Ser...

[output cut]

Using Out-File cmdlet

You can use Out-File cmdlet to redirect and save the output of Get-Service and even the output of every cmdlet to a text file. This method can be helpful for logging.

PS D:MyScripts> Get-Service | Where-Object {$_.Status -eq "Stopped"} | out-file "D:Stopped_services.txt"

This time you will not see any output on console, instead the output is sent to file D:Stopped_services.txt file. If you look at the contents of file, the output would be similar to that of console output.

PS D:MyScripts> Get-Content D:Stopped_services.txt

Status   Name               DisplayName
------   ----               -----------
Stopped  AeLookupSvc        Application Experience
Stopped  ALG                Application Layer Gateway Service
Stopped  AmmyyAdmin         Ammyy Admin
Stopped  AmmyyAdmin_690     AmmyyAdmin_690
Stopped  AppIDSvc           Application Identity
Stopped  AppMgmt            Application Management
Stopped  AppReadiness       App Readiness
Stopped  AppXSvc            AppX Deployment Service (AppXSVC)
Stopped  AxInstSV           ActiveX Installer (AxInstSV)
Stopped  BDESVC             BitLocker Drive Encryption Service
Stopped  BthHFSrv           Bluetooth Handsfree Service
Stopped  bthserv            Bluetooth Support Service
Stopped  COMSysApp          COM+ System Application
Stopped  cphs               Intel(R) Content Protection HECI Se...
Stopped  CscService         Offline Files
Stopped  defragsvc          Optimize drives
Stopped  DeviceInstall      Device Install Service

[output cut]

Start a Windows Service

You can start any service with the help of Start-Service cmdlet. An example of starting a ‘Stopped’ windows update service is given below:

PS D:MyScripts> gsv wuauserv

Status   Name               DisplayName
------   ----               -----------
Stopped  wuauserv           Windows Update

PS D:MyScripts> Get-Service wuauserv | Start-Service -Verbose
VERBOSE: Performing the operation "Start-Service" on target "Windows Update (wuauserv)".

In first command, I checked the status of Windows Update service. I saw it is stopped. So, I piped the output of Get-Service wuauserv command to Start-Service cmdlet and the service started. The -verbose switch displayed the information about the operation being performed.

PS D:MyScripts> Get-Service wuauserv

Status   Name               DisplayName
------   ----               -----------
Running  wuauserv           Windows Update

You can also use the Start-Service cmdlet directly if you know the name of service you want to start. This is shown below:

PS D:MyScripts> Start-Service AmmyyAdmin -Verbose
VERBOSE: Performing the operation "Start-Service" on target "Ammyy Admin (AmmyyAdmin)".

Stop a Windows Service

To stop any running service, use Stop-Service cmdlet as shown below:

PS D:MyScripts> Stop-Service AmmyyAdmin ; Get-Service AmmyyAdmin

Status   Name               DisplayName
------   ----               -----------
Stopped  AmmyyAdmin         Ammyy Admin

This time I did not use -verbose switch, that’s why I did not see any information but the service is actually stopped. Notice that I’ve used semi-colon (;) to run two commands at one time. You can always run multiple PowerShell commands at once by using semi-colon (;) between each command.

Change the Service StartMode

Sometime you might want to see and even change the StartMode of any service. The StartMode is a condition which determines the behavior of service. The StartupMode can accept the following values:

  • Automatic: The Service is started automatically as part of the Windows boot process.
  • Manual: The Service can be started by any application, process or user whenever needed, but is off by default. Once it is started, the service will remain started until it is manually stopped or the system is rebooted.
  • Disabled: The service is disabled. It will not run.

Unfortunately, Windows PowerShell does not have any built-in cmdlet which can display the StartMode for any service. The Get-Service cmdlet does not display StartMode property even when used with Format-List -Property * parameter.

PS D:MyScripts> Get-Service wuauserv | Select-Object -Property *

Name                : wuauserv
RequiredServices    : {rpcss}
CanPauseAndContinue : False
CanShutdown         : False
CanStop             : False
DisplayName         : Windows Update
DependentServices   : {}
MachineName         : .
ServiceName         : wuauserv
ServicesDependedOn  : {rpcss}
ServiceHandle       : SafeServiceHandle
Status              : Stopped
ServiceType         : Win32ShareProcess
Site                :
Container           :

Look at the output of above command; you can not see the StartMode property. So, how do you come to know if any service (Windows Update for instance) is set to start automatically at system startup or it is set as manual?

Luckily, Windows PowerShell has a Get-WmiObject cmdlet which allows you to query WMI (Windows Management Instrumentation) on system and retrieve the data from WMI store. You can see the StartMode property of any windows service using Get-WmiObject cmdlet as shown below:

PS D:MyScripts> Get-WmiObject -Class Win32_Service

ExitCode  : 0
Name      : AdobeARMservice
ProcessId : 1532
StartMode : Auto
State     : Running
Status    : OK

ExitCode  : 0
Name      : AeLookupSvc
ProcessId : 0
StartMode : Manual
State     : Stopped
Status    : OK

ExitCode  : 1077
Name      : ALG
ProcessId : 0
StartMode : Manual
State     : Stopped
Status    : OK

[output cut]

Notice that Get-WmiObject cmdlet by default uses Format-List to format the output and it displays all the information like that of Get-Service cmdlet including StartMode property. To display the output in the same format as Get-Service; use the following command:

PS D:MyScripts> Get-WmiObject -Class Win32_Service | Format-Table -Property State, Name, DisplayName, StartMode

State                            Name                             DisplayName                      StartMode
-----                            ----                             -----------                      ---------
Running                          AdobeARMservice                  Adobe Acrobat Update Service     Auto
Stopped                          AeLookupSvc                      Application Experience           Manual
Stopped                          ALG                              Application Layer Gateway Ser... Manual
Stopped                          AmmyyAdmin_690                   

[output cut]         

The above command produces the output similar to Get-Service cmdlet including StartMode property for every service.

To view the StartMode property for a particular service (Windows Update for instance), use the Get-WmiObject cmdlet as shown below:

PS D:MyScripts> Get-WmiObject -Class Win32_Service | Where-Object {$_.name -eq 'wuauserv'} | Format-Table -Property State, Name, Di
splayName, StartMode

State                            Name                             DisplayName                      StartMode
-----                            ----                             -----------                      ---------
Running                          wuauserv                         Windows Update                   Manual

You see the above command became very lengthy. You can always shorten the commands by using aliases instead of typing complete command. The above command can be shortened as follows:

PS D:MyScripts> gwmi Win32_Service|?{$_.name -eq 'wuauserv'}|ft State,Name,DisplayName,StartMode

State                            Name                             DisplayName                      StartMode
-----                            ----                             -----------                      ---------
Stopped                          wuauserv                         Windows Update                   Manual

Now, we know that Windows update service has StartMode set to Manual. To change the StartMode, use Set-Service cmdlet with -StartupType parameter as shown below:

PS D:MyScripts> Set-Service wuauserv -StartupType Automatic -Status Running
PS D:MyScripts> gwmi Win32_Service|?{$_.name -eq 'wuauserv'}|ft State,Name,DisplayName,StartMode

State                            Name                             DisplayName                      StartMode
-----                            ----                             -----------                      ---------
Running                          wuauserv                         Windows Update                   Auto

The -StartupType parameter can accept only 3 values (Automatic, Manual, Disabled) and the -Status parameter can also accept only 3 values (Running, Paused, Stopped).

Stop a Windows Service

You can stop a running windows service using Stop-Service cmdlet. Remember that there are some critical windows services which do not support stopping. To get the list of windows services which can be stopped, use the Get-Service cmdlet as shown below:

PS D:MyScripts> Get-Service | Where-Object {$_.Status -eq 'Running' -and $_.CanStop}

Status   Name               DisplayName
------   ----               -----------
Running  AdobeARMservice    Adobe Acrobat Update Service
Running  Appinfo            Application Information
Running  AudioEndpointBu... Windows Audio Endpoint Builder
Running  Audiosrv           Windows Audio
Running  AVP15.0.2          Kaspersky Small Office Security Ser...
Running  BFE                Base Filtering Engine
Running  BITS               Background Intelligent Transfer Ser...
Running  Browser            Computer Browser
Running  c2cautoupdatesvc   Skype Click to Call Updater
Running  c2cpnrsvc          Skype Click to Call PNR Service
Running  CertPropSvc        Certificate Propagation
Running  CryptSvc           Cryptographic Services

[output cut]

To list all services that cannot be stopped, slightly modify the above command:

PS D:MyScripts> Get-Service | Where-Object {$_.status -eq 'running' -and !$_.CanStop}

Status   Name               DisplayName
------   ----               -----------
Running  BrokerInfrastru... Background Tasks Infrastructure Ser...
Running  DcomLaunch         DCOM Server Process Launcher
Running  LSM                Local Session Manager
Running  Power              Power
Running  RpcEptMapper       RPC Endpoint Mapper
Running  RpcSs              Remote Procedure Call (RPC)
Running  SamSs              Security Accounts Manager
Running  wudfsvc            Windows Driver Foundation - User-mo...

Notice that I used Not Operator (!) in front of CanStop property. The same command could be written as follows:

PS D:MyScripts> Get-Service | Where-Object {$_.Status -eq 'Running' -and $_.CanStop -eq $false}

Status   Name               DisplayName
------   ----               -----------
Running  BrokerInfrastru... Background Tasks Infrastructure Ser...
Running  DcomLaunch         DCOM Server Process Launcher
Running  LSM                Local Session Manager
Running  Power              Power
Running  RpcEptMapper       RPC Endpoint Mapper
Running  RpcSs              Remote Procedure Call (RPC)
Running  SamSs              Security Accounts Manager
Running  wudfsvc            Windows Driver Foundation - User-mo...

For example, to stop Windows Update service, run the following command:

PS D:MyScripts> Get-Service wuauserv | Stop-Service -Verbose
VERBOSE: Performing the operation "Stop-Service" on target "Windows Update (wuauserv)".
WARNING: Waiting for service 'Windows Update (wuauserv)' to stop...
WARNING: Waiting for service 'Windows Update (wuauserv)' to stop...

The -verbose switch is used to display the information about the operation being performed. You could also use Stop-Service wuauserv command. Both will work and perform same thing.

Restart a Windows Service

PowerShell gives you Restart-Service cmdlet which works pretty much same way as that of Stop-Service and Start-Service cmdlets. The following example shows how to restart Windows Update service.

PS D:MyScripts> Restart-Service wuauserv -Verbose
VERBOSE: Performing the operation "Restart-Service" on target "Windows Update (wuauserv)".

Pause and Resume Windows Service

The Suspend-Service cmdlet sends a suspend (pause) message to the Windows Service Controller for each of the specified services. While suspended, the service is still running, but its action is halted until resumed, such as by using Resume-Service. You can specify the services by their service names or display names, or you can use the InputObject parameter to pass a service object representing the services that you want to suspend.

The following command list all of the services on the computer that can be suspended.

PS D:MyScripts> Get-Service | Where-Object {$_.CanPauseAndContinue }

Status   Name               DisplayName
------   ----               -----------
Running  LanmanWorkstation  Workstation
Running  Netlogon           Netlogon
Running  stisvc             Windows Image Acquisition (WIA)
Running  Winmgmt            Windows Management Instrumentation

To Suspend (pause) the Workstation service on computer, use the following command.

PS D:MyScripts> Suspend-Service -DisplayName Workstation

Now the status service changed to Paused.

PS D:MyScripts> Get-Service Workstation

Status   Name               DisplayName
------   ----               -----------
Paused   LanmanWorkstation  Workstation

To Resume the service, use Resume-Service cmdlet as shown below:

PS D:MyScripts> Resume-Service -DisplayName Workstation

Using Out-GridView cmdlet

PowerShell offers an Out-GridView cmdlet that sends the output to an interactive graphical table in a separate window. You can use Out-GridView along with Get-Service cmdlet to control services even more elegantly. See the following command as an example:

PS D:MyScripts> Get-Service | Where-Object {$_.status -eq 'Stopped'} | Out-GridView -Title "Select service(s) to start" –PassThru | Start-Service –Verbose

Using Out-GridView cmdlet in PowerShell

Using Out-GridView cmdlet in PowerShell

We are essentially getting the services that are currently stopped, passing them to Out-GridView cmdlet in a nice graphical table, where we can select one or more services (by pressing and holding Ctrl button). After making the selection, when we click OK, the selected services will then be passed to Start-Process cmdlet with the help of -PassThru parameter. Ultimately, the selected services will be started. You can use the same idea to stop running services.

Create a new Windows Service

The New-Service cmdlet creates a new entry for a Windows service in the registry and in the service database. A new service requires an executable file that executes during the service.

The parameters of this cmdlet let you set the display name, description, startup type, and dependencies of the service.

For example, I have downloaded a portable TFTP Server from internet and I want to create a new TFTP service on my computer. Use the following PowerShell command to create new service.

PS D:MyScripts> Get-Service | ? {$_.DisplayName -like "*tftp*"}

This command confirms if there is any existing service on computer with matching name.

The following command creates a new service with the name TFTPServer and sets the StartMode to Manual:

PS D:MyScripts> New-Service -Name TFTPServer -BinaryPathName "C:TFTPtftpd32.exe" -DisplayName "TFTP Server" -Description "Open Source TFTP Server" -StartupType Manual

Status   Name               DisplayName
------   ----               -----------
Stopped  TFTPServer         TFTP Server

The newly created service is stopped. To start the service, use Start-Service cmdlet.

PS D:MyScripts> Start-Service TFTPServer -Verbose

Delete or Remove a Windows Service

Have you ever encountered in a situation when you have uninstalled any software but the it’s rellevant service keeps appearing in Windows Services? The service no longer work and you want to remove this service.However, Windows PowerShell does not give any Remove-Service cmdlet to use, but still you can use Get-WmiObject cmdlet to remove the service. Wodering how?

This is how you do it. Remember that you can create any variable in PowerShell using dollar ($) symbol. You need to create a $svc variable and store the service name into it. Then you need to call delete method and the service will be gone.

I will show you step by step process:

1). Create a $svc variable and store the service with the name TFTServer into it.

PS D:MyScripts> $svc = Get-WmiObject Win32_Service -Filter "Name='TFTPServer'"

2). To confirm, type the variable name ($svc) and press Enter.

PS D:MyScripts> $svc

ExitCode  : 0
Name      : TFTPServer
ProcessId : 0
StartMode : Manual
State     : Stopped
Status    : OK

3). Now you know that the service you want to remove is stored into $svc variable, use Get-Member cmdlet with -MemberType Method parameter to see the available methods for this service. The following command tells you what methods this service can accept.

PS D:MyScripts> Get-Member -InputObject $svc -MemberType Method

   TypeName: System.Management.ManagementObject#rootcimv2Win32_Service

Name                  MemberType Definition
----                  ---------- ----------
Change                Method     System.Management.ManagementBaseObject Change(System.String DisplayName, System.String PathName...
ChangeStartMode       Method     System.Management.ManagementBaseObject ChangeStartMode(System.String StartMode)
Delete                Method     System.Management.ManagementBaseObject Delete()
GetSecurityDescriptor Method     System.Management.ManagementBaseObject GetSecurityDescriptor()
InterrogateService    Method     System.Management.ManagementBaseObject InterrogateService()
PauseService          Method     System.Management.ManagementBaseObject PauseService()
ResumeService         Method     System.Management.ManagementBaseObject ResumeService()

[output cut]

4). We are only interested in delete method since we want to delete the service. Now, all you need to do is to call the delete method and the service will be removed. This is done with the following command.

PS D:MyScripts> $svc.delete()

__GENUS          : 2
__CLASS          : __PARAMETERS
__SUPERCLASS     :
__DYNASTY        : __PARAMETERS
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
ReturnValue      : 0
PSComputerName   :

5). Use the Get-Service cmdlet to confirm if the service is deleted or still exists.

PS D:MyScripts> Get-Service TFTPServer
Get-Service : Cannot find any service with service name 'TFTPServer'.
At line:1 char:1
+ Get-Service TFTPServer
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (TFTPServer:String) [Get-Service], ServiceCommandException
    + FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand

The above process is not so difficult. But if you believe in shorthand one-liners, below is a one-liner to delete a service:

PS D:MyScripts> (Get-WmiObject Win32_Service -Filter "Name='TFTPServer'").Delete()

__GENUS          : 2
__CLASS          : __PARAMETERS
__SUPERCLASS     :
__DYNASTY        : __PARAMETERS
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
ReturnValue      : 0
PSComputerName   :

The more you use Windows PowerShell, the more you will be able to understand it. Try to use aliases to shorten the commands and use tab-completion feature where-ever possible.

Thats all about Managing windows services using PowerShell. In the next section, we will look into how to Manage Windows Processes using PowerShell.

Back

Table of Contents

  • Methodology
  • Script To Find All Services
  • Script To Filter Services
  • Conclusion
  • See Also
  • References

Most people know you can see all the running services in a Windows operating system by employing
services.msc through the Search box or Run command. From there, you can filter by Name or Startup Type to view what services are started, which are stopped, and which should have been started and perhaps failed.

You can also retrieve this information through PowerShell. The benefit of using PowerShell is that you can filter by Startup Type (startmode in PowerShell) or Status (state). For example, by using a PowerShell command you can find all services that have
a Startup Type of Automatic and a Status of Stopped. This information is filtered and presented quickly to you. This saves you time from sorting and scrolling through the list of services.

Methodology

To find the services we are looking for, we will use the Get-WmiObject cmdlet within PowerShell. It is used to carry out system administration tasks and can even be run against remote computers. This cmdlet gets an instance of Windows Management
Instrumentation (WMI) and any of its available sub-classes. We could also use its alias
gwmi to shorten the cmdlet call.

Script To Find All Services

If we want to run a PowerShell command to find all services on our operating system, we can use a script similar to the one shown in the image below. It retrieves the Name, DisplayName, State and StartMode of the services and then sorts them by State and
Name. Setting the script up this way lets us see all of the Running and Stopped services grouped together. This provides a quick glimpse into services we suspect is causing a problem, especially if one is supposed to be Running and it is set to Stopped.

Script To Filter Services

If we need to be more precise in our searching, we can apply filters to our Get-WmiObject calls so that they return only the information we need. Using our example from above, to find all services that have a Startup Type of Automatic and a Status of Stopped
we can apply a filter to return only services that meet these criteria.

Conclusion

In this article, we reviewed how we can use the PowerShell Get-WmiObject cmdlet to find all the running services on an OS. We also saw how we can filter the data returned so it only shows the information we need to troubleshoot a problem. Using this filtering
capability, we can see how much easier it is to quickly find services that meet our troubleshooting criteria.

See Also

Download a copy of each PowerShell script from the TechNet Gallery:

  • Get all services (PowerShell)
  • Get all services with filter (PowerShell)

References

  • Use PowerShell to Find Non-Starting Automatic
    Services
  • Use
    PowerShell to List Stopped Services that are Set to Start Automatically While Excluding Delayed Start Services

The Get-Command cmdlet helps you find PowerShell cmdlets, especially one you used previously but just can’t remember its exact name.

  • Author
  • Recent Posts

Michael Pietroforte is the founder and editor in chief of 4sysops. He has more than 35 years of experience in IT management and system administration.

The number of PowerShell cmdlets has increased with each release, and you’ll now find few Windows functions or features that you can’t manage with PowerShell. However, you’ll often face the question of which cmdlet to use to get the job done. The Get-Command cmdlet offers various options to search for the available cmdlets on your computer.

To display a list of all available PowerShell cmdlets, you have to run Get-Command without parameters, like this:

Get-Command

Note that this command lists not only PowerShell cmdlets but also functions, workflows, and aliases. You can even use Get-Command to view all executables, including files that are not Windows PowerShell files, like this:

Get-Command *

This command will search for all executables in all folders that are stored in the Path environment variable. You can list these folders by typing $env:path at a PowerShell prompt.

However, in most cases, you will only want to list all cmdlets. You can do so by using the CommandType parameter, like this:

Get-Command -CommandType Cmdlet

This list is still a bit long if you want to skim through the cmdlets to find the one you used last week but can’t recall its name. If you know that the cmdlet is part of a certain module, say the Active Directory module, you can restrict the list to just this module:

Get-Command -Module ActiveDirectory

This command will only produce output if you installed the Active Directory module. However, PowerShell comes with many pre-installed modules. As of PowerShell 3.0, PowerShell automatically imports installed modules when you run a cmdlet or access one with Get-Help and Get-Command. To display a list of all installed modules, you can run this command:

Get-Module -ListAvailable

You can see the imported cmdlets of your current session with this command:

Get-Command -ListImported -CommandType Cmdlet

Note that this list changes when you access modules in your current session. For instance, if you listed the available cmdlets in the AppLocker module with Get-Command -Module AppLocker, the -ListImported parameter will then also display the cmdlets included in the AppLocker module because Get-Command automatically imports the AppLocker module into your current session.

If you added modules to your session but you only want to know what cmdlets are already imported at the start of a session, use this command to list only the cmdlets of the PowerShell Core modules:

Get-Command -CommandType Cmdlet -Module Microsoft*,PS*

You probably know that PowerShell cmdlets follow the naming convention verb-noun, where verb stands for an action that is applied to the object to which the noun refers. To get a list of all available verbs, you can use the Get-Verb cmdlet. This list won’t help you much in your search for your cmdlet; however, if you know that you are looking for a cmdlet to retrieve information, it will start with the verb Get:

Get-Command -Verb Get

Quite a few approved PowerShell verbs exist. In most cases, you will remember the verb if you used the cmdlet before. The above command then allows you to reduce your search list.

No Get-Noun cmdlet exists, but we can use Get-Command to list all nouns:

Get-Command -Noun *

The problem with this command is that the list also includes function names. We can’t use the CommandType parameter together with the Noun parameter because they belong to different parameter sets. That is, if you use the Noun parameter, Get-Command only returns cmdlets anyway, and using the CommandType parameter would therefore make no sense. If you only want to see a list of cmdlet nouns without the function names, you can use this command:

Get-Command -CommandType Cmdlet | Select Noun | Sort Noun

We can pipe the output to the Select-Object cmdlet because Get-Command returns objects and Noun is one of their properties. To get an alphabetically sorted list, we pipe it to the Sort-Object cmdlet.

However, in most cases, you will want to search for a noun that contains a certain string. For instance, if you are looking for a way to manage AppLocker with PowerShell, you could display a list of nouns that start with “applocker” by using “*” as a wildcard character:

Get-Command -Noun applocker*

Because PowerShell is case insensitive, we don’t have to worry about capital letters.

If you only want to have cmdlet names in your results list, you can use the CommandType and Name parameters together:

Get-Command -CommandType Cmdlet -Name *applocker*

The wildcard characters at the beginning and the end ensure that the command finds all cmdlets that contain the string “applocker.”

After you find your cmdlet, you can use Get-Command to get more information about the cmdlet’s usage. You can even use Get-Command to find out more about Get-Command.

Get-Command Get-Command | Format-List

Get-Command Get-Command

As mentioned above, Get-Command returns an object that we can pipe to the Format-List cmdlet to display a formatted list of the object’s properties. This will give you information about the cmdlet’s syntax. However, if you need more detailed help, you should use the Get-Help cmdlet:

Get-Help Get-ApplockerPolicy

Just make sure to get help before use Get-Help.

I only discussed the most common usage scenarios of Get-Command. For a complete list of all parameters, you can either run Get-Help Get-Command or read its documentation online.

In my next post I will discuss Show-Command, another helpful tool that allows you to find cmdlets and learn how to use them.

There are many ways to monitor Windows services but one of the most flexible methods is via PowerShell (PS).

The advanced PS scripts referenced in this post will help you detect when a Windows service is stopped, when it is back up again, and will ultimately send an email alert with details.

To help automate monitoring, you can configure PS to schedule tasks to run scripts daily, at different intervals.

PowerShell

The few critical Windows OS services are started when the server boots and are stopped when the server shuts down.

These services need to be continuously running and they don’t have a reason to stop their operations while the server is up.

But on the other hand, there are applications such as IIS, Exchange, Active Directory that are running on a Windows server.

These applications need their services to be up and running but, if any of these services stop, the whole application is disrupted.

A Windows Services monitoring solution should be able to keep track of these services and send alerts when one of these services stops or is down.

There are some Windows Services monitoring solutions that can help you automate this process.

These tools include PRTG Network Monitor, SolarWinds SAM, ManageEngine, and more.

But if you have basic PowerShell scripting skills, you can set up your own monitoring solution with the help of basic functions and cmdlets.

Related Post: PowerShell Kill Process Command

Managing Services with Cmdlets

A cmdlet is a lightweight Windows PowerShell (PS) script that helps interact with the PS platform and the scripting language.

There are eight service cmdlets that let you perform an extensive number of tasks on Windows services.

These can let you query, reset, start, stop, and set services.

To get a list of the cmdlets, you can open PowerShell and use the command:

Get-Help *-Service

Powershell Get Help

We will be using the “Get-Service” cmdlet to display the status of a service named Microsoft Remote Access Service (RasMan).

For example, let’s say that currently, RasMan is down.

Run the following command:

Get-Service -Name RasMan | Select-Object -Property *

PowerShell Get Service

As you can see from the output, the current “Status” of the service is “Stopped.”

From this output, you can also see other details like whether you can start it, stop it, reset it, its dependent services, type, etc.

The Get-Service is the right cmdlet to monitor services, but you can also use others to push actions such as the “Start-Service” or “Restart-Service.”

Let’s go ahead and attempt to start the service using the “Start-Service” cmdlet.

Run the following command:

Start-Service -Name RasMan

Powershell Start Service

And now from the results shown above, you can see that the service is up and running.

Now, the good thing with PowerShell is that you can combine the results of a “Get-Service” with the actions of the “Start-Service”.

You can use this combination of both to query and then start a service if it is equal to “stopped.”

To start a service if it is not running run the following line:

Get-Service RasMan | %{if ($_.Status -eq "Stopped") { Start-Service RasMan }}

Powershell Get Start

Cmdlets are amazing lightweight tools that can help monitor services running on a local or remote server.

But these tools will not be capable of notifying you when a service status changes or for automating specific tasks.

The next advanced PowerShell functions will take this simple script to a new level.

Advanced PowerShell Functions

The functions shown here are able to keep track of a Windows service, attempt to restart, and even send an alert via email.

The Get-PSServiceStatus Function:

The open-source PowerShell code Get-PSServiceStatus developed by dfranciscus, suggests using the Send-MailMessage function, along with the cmdlets.

This script is capable of sending alerts via email when the service changes.

The Get-PSServiceStatus can only keep track of the last service status polled and notify you when there is a change.

To accomplish this, the script uses a text file.

If a service is down, the code creates the text file with detailed information and sends an alert.

When the service is back up, it deletes the text file.

The following is the overall flow of the function:

  1. Check for a text file and the services.
  2. If there is a text file, it means that the service was not running before.
  3. If the service is not running and there is no text file, create a text file.
  4. Send an email alert saying that the service is down.
  5. If the service is running again, remove the text file.
  6.  Send an email saying that the service is up.

To run the function you’ll need to specify the computer name (remote or local), the service name, and path name where the text files will be stored.

Other important parameters to specify are, the source email and destination email.

For example:

C:> Get-PSServiceStatus -ComputerName test-01, -ServiceName ‘RasMan’ -Path ‘C:PSServiceStatus’ -FromAddress ‘alerts@emailsrv.com’ ‑ToAddress ‘ITadmin@emailsrv.com’ -SmtpServer ‘smtp.domain.com’

Running this script will check the computer [test-01], the service [RasMan], and notify via email and the console if the service is not running.

Download the Source Code:

The Get-PSServiceStatus.ps1 can be downloaded here:
https://github.com/dfranciscus/Get-PSServiceStatus/blob/master/Get-PSServiceStatus.ps1

Other Functions

Below are two other PowerShell functions that can help you monitor Windows services, from the Microsoft web portal TechNet:

  • Check-Svc Function
    Another great script used to monitor Windows Services via PowerShell is Microsoft’s check-Svc. The script finds a stopped service with Get-Service cmdlet, and attempts to restart it. If after the third time, it is unable to start, it will send an alert via email.
  • CheckServices Function
    The Checkservices is another PS script that allows you to monitor the Windows Services of local and remote computers. This script will check the service status and report back in HTML all services that are running or stopped. It will also send an alert via email if the services are stopped.

Scheduling a Task to Run these PowerShell Functions

To automate the monitoring even more, you can use the Microsoft Windows Task Scheduler to automatically launch a PowerShell script, such as Get-PSServiceStatus function, at a certain time or when specific conditions are met.

For example to create a new task called “MonitorServ,” you can run the following command.

C:WindowsSystem32schtasks.exe /create /TN MonitorServ /ST 12:30 /SC DAILY /RI 10 /TR “powershell.exe C: Get-PSServiceStatus”

This newly created Windows Task Schedule will run the Get-PSServiceStatus function daily starting at 12:30 and every 10 minutes.

Final Words & Conclusion

A simple PowerShell script with two cmdlets can help you start a Windows service if it is stopped, much like the built-in Windows Services “Automatic Startup” function.

Throw in a scheduling task and you’ll have a simple polling system.

But when you start to combine it with other functions such as the “Send-MailMessage,” and advanced polling mechanisms such as the one in Get-PSServiceStatus, you can take your Windows Services monitoring to the next level.

Like this post? Please share to your friends:
  • Final fantasy xv windows edition скачать торрент последняя версия
  • Final fantasy xv windows edition скачать торрент на русском
  • Final fantasy xv windows edition скачать торрент xattab
  • Final fantasy xv windows edition системные требования максимальные
  • Final fantasy xv windows edition прохождение на русском