How to Restart a Service with PowerShell: A Step-by-Step Guide

As IT professionals and Managed Service Providers (MSPs), the task of managing and optimizing system services is an integral part of our roles. PowerShell, a robust scripting language, provides an efficient way to perform these tasks. It enables task automation, simplifies complex operations with just a few lines of code, and facilitates services management on multiple machines simultaneously.

The Script


<#
.SYNOPSIS
    Restart one or more services.
.DESCRIPTION
    Restart one or more services. This also try three more times to get the service(s) to start, all the while waiting 15 seconds between each attempt.
.EXAMPLE
     -Name "ServiceName"
    Restarts a service with the name ServiceName
.EXAMPLE
     -Name "ServiceName","AnotherServiceName" -WaitTimeInSecs 15
    Restarts two services with the names ServiceName and AnotherServiceName and waits 15 Seconds for them all to start
.EXAMPLE
    PS C:> Restart-Service.ps1 -Name "ServiceName"
    Restarts a service with the name ServiceName
.EXAMPLE
    PS C:> Restart-Service.ps1 -Name "ServiceName","AnotherServiceName" -WaitTimeInSecs 15
    Restarts two services with the names ServiceName and AnotherServiceName and waits 15 Seconds for them all to start
.NOTES
    Exit Code 0: All service(s) restarted
    Exit Code 1: Some or all service(s) failed to restart
    Release Notes:
    Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>
[CmdletBinding()]
param (
    # Name of service(s), either Name or DisplayName from Get-Service cmdlet
    [Parameter(Mandatory = $true)]
    [String[]]
    $Name,
    # The number of attempts to restart the service before giving up
    [Parameter()]
    [int]
    $Attempts = 3,
    # Duration in Seconds to wait for service(s) to start between each attempt
    [Parameter()]
    [int]
    $WaitTimeInSecs = 15
)

begin {
    function Test-Service {
        [CmdletBinding()]
        param (
            [Parameter()]
            [String[]]
            $Services
        )
        if ((Get-Service | Where-Object { ($_.Name -in $Services -or $_.DisplayName -in $Services) -and $_.Status -like "Running" }).Count -gt 0) {
            $true
        }
        else {
            $false
        }
    }
    $FailedToStart = 0
}
process {
    # Get service(s)
    $Services = Get-Service | Where-Object { $_.Name -in $Name -or $_.DisplayName -in $Name }
    if ($Services.Count -eq 0) {
        Write-Error "No service(s) found."
        exit 1
    }

    # Restart service(s)
    $Services | ForEach-Object {
        $AttemptCounter = $Attempts
        # Restart the service
        $Service = $_ | Restart-Service -PassThru
        # Wait till status of service reaches Running, timeout after $WaitTimeInSecs seconds
        $Service.WaitForStatus([System.ServiceProcess.ServiceControllerStatus]::Running, [timespan]::FromSeconds($WaitTimeInSecs)) | Out-Null
        # Loop till either the service is in a running state or our $AttemptCounter reaches 0 or less
        while ($(Get-Service -Name $Service.ServiceName).Status -ne [System.ServiceProcess.ServiceControllerStatus]::Running -or $AttemptCounter -le 0) {
            # Start service
            Start-Service -Name $Service.ServiceName
            # Wait $WaitTimeInSecs seconds
            Start-Sleep -Seconds $WaitTimeInSecs
            $AttemptCounter = $AttemptCounter - 1
        }
        if ($((Get-Service -Name $Service.ServiceName).Status -ne [System.ServiceProcess.ServiceControllerStatus]::Running)) {
            # Add 1 to later show the count of services that failed to reach the running state
            $FailedToStart = $FailedToStart + 1
            Write-Error -Message "Failed to start service( $($Service.ServiceName) ) after $Attempts attempts."
        }
    }

    # Print out services with their status
    Get-Service | Where-Object { $_.Name -in $Name -or $_.DisplayName -in $Name }

    # Check if service(s) have started
    if ($FailedToStart -eq 0) {
        # All service(s) have been restarted
        Write-Host "All Service(s) restarted."
        exit 0
    }
    else {
        # Some or all Service(s) failed to restart
        Write-Error -Message "Failed to start $FailedToStart service(s)."
        exit 1
    }
}
end {}

 

Access over 300+ scripts in the NinjaOne Dojo

Get Access

Exploring the Restart-Service Cmdlet

The `Restart-Service` cmdlet in PowerShell is a powerful tool that allows you to restart a service on a local or a remote computer. This command consolidates the processes of stopping and starting a service, simplifying service management.

Extending the Use of Our Restart-Service Script

Our PowerShell script, designed to leverage the `Restart-Service` cmdlet, provides a comprehensive solution for restarting one or more services. This script, apart from restarting a service, also makes three attempts to start a service if it doesn’t initialize immediately, incorporating a 15-second pause between each attempt

Applications of the Script

Our Restart-Service script is not only handy for immediate service restarts but can also be used in various scenarios, such as:

Scheduled Restarts

You can use Task Scheduler in conjunction with our script to restart services on a schedule. This can be beneficial for services that need periodic restarts to free up resources or maintain optimal performance.

Post-Update Restarts

After a system update, some services may need to be restarted. Our script can be used in a post-update script to ensure all necessary services are restarted and running correctly.

Troubleshooting the Script

Despite the robustness of PowerShell scripts, there can be instances when things don’t go as planned. Here are some ways to troubleshoot issues with our Restart-Service script:

Error Logs
PowerShell provides detailed error logs that can be used to troubleshoot issues. If our script fails to restart a service, check the error logs for any error messages or exceptions that can provide insights into what went wrong.

Debugging the Script
PowerShell provides debugging features that can be used to step through the script and identify where the issue is occurring. Use the `Set-PSDebug -Trace 1` command to enable script tracing, and then run the script to see a line-by-line display of the commands being executed.

Final Thoughts

In conclusion, PowerShell provides a dynamic and efficient platform for managing services on Windows systems. With our PowerShell script, you can automate service restarts, perform complex operations with minimal code, and manage services across multiple systems. Stay tuned for more insights on leveraging PowerShell for efficient IT operations.

With NinjaOne’s comprehensive IT operations management platform, you can integrate and scale the use of custom scripts like our PowerShell service restart script across numerous endpoints. The platform’s capability to deploy and manage scripts centrally makes executing complex tasks across multiple devices seamless. This means you can use our script to manage services across your entire network, from a single dashboard, enhancing efficiency and ensuring consistency in your IT operations.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).