Learning and Sharing
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
No Result
View All Result

#8 PowerShell Learning: Manage Services using PowerShell

August 11, 2023
in Blog, PowerShell Learning
0
ADVERTISEMENT

Table of Contents

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 C:\> Get-Command -Noun 'service'

CommandType Name            Version Source
----------- ----            ------- ------
Cmdlet      Get-Service     3.1.0.0 Microsoft.PowerShell.Management
Cmdlet      New-Service     3.1.0.0 Microsoft.PowerShell.Management
Cmdlet      Restart-Service 3.1.0.0 Microsoft.PowerShell.Management
Cmdlet      Resume-Service  3.1.0.0 Microsoft.PowerShell.Management
Cmdlet      Set-Service     3.1.0.0 Microsoft.PowerShell.Management
Cmdlet      Start-Service   3.1.0.0 Microsoft.PowerShell.Management
Cmdlet      Stop-Service    3.1.0.0 Microsoft.PowerShell.Management
Cmdlet      Suspend-Service 3.1.0.0 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 C:\> Get-Service

Status   Name               DisplayName
------   ----               -----------
Stopped  AarSvc_c2fc5c      Agent Activation Runtime_c2fc5c
Running  AdobeARMservice    Adobe Acrobat Update Service
Running  AdobeUpdateService AdobeUpdateService
Running  AGMService         Adobe Genuine Software Monitor Service
Stopped  AJRouter           AllJoyn Router Service
Stopped  ALG                Application Layer Gateway Service
Running  AnyDesk            AnyDesk Service
Stopped  AppIDSvc           Application Identity
Running  Appinfo            Application Information

#[Output Trimed]

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 C:\> Get-Service | Format-List

Name                : AarSvc_c2fc5c
DisplayName         : Agent Activation Runtime_c2fc5c
Status              : Stopped
DependentServices   : {}
ServicesDependedOn  : {}
CanPauseAndContinue : False
CanShutdown         : False
CanStop             : False
ServiceType         : 224

#[Output Trimed]

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 all services with 3 properties (Name, DisplayName, Status) in List format.

PS C:\> Get-Service | Format-List -Property Name, DisplayName, Status

Name        : AarSvc_c2fc5c
DisplayName : Agent Activation Runtime_c2fc5c
Status      : Stopped

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

#[Output Trimed]

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

PS C:\> Get-Service "Windows Update" | Format-List

Name                : wuauserv
DisplayName         : Windows Update
Status              : Stopped
DependentServices   : {}
ServicesDependedOn  : {rpcss}
CanPauseAndContinue : False
CanShutdown         : False
CanStop             : False
ServiceType         : Win32OwnProcess, Win32ShareProcess

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 C:\> Get-Service -DisplayName *microsoft*

Status   Name               DisplayName
------   ----               -----------
Stopped  AppVClient         Microsoft App-V Client
Running  ClickToRunSvc      Microsoft Office Click-to-Run Service
Stopped  cloudidsvc         Microsoft Cloud Identity Service
Stopped  diagnosticshub.... Microsoft (R) Diagnostics Hub Stand...
Stopped  edgeupdate         Microsoft Edge Update Service (edge...
Stopped  edgeupdatem        Microsoft Edge Update Service (edge...
Running  InstallService     Microsoft Store Install Service
Stopped  MicrosoftEdgeEl... Microsoft Edge Elevation Service (M...
Stopped  MSiSCSI            Microsoft iSCSI Initiator Service

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 C:\> 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 desiredStat...
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;}
StartType                 Property      System.ServiceProcess.ServiceStartMode StartType {get;}
Status                    Property      System.ServiceProcess.ServiceControllerStatus Status {get;}
ToString                  ScriptMethod  System.Object ToString();

The following example illustrates how we can Sort the output based on a property. The -AutoSize parameter produces more sensible column widths.

PS C:\> gsv | Sort-Object -Property 'ServiceType' | FT Name, ServiceType, Status, CanStop -AutoSize

Name                                      ServiceType  Status CanStop -AutoSize
----                                      -----------  ------ -------
AGMService                            Win32OwnProcess Running    True
AnyDesk                               Win32OwnProcess Running    True
ALG                                   Win32OwnProcess Stopped   False
AdobeUpdateService                    Win32OwnProcess Running    True
AdobeARMservice                       Win32OwnProcess Running    True
AppIDSvc                            Win32ShareProcess Stopped   False
AJRouter                            Win32ShareProcess Stopped   False
AppMgmt                             Win32ShareProcess Stopped   False
Appinfo            Win32OwnProcess, Win32ShareProcess Running    True
AarSvc_c2fc5c                                     224 Stopped   False

PS C:\> gsv | Sort-Object -Property 'Name' | FT Name, ServiceType, Status, CanStop -AutoSize

Name                                      ServiceType  Status CanStop -AutoSize
----                                      -----------  ------ -------
AarSvc_c2fc5c                                     224 Stopped   False
AdobeARMservice                       Win32OwnProcess Running    True
AdobeUpdateService                    Win32OwnProcess Running    True
AGMService                            Win32OwnProcess Running    True
AJRouter                            Win32ShareProcess Stopped   False
ALG                                   Win32OwnProcess Stopped   False
AnyDesk                               Win32OwnProcess Running    True
AppIDSvc                            Win32ShareProcess Stopped   False
Appinfo            Win32OwnProcess, Win32ShareProcess Running    True
AppMgmt                             Win32ShareProcess Stopped   False

PS C:\> gsv | Sort-Object -Property 'Status' | FT Name, ServiceType, Status, CanStop -AutoSize

Name                                      ServiceType  Status CanStop -AutoSize
----                                      -----------  ------ -------
ALG                                   Win32OwnProcess Stopped   False
AJRouter                            Win32ShareProcess Stopped   False
AppMgmt                             Win32ShareProcess Stopped   False
AppIDSvc                            Win32ShareProcess Stopped   False
AarSvc_c2fc5c                                     224 Stopped   False
Appinfo            Win32OwnProcess, Win32ShareProcess Running    True
AGMService                            Win32OwnProcess Running    True
AdobeARMservice                       Win32OwnProcess Running    True
AdobeUpdateService                    Win32OwnProcess Running    True
AnyDesk                               Win32OwnProcess Running    True

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.

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

Status   Name               DisplayName
------   ----               -----------
Stopped  AarSvc_c2fc5c      Agent Activation Runtime_c2fc5c
Stopped  AJRouter           AllJoyn Router Service
Stopped  ALG                Application Layer Gateway Service
Stopped  AppIDSvc           Application Identity
Stopped  AppMgmt            Application Management
Stopped  AppReadiness       App Readiness
Stopped  AppVClient         Microsoft App-V Client
Stopped  AssignedAccessM... AssignedAccessManager Service

PS C:\> (Get-Service | Where-Object {$_.Status -eq "Stopped"}).Count
174      #Coounting the number of services have been stopped.

Take careful note of the syntax:

  • The Where-Object (alias: ? -> Where-Object) is enclosed within curly braces.
  • 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 C:\> Get-Service | Where-Object {$_.Status -eq "Running"}

Status   Name               DisplayName
------   ----               -----------
Running  AdobeARMservice    Adobe Acrobat Update Service
Running  AdobeUpdateService AdobeUpdateService
Running  AGMService         Adobe Genuine Software Monitor Service
Running  AnyDesk            AnyDesk Service
Running  Appinfo            Application Information
Running  AudioEndpointBu... Windows Audio Endpoint Builder
...

PS C:\> (Get-Service | Where-Object {$_.Status -eq "Running"}).Count
142      #Counting the number of services have been running.

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 .NetFramework methods. So, you can run Get-Service cmdlet against any remote computer which does not have PowerShell remoting configured.

PS C:\ Get-Service -ComputerName DC01

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

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.

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 C:\> Get-Service | Where-Object {$_.Status -eq "Stopped"} | Out-File "D:\Stopped_services.txt"
PS C:\> Get-Content "D:\Stopped_services.txt"

Status   Name               DisplayName
------   ----               -----------
Stopped  AarSvc_c2fc5c      Agent Activation Runtime_c2fc5c
Stopped  AJRouter           AllJoyn Router Service
Stopped  ALG                Application Layer Gateway Service
Stopped  AppIDSvc           Application Identity
Stopped  AppMgmt            Application Management
Stopped  AppReadiness       App Readiness

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 C:\> gsv wuauserv

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

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

PS C:\> Get-Service wuauserv

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

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.

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 C:\> Start-Service wuauserv -Verbose
VERBOSE: Performing the operation "Start-Service" on target "Windows Update (wuauserv)".

Stop a Windows Service

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

PS C:\> Stop-Service wuauserv ; Get-Service wuauserv

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

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.

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 C:\> Get-Service | Where-Object {$_.Status -eq 'Running' -and $_.CanStop}

Status   Name               DisplayName
------   ----               -----------
Running  AdobeARMservice    Adobe Acrobat Update Service
Running  AdobeUpdateService AdobeUpdateService
Running  AGMService         Adobe Genuine Software Monitor Service
Running  AnyDesk            AnyDesk Service
Running  Appinfo            Application Information

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

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

Status   Name               DisplayName
------   ----               -----------
Running  BrokerInfrastru... Background Tasks Infrastructure Ser...
Running  CoreMessagingRe... CoreMessaging
Running  DcomLaunch         DCOM Server Process Launcher
Running  Dnscache           DNS Client
Running  EFS                Encrypting File System (EFS)
Running  LSM                Local Session Manager
Running  mpssvc             Windows Defender Firewall
Running  Power              Power
Running  RpcEptMapper       RPC Endpoint Mapper
Running  RpcSs              Remote Procedure Call (RPC)
Running  SamSs              Security Accounts Manager
Running  SecurityHealthS... Windows Security Service
Running  SgrmBroker         System Guard Runtime Monitor Broker
Running  TextInputManage... Text Input Management Service
Running  WinHttpAutoProx... WinHTTP Web Proxy Auto-Discovery Se...

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

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

Status   Name               DisplayName
------   ----               -----------
Running  BrokerInfrastru... Background Tasks Infrastructure Ser...
Running  CoreMessagingRe... CoreMessaging
Running  DcomLaunch         DCOM Server Process Launcher
Running  Dnscache           DNS Client
Running  EFS                Encrypting File System (EFS)
Running  LSM                Local Session Manager
Running  mpssvc             Windows Defender Firewall
Running  Power              Power
Running  RpcEptMapper       RPC Endpoint Mapper
Running  RpcSs              Remote Procedure Call (RPC)
Running  SamSs              Security Accounts Manager
Running  SecurityHealthS... Windows Security Service
Running  SgrmBroker         System Guard Runtime Monitor Broker
Running  TextInputManage... Text Input Management Service
Running  WinHttpAutoProx... WinHTTP Web Proxy Auto-Discovery Se...

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 C:\> 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 C:\> Get-Service | Where-Object {$_.CanPauseAndContinue}

Status   Name               DisplayName
------   ----               -----------
Running  igccservice        Intel(R) Graphics Command Center Se...
Running  LanmanWorkstation  Workstation
Running  NetTcpPortSharing  Net.Tcp Port Sharing Service
Running  seclogon           Secondary Logon
Running  simptcp            Simple TCP/IP Services
Running  StiSvc             Windows Image Acquisition (WIA)
Running  webthreatdefsvc    Web Threat Defense Service
Running  webthreatdefuse... Web Threat Defense User Service_c2fc5c
Running  WerSvc             Windows Error Reporting Service
Running  Winmgmt            Windows Management Instrumentation

To Suspend (pause) the Workstation service on computer, use the following command with -Name or -Displayname parameter.

PS C:\> Suspend-Service -DisplayName Workstation
PS C:\> Suspend-Service -Name LanmanWorkstation

Now the status service changed to Paused.

PS C:\> Get-Service LanmanWorkstation

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

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

Resume-Service -DisplayName Workstation

Change the Service StartMode

Sometimes 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 C:\> 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         : Win32OwnProcess, Win32ShareProcess
StartType           : Manual
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 C:\> Get-WmiObject -Class Win32_Service

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

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

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 C:\> Get-WmiObject -Class Win32_Service | FT -Property State, Name, StartMode, Displayname

State   Name                        StartMode Displayname
-----   ----                        --------- -----------
Running AdobeARMservice             Auto      Adobe Acrobat Update Service
Running AdobeUpdateService          Auto      AdobeUpdateService
Running AGMService                  Auto      Adobe Genuine Software Monitor Service
Stopped AJRouter                    Manual    AllJoyn Router Service
Stopped ALG                         Manual    Application Layer Gateway Service
Running AnyDesk                     Auto      AnyDesk Service

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

PS C:\> Get-WmiObject -Class Win32_Service | Where-Object {$_.Name -eq 'wuauserv'}

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

PS C:\> (Get-WmiObject -Class Win32_Service | Where-Object {$_.Name -eq 'wuauserv'}).StartMode
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 C:\> Set-Service -Name wuauserv -StartupType 'Automatic'
PS C:\> Start-Service -Name wuauserv
PS C:\> Get-WmiObject -Class Win32_Service | Where-Object {$_.Name -eq 'wuauserv'}

ExitCode  : 0
Name      : wuauserv
ProcessId : 0
StartMode : Auto
State     : Stopped
Status    : OK

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:

A single long command with the pipeline notation can be brake to multiple lines.

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

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-Service cmdlet with the help of –PassThru parameter. Ultimately, the selected services will be started. You can use the same idea to stop running services.

718okn70QWEqYG0o6453qOvql6K5U1vbl1jBYKvT2kC5RmzEWPe8oNio6zlg

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.

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

Get-Service | ? {$_.DisplayName -like "*tftp*"}

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

Note Tip: A long command can be break to multiple lines with ` notation.
New-Service `
  -Name TFTPServer `
  -BinaryPathName "C:\TFTP\tftpd32.exe" `
  -DisplayName "TFTP Server" `
  -Description "Open Source TFTP Server" `
  -StartupType Manual

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

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?

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.

$svc = Get-WmiObject Win32_Service -Filter "Name='TFTPServer'"

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

PS C:\> $svc

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

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 C:\> Get-Member -InputObject $svc -MemberType Method

   TypeName: System.Management.ManagementObject#root\cimv2\Win32_Service

Name                  MemberType Definition
----                  ---------- ----------
Change                Method     System.Management.ManagementBaseObject Change(System.String DisplayName...
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()

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 C:\> $svc.delete()

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

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

PS C:\> 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 C:\> (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.

5/5 - (1 vote)
Previous Post

#7 PowerShell Learning: Windows PowerShell ISE

Next Post

#9 PowerShell Learning: Manage Processes using PowerShell

Related Posts

Running Hyper-V and VMware Workstation on The Same Machine

August 15, 2024

How to Uninstall All Autodesk Products At Once Silently

July 29, 2024
Ftr5

How to Uninstall the Autodesk Genuine Service on Windows

July 29, 2024
Ftr19

How to Fix Windows Cannot Read the ProductKey From the Unattend Answer File in VirtualBox

July 26, 2024
Ftr25

How to Update Windows Terminal in Windows 10/11

July 26, 2024

How to Disable The Beep Sound in WSL Terminal on Windows

July 26, 2024

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • How To Turn On uBlock Origin Extension in Chrome (2025)
  • Images Hidden Due To Mature Content Settings In CivitAI
  • Azure OpenAI vs Azure AI Hub, How to Choose the Right One for Your Needs

Categories

Stay in Touch

Discord Server

Join the Discord server with the site members for all questions and discussions.

Telegram Community

Jump in Telegram server. Ask questions and discuss everything with the site members.

Youtube Channel

Watch more videos, learning and sharing with Leo ❤❤❤. Sharing to be better.

Newsletter

Join the movement and receive our weekly Tech related newsletter. It’s Free.

General

Microsoft Windows

Microsoft Office

VMware

VirtualBox

Technology

PowerShell

Microsoft 365

Microsoft Teams

Email Servers

Copyright 2025 © All rights Reserved. Design by Leo with ❤

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory