Как перезапустить службу windows с использованием power shell

In this post, I’ll demonstrate using the sc delete Windows command and the Remove-Service PowerShell command to delete a Windows Service.

Step 1. Find the Service Name

Open Windows Services, find the service name, right click and select properties.

Copy the service name.

Как перезапустить службу windows с использованием power shell

Step 2. Run the sc delete command

Как перезапустить службу windows с использованием power shell

Next, run the below command. Replace “servicename” with the service name from Step 1.

sc delete servicename

You should get DeleteService SUCCESS message.

Как перезапустить службу windows с использованием power shell

You might need to reboot the computer for the service to be completely removed.

Как перезапустить службу windows с использованием power shell

That completes the steps for deleting a windows service using the sc command.

How to Delete a Windows Service Using PowerShell

Requirements: You will need to be running at least PowerShell version 6 for this command to work. Refer to the updating PowerShell guide for steps on upgrading PowerShell to the latest version.

Step 1. You will need the service name

Open Windows services and get the service name. If you need to see screenshots see the Windows command line example.

Step 2. Run Remote-Service PowerShell command.

Remove-Service -Name servicename
Как перезапустить службу windows с использованием power shell

Note: I’m not sure why but the PowerShell command removed the service without requiring a reboot. The sc delete command required a reboot. It might depend on the service but just be aware you might need to reboot.

If you liked this post, you might also want to check out:

I have this powershell code already created.
It runs and sends an email with details of each remote machine, service and what seems to be the status.

However the service name and status appear to not function correctly. The output from this script tells me that the service isn’t found. However, I’ve checked this by just running this on the same machine I ran this full script to validate the services are present and identify the status of the actual service;

Get-Service -ComputerName machine1 -Name MyService

My full PowerShell script is below;

# Define the list of machine names where the service should be checked
$machineNames = @("machine1","machine2") # Add more machine names as needed
# Define the service name to check
$serviceName = "MyService"
# Function to check service status on a specific machine
function Get-ServiceStatus {
param ( [string]$machineName, [string]$service
)
$serviceStatus = Get-Service -ComputerName $machineName -Name $service -ErrorAction
SilentlyContinue
if ($serviceStatus) { return $serviceStatus.Status
} else { return "Service Not Found"
}
}
# Initialize an empty array to store information about services that are not running
$notRunningServices = @()
# Check the service status on each machine
foreach ($machine in $machineNames) {
$status = Get-ServiceStatus -machineName $machine -service $serviceName
if ($status -ne "Running") { $notRunningServices += [PSCustomObject]@{ MachineName = $machine ServiceName = $serviceName Status = $status }
}
}
# If there are services not running, send an email
if ($notRunningServices.Count -gt 0) {
$smtpServer = "smtp.server.com"
$smtpPort = 25
$fromAddress = "[email protected]"
$toAddress = "[email protected]"
$emailSubject = "MyService Service Status - Not Running"
$emailBody = "The following services are not running:`r`n`r`n"
foreach ($service in $notRunningServices) { $emailBody += "Server: $($service.MachineName)`r`nService:
$($service.ServiceName)`r`nStatus: $($service.Status)`r`n`r`n"
}
Send-MailMessage -From $fromAddress -To $toAddress -Subject $emailSubject -Body $emailBody -
SmtpServer $smtpServer -Port $smtpPort
}

I need to resolve the powershell script to identify the remote service name on each machine.

A copy of the email is here;

Server: machine1
Service: MyService
Status: Service Not Found


Server: machine2
Service: MyService
Status: Service Not Found

Would really appreciate if someone could please help.

Thanks in advance

The Particular.ServiceControl.Management module can be installed from the PowerShell Gallery, and is used to add, remove, update and delete instances of ServiceControl.

Prerequisites

  • PowerShell (Core) 7.2 or later

Installing and using the PowerShell module

In order to use the PowerShell module, the PowerShell execution policy needs to be set to RemoteSigned. Refer to the PowerShell documentation on how to change the execution policy.

Install-Module -Name Particular.ServiceControl.Management
Import-Module Particular.ServiceControl.Management
Get-Module Particular.ServiceControl.Management | Select-Object -ExpandProperty Version

Powershell Commands

For a complete overview of all cmdlets, see the Cmdlets and Aliases page.

Troubleshooting via PowerShell

The ServiceControl Management PowerShell module offers some cmdlets to assist with troubleshooting the installation of ServiceControl instances.

Check if a port is already in use

Before adding an instance of ServiceControl test if the port to use is currently in use.

Test-IfPortIsAvailable -Port 33333

This example shows the available ports out of a range of ports

33330..33339 | Test-IfPortIsAvailable | ? Available

If the port is already in use, then choose a different port.

Checking and manipulating UrlAcls

The Window HTTPServer API is used by underlying components in ServiceControl. This API uses a permissions system to limit what accounts can add a HTTP listener to a specific URI. The standard mechanism for viewing and manipulating these ports is with the netsh.exe command line tool.

For example netsh.exe http show urlacl will list all of the available UrlAcls. This output is detailed but not easy to query. The ServiceControl Management PowerShell provides simplified PowerShell equivalents for listing, adding, and removing UrlAcls and makes the output easier to query.

Get-UrlAcls | ? Port -eq 33333

In this example any UrlAcl on port 33335 is removed

Get-UrlAcls | ? Port -eq 33335 | Remove-UrlAcl
Add-UrlAcl -Url http://servicecontrol.mycompany.com:33333/api/ -Users Users

PowerShell Service Management: Tips & Tricks for Experts

List of content you will read in this article:

Powershell List Services

  • Step 1: Open PowerShell

Begin by launching PowerShell on your system. Use the Start menu or search bar to find and open the application.

Managing Windows services with PowerShell

Managing Windows services with PowerShell

  • Step 2: Execute the List Services Command

This command fetches and displays a comprehensive list of all services running on your Windows system.

  • Step 3: Review the Service List

After executing the command, review the displayed list of services. Each service is accompanied by essential details such as its display name, service name, and status.

This is a sample of the output you’ll receive.

Status   Name               Display Name

------   ----               -----------

Running  AcrSch2 class="link-id"Svc         Acronis Scheduler2 Service

Running  AdobeUpdateService AdobeUpdateService

Running  afcdpsrv           Acronis Nonstop Backup Service

Running  AGMService         Adobe Genuine Monitor Service

Stopped  AJRouter           AllJoyn Router Service

Stopped  ALG                Application Layer Gateway Service

Stopped  AppIDSvc           Application Identity

Stopped  Appinfo            Application Information

Stopped  AppMgmt            Application Management

Stopped  AppReadiness       App Readiness

Stopped  AppVClient         Microsoft App-V Client

Stopped  AppXSvc            AppX Deployment Service (AppXSVC)

Running  Audiosrv           Windows Audio

Stopped  AxInstSV           ActiveX Installer (AxInstSV)

Stopped  BDESVC             BitLocker Drive Encryption Service

Running  BFE                Base Filtering Engine

In the output, by default, you will see 3 main sections: Status, Name, and Display Name.

Now, if you want to search and list a particular service, you can filter out any parameters.

  • Show all services whose names start with wi:

Get-Service -Name wi*

  • Show all services whose display names start with win:

Get-Service -DisplayName win*

  • Note: If you want to access another computer through the network, you can see the list of services for that system with this command:

Get-Service -ComputerName Server1

An important part of service management is the management of Dependent Services.

Get-Service -Name WinDefend -DependentServices

  • You can also use the Required Services parameter to get a list of service pre-requisites.

Get-Service -Name WinDefend - RequiredServices

So with the above commands, we can find the name of the service we are looking for, see the status and related services or its prerequisites. Now we want to explain the services’ management commands.

Powershell Stop Service

  • Step 1: Open PowerShell

Open PowerShell on your system. You can do this by searching for “PowerShell” in the Start menu and selecting the application.

Managing Windows services with PowerShell

Managing Windows services with PowerShell

  • Step 2: Identify the Service

Determine the name of the service you want to stop. This information is vital for executing the correct PowerShell command.

  • Step 3: Execute the Stop Command

Stop-Service -Name Windefend

Ensure that in every PowerShell service scenario, you begin by opening PowerShell on your system. This can be done by searching for PowerShell in the Start menu and selecting the application. Afterward, identify the service and determine the name of the service you intend to stop. This information is crucial for executing the correct PowerShell command.

Powershell Start Service

  • starting a service in PowerShell you can use this command:

Start-Service -Name Windefend

Powershell Restart Service

  • One of the most commonly used commands to work with services is service restarting in PowerShell command. The structure of the service restarting command is as such:

Restart-Service -Name Windefend

Powershell Suspend Service

Suspend-Service -Name Windefend

Powershell Get Service

Execute the Get Service Command:

Get-Service -Name "YourServiceName"

Replace “YourServiceName” with the actual name of the service you want to retrieve information about.

Windows servers can be run with Powershell, you can manage and run your services in Windows Server with PowerShell.

Before diving into advanced PowerShell tasks, ensure you’re using the latest features and capabilities by verifying your software’s currency. For a quick guide on how to do this, check out our article on Check PowerShell Version to stay up-to-date and make the most of your scripting experience.

restart service powershell

The PowerShell cmdlet Restart-Service provides a simple way to stop and start a service on a local or remote computer. In this article, we will cover the basics of using Restart-Service to restart services in PowerShell. You’ll learn the basic syntax, how to target local or remote services, restart multiple services at once, and even how to script and schedule automated restarts.

Why Should You Use PowerShell to Restart Services?

You might need to restart a service on a computer or server for several reasons. Restarting services is necessary when troubleshooting issues, applying updates, or restarting processes. Doing this manually through the Windows Services console can be time-consuming, especially if you need to restart multiple services across many computers. Some of these reasons include:

1. Service Failure

Services can fail for various reasons, including hardware failure, software bugs, and configuration errors. When a service fails, the system can become unavailable or unstable. Restarting the service can sometimes resolve the problem.

2. Software Updates

When installing software updates on a computer or server, you might need to restart services to ensure the changes take effect.

3. Performance Issues

Services can sometimes consume too much memory or CPU, causing performance issues. Restarting the service can help free up resources and improve system performance.

Understanding the PowerShell Restart-Service cmdlet

The Restart-Service cmdlet is used to restart services in PowerShell. This command can be used to restart services on the local computer or remote computers. Here are the important parameters of the Restart-Service command:

ParameterDescriptionExample Usage
-NameSpecifies the name of the service you want to restart.Restart-Service -Name "ServiceName"
-DisplayNameAllows you to specify the service by its display name instead of its service name.Restart-Service -DisplayName "Display Name"
-ForceRestarts the service and any dependent services.Restart-Service -Name "ServiceName" -Force
-ExcludeExcludes specified services from being restarted, useful when using wildcard characters.Restart-Service -Name * -Exclude "ServiceToExclude"
-IncludeThe -Include parameter of the Restart-Service cmdlet is used to specify an array of service names to include in the operation.Restart-Service -Name 'win*' -Include 'WinRM','Winmgmt'

More info on the syntax and parameters for Restart-Service is here: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/restart-service?view=powershell-7.4

Restarting a Service via the Services Console

  1. Open the Services console by searching for “Services” in the Windows start menu. You can do this by pressing the Windows key + R and typing “services.msc” in the Run dialog box.
    How to Restart a Service
  2. Locate the service you want to restart in the list of services.
  3. Right-click on the service and select “Restart” from the context menu. The service status will change to “Stopping” and then to “Starting” as the service restarts.
    restart service
  4. Alternatively, you can stop the service by selecting “Stop” from the context menu and then start it again by selecting “Start”.

When the restart is complete, the service status will display as “Running”. If you prefer to use the command line, you can use the “net stop” and “net start” commands to stop and start a service, respectively. You can also restart a service through Task Manager >> Services.

Restart-Service -Name <ServiceName>

Replace <ServiceName> with the name of the service you want to restart. For example, to restart the Print Spooler service, type:

Restart-Service -Name Spooler -PassThru

This will restart the Print Spooler service on the local computer. Here, -Name specifies the name of the service that you want to restart. The service name is different from the display name, which is generally what you see in the services manager. To specify a service by its display name, use the -displayname parameter. The -PassThru parameter waits until the service is restarted and displays its running status.

How to Restart a service in PowerShell

Alternatively, You can use Get-Service to find the service name and pipeline the service object to the Restart-Service cmdlet.

Get-Service Spooler | Restart-Service
PowerShell Restart-service

Please note that the services can be started only if the start type is set to automatic, manual, and automatic (delayed start). You can’t start the service if it’s disabled. You can change the startup type of the service using:

Set-Service -Name "Service Name" -StartupType Automatic

Use -Force Parameter to Immediately Restart a Service

By default, Restart-Service sends a stop message and waits for the service to enter the stopped state before restarting. This helps ensure proper restart but can take more time. You can use the -Force parameter to immediately restart the service after sending a stop message to the Windows service manager:

Restart-Service -Name Spooler -Force

This bypasses the waiting and restarts the service as soon as possible. Use -Force when you need to quickly restart a service.

How do you identify the name of the service you want to restart?

Not sure about the name of the service you need to restart? Use the Get-Service cmdlet to find it. This will return an object representing each service, helping you identify them by their service name or display name of the services. Just open the PowerShell console and type Get-Service to list all services:

Get-Service

Apart from the Name column from the above cmdlet, You can also get the service name from the services console:

get service name

You can use wildcards to get multiple services. Say, for example, let’s find all the services on the computer (starting with “Samsung Mobile”) and restart any that are stopped:

Get-service -DisplayName "Samsung*" | where {$_.Status -eq "Stopped"} | Restart-Service

You can also filter services by their other properties using the Where-object cmdlet:

Get-Service | Where-Object {$_.Name -like "*print*"} | Restart-Service

Stop and Start Windows Service using PowerShell

Here is how to stop and start Windows services using PowerShell:

Stop a Windows Service

To stop a service, you use the Stop-Service cmdlet. Specify the service name or display name using the -Name parameter:

Stop-Service -Name "Spooler"

This sends a stop message to the Windows Service controller. You can also pipe the Get-Service to stop or start a service. E.g.,

Get-Service -Name 'ServiceName' | Stop-Service

Alternatively, You can use the InputObject parameter as:

#Get the specific service
$Service = Get-service -DisplayName "Print Spooler"
#Stop the service
Stop-Service -InputObject $Service -Verbose

Start a Windows Service

To start a service, you use the Start-Service cmdlet, again specifying the service name with -Name:

Start-Service -Name "Spooler"

This sends a start message to restart the service. You can check the status using Get-Service to confirm it stopped:

Get-Service -Name Spooler

Stop/Start Multiple Services

You can target multiple services using an array:

$services = @("Spooler", "Wsearch")
Restart-Service -Name $services

This provides an easy way to stop and start multiple Windows services with PowerShell.

Restarting Services with PowerShell on Remote Computer

#Enter into a new session
$Session = New-PSsession -Computername "RemoteComputer"
#Execute PowerShell script remotely
Invoke-Command -Session $Session -ScriptBlock {Restart-Service "webClient"}
#Disconnect the Session
Remove-PSSession $Session

Remote PowerShell Execution – Requirements

Please note, that the PowerShell remoting has below requirements:

  • WinRM: The Windows Remote Management (WinRM) service must be running on the remote computer and properly configured to allow remote connections. You can configure it by running winrm quickconfig on the remote computer.
  • Firewall: Make sure the firewall allows for WinRM traffic (usually HTTP over port 5985 or HTTPS over port 5986).
  • Permissions: Make sure you have the necessary permission to run commands on the remote computer. You might need administrative privileges, depending on what you’re trying to do.
  • Network: Both the local and remote computers must be reachable over the network.

PowerShell Script to Restart Services on Multiple Computers

You can also use a PowerShell script to restart services on multiple computers. The script can be used to restart services on a list of computers or on all computers in a domain. Here is an example script that restarts the Print Spooler service on a list of computers:

$Computers = Get-Content "C:\temp\computers.txt"
$ServiceName = "Spooler"
foreach ($Computer in $Computers)
{ Write-Host "Restarting service on $Computer" Invoke-Command -ComputerName 'RemoteServerName' -ScriptBlock { Restart-Service -Name $ServiceName -Force }
}

In this script, the Get-Content cmdlet reads a list of computer names from a file, and the foreach loop restarts the Print Spooler service on each computer.

Restarting IIS Services with PowerShell

Restart-Service -Name W3SVC
Invoke-Command -ComputerName 'RemoteServerName' -ScriptBlock { iisreset
} -Credential (Get-Credential)

Restarting a Specific Website Remotely

If you want to restart a specific website on a remote computer, you can use Invoke-Command to run the necessary cmdlets.

Invoke-Command -ComputerName 'RemoteServerName' -ScriptBlock { Import-Module WebAdministration Stop-WebSite -Name 'Default Web Site' Start-WebSite -Name 'Default Web Site'
}

How to Restart Multiple Services using PowerShell?

While individual cmdlets are powerful, a PowerShell script can help you perform more complex tasks like restarting multiple services in a specific order. You can create a script to restart services based on custom conditions and even apply it to multiple computers.

Having to restart services one by one can become tedious. Luckily, Restart-Service makes it easy to restart multiple services at the same time.

You have a few different options for restarting multiple services:

  • Use wildcards: The -Name parameter accepts wildcard characters to target multiple services. For example:
Restart-Service -Name *print*

Input object: You can pipe a collection of services from Get-Service to target multiple services:

Get-Service | Where-Object {$_.Name -like "*print*"} | Restart-Service

Specify service names: You can provide a comma-separated list of services:

Restart-Service Spooler,Wsearch

This provides flexibility for restarting groups of related services.

PowerShell to Restart multiple services if they are in the stopped state

To restart multiple services only if they are stopped, you can use PowerShell to first check the status of each service. If a service is stopped, you can restart it. Here’s how you can do this:

# Define an array of service names you want to restart
$serviceNames = @('seclogon', 'WAS', 'TermService')
# Loop through each service name in the array
Try { ForEach ($ServiceName in $serviceNames) { # Retrieve the current status of the service $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue # Check if the service exists if ($service -ne $null) { # Check if the service is stopped if ($service.Status -eq 'Stopped') { # Restart the service Restart-Service -Name $serviceName -ErrorAction Stop Write-Host -f Yellow "Restared the service $serviceName because it was stopped" } else { # Output the current status of the service Write-Host -f Green "Service $serviceName is currently $($service.Status)" } } else { Write-Host -f Yellow "Service $ServiceName does not exist!" } }
}
catch { Write-Host -f Red "An error occurred: $_"
}

How to Schedule Restarting Services?

You can easily create PowerShell scripts to automate restarting Windows services. This allows you to schedule restart tasks using tools like Windows Task Scheduler.

Here is an example script that restarts two services every day at 1 AM:

# Daily service restart script
$services = @("Spooler","Wsearch")
foreach ($service in $services) { Restart-Service -Name $service -Force
}

Save this script as Restart-Services.ps1 and call it from Task Scheduler. This automates the task!

Best Practices for Restarting Services with PowerShell

1. Verify Service Name and Status

Before restarting a service, verify the service name to ensure you restart the correct service. Check the current status of the service using Get-Service. Make sure the service has not been stopped before trying to restart it.

2. Stop Dependent Services

If a service has dependent services, stop the dependent services before restarting the main service.

3. Check the Service Status

After restarting a service, check the service status to ensure that it is running.

4. Test Service Functionality

Test the service functionality after restarting to ensure that it is working as expected.

5. Error Handling

try { Restart-Service -Name 'ServiceName' -ErrorAction Stop
}
catch { Write-Host "An error occurred: $_"
}

Troubleshooting Common Issues with Service Restart

Sometimes, restarting services with PowerShell can encounter errors. Here are some common issues and their solutions:

  1. Access Denied – If you get an access denied error when restarting a service, ensure you have administrative credentials on the local or remote computer.
  2. Service Not Found: If you get a service not found error, verify that you have entered the correct service name.
  3. Service Dependencies: If a service has dependent services, stop the dependent services before restarting the main service.
  4. PowerShell Version: Ensure you are using the latest version of PowerShell to avoid compatibility issues.
  5. Verify that the service name is spelled correctly.
  6. Ensure that the remote computer is accessible and that you have the necessary network permissions.
  7. Check the event logs for any error messages related to the service restart failure.

Tail: How to Create a New Service and delete existing services using PowerShell?

PowerShell provides some more cmdlets for efficient service management. You can provision new services and remove existing services through PowerShell. Here is a quick example:

#Create a New service to Execute PowerShell script
New-Service -name SiteBackupScript -binaryPathName "C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -File C:\Scripts\BackupScript.ps1"
#Delete existing service
(Get-WmiObject win32_service -Filter "name='SiteBackupScript'").delete()
#From PowerShell 6 onwards, You can use:
Remove-Service -Name "SiteBackupScript"

Conclusion and Next Steps

Restarting Windows services is a common task required for managing servers and workstations. However, doing this manually through the Services console is slow and tedious. The Restart-Service cmdlet in PowerShell provides a quick, flexible method for restarting services. This comprehensive guide has explored how to restart services with PowerShell. We have covered various scenarios, including restarting services on the local and remote computers, using scripts to restart services, and restarting IIS services.

How do I restart a service using PowerShell?

How can I restart a service on a remote computer?

Can I restart multiple services at once using PowerShell?

How can I check if a service was successfully restarted?

Can I restart a service using the service’s display name instead of its service name?

What if the service does not stop and start within a reasonable time?

If a service does not stop or start within a reasonable time, you may need to investigate further to understand the issue. You can use the Stop-Service and Start-Service cmdlets separately to have more control over the process:
Stop-Service -Name "ServiceName"
Start-Service -Name "ServiceName"

How do I restart a service from the command line?

To restart a Windows service from the command line, you can use the net command:
Stop the service with: net stop <service_name>
Start the service with: net start <service_name>

How do I stop a service?

How do I stop and disable a service?

To disable a service, you can use the Set-Service cmdlet with the -StartupType parameter set to “Disabled” after stopping the service. For example: Set-Service -Name "SERVICE-NAME" -StartupType Disabled

How do I check if a Service is running in PowerShell?

To check if a service is running in PowerShell, use the Get-Process cmdlet. For example: $Drive = Get-Process -Name "GoogleDriveFS" -ErrorAction SilentlyContinue

Vivekjainmaiet

Automation with PowerShell to manage Windows services

Introduction

Windows services play a vital role in the functionality of your system. Managing these services efficiently is crucial for maintaining system stability and performance. In this guide, we’ll explore how to use PowerShell to manage Windows services effortlessly.

Prerequisites

Before you dive in, make sure you have a basic understanding of PowerShell and Windows operating systems.

  1. Understanding Windows Services:

2. PowerShell and Windows Services:

PowerShell provides a versatile platform for managing Windows services. Its automation capabilities allow you to streamline service-related tasks with ease.

3. Retrieving Service Information: Get-Service Cmdlet:

4. Starting and Stopping Services:

To start a service, use the Start-Service cmdlet:

Start-Service -Name "serviceName"

Similarly, you can stop a service using the Stop-Service cmdlet.

Stop-Service -Name "serviceName"

Note :- Replace “serviceName” with the actual name of the service you want to start or stop.

5. Restarting Services:

Restarting a service involves stopping and then starting it. Combine the previous two commands:

Stop-Service -Name "serviceName"
Start-Service -Name "serviceName"
Restart-Service -Name "serviceName"

6. Filtering Services: Where-Object:

Filter services based on criteria using the Where-Object cmdlet. For example, to list only running services:

7. Managing Multiple Services: Loop Through Services:

8. Error Handling and Verbose Output: Try-Catch:

9. Practical Example: Monitoring and Managing a Service:

Conclusion

Congratulations! You’ve learned how to manage Windows services using PowerShell. This newfound skill will save you time and effort in maintaining your system’s health.

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, and others.

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.

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.

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.”

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.

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.

C:\Windows\System32\schtasks.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.

Monitor Windows Services via PowerShell FAQs

Can I use PowerShell to monitor services on remote computers?

You can use PowerShell to monitor services on remote computers by specifying the computer name when running the cmdlets. For example, you can use the “-ComputerName” parameter with the “Get-Service” cmdlet to view the status of a specific service or all services on a remote computer.

Can I schedule a PowerShell script to monitor services regularly?

Yes, you can use the “Scheduled Tasks” feature in Windows or use 3rd party software to schedule a PowerShell script to run regularly. The script could include commands to check the status of specific services, and then send an email or generate a log file if the status of service changes.

Can I filter or sort the services that are displayed by the “Get-Service” cmdlet?

Yes, you can use the “-Name” parameter to filter the services displayed by name and use the “-Status” to filter the services displayed by status. You can use the “-Sort” parameter to sort the services based on properties such as name, status, and start mode.

:/>  Активация windows 7 через командную строку kms