PowerShell – Restart Service – Local or Remote Machines

This post is to start the services of local or remote computers. It also check for all its dependent services.  The script works on below logic

  • Service status is Running

The script will stop the dependent services ,stop the main service , start the dependent service and then start the main service.

  • Service status is stopped 

Start the dependent service and start the main service

I’ve tested this script by executing it on SQL Services(both default and Named instance). Please do a thorough testing before executing it across production. The different ways of executing it is shown below. You can customize this script as per your requirement.

The step by step details are given below

Code Details –

********************************************************************************

Function Restart-Service
{
PARAM([STRING]$SERVERNAME=$ENV:COMPUTERNAME,[STRING]$SERVICENAME)
#Default instance – MSSQLSERVER  ,
#Named instance is MSSQL$KAT – Try to retain its value by negating “$” meaning using “`
#hence you need to pass service name like MSSQL`$KAT
$SERVICE = GET-SERVICE -COMPUTERNAME $SERVERNAME -NAME $SERVICENAME -ERRORACTION SILENTLYCONTINUE
IF( $SERVICE.STATUS -EQ “RUNNING” )
{
$DEPSERVICES = GET-SERVICE -COMPUTERNAME $SERVERNAME -Name $SERVICE.SERVICENAME -DEPENDENTSERVICES | WHERE-OBJECT {$_.STATUS -EQ “RUNNING”}
IF( $DEPSERVICES -NE $NULL )
{
FOREACH($DEPSERVICE IN $DEPSERVICES)
{
Stop-Service -InputObject (Get-Service -ComputerName $SERVERNAME -Name $DEPSERVICES.ServiceName)
}
}
Stop-Service -InputObject (Get-Service -ComputerName $SERVERNAME -Name $SERVICE.SERVICENAME) -Force
if($?)
{
Start-Service -InputObject (Get-Service -ComputerName $SERVERNAME -Name $SERVICE.SERVICENAME)
$DEPSERVICES = GET-SERVICE -COMPUTERNAME $SERVERNAME -NAME $SERVICE.SERVICENAME -DEPENDENTSERVICES | WHERE-OBJECT {$_.STATUS -EQ “STOPPED”}
IF( $DEPSERVICES -NE $NULL )
{
FOREACH($DEPSERVICE IN $DEPSERVICES)
{
Start-Service -InputObject (Get-Service -ComputerName $SERVERNAME -Name $DEPSERVICE.SERVICENAME)
}
}
}
}
ELSEIF ( $SERVICE.STATUS -EQ “STOPPED” )
{
Start-Service -InputObject (Get-Service -ComputerName $SERVERNAME -Name $SERVICE.SERVICENAME)
$DEPSERVICES = GET-SERVICE -COMPUTERNAME $SERVERNAME -NAME $SERVICE.SERVICENAME -DEPENDENTSERVICES | WHERE-OBJECT {$_.STATUS -EQ “STOPPED”}
IF( $DEPSERVICES -NE $NULL )
{
FOREACH($DEPSERVICE IN $DEPSERVICES)
{
Start-Service -InputObject (Get-Service -ComputerName $SERVERNAME -Name $DEPSERVICE.SERVICENAME)
}
}
}
ELSE
{
“THE SPECIFIED SERVICE DOES NOT EXIST”
}
}

*******************************************************************************

Example 1:- Local Machine( Restart SQL Service locally)

PS P:\> Restart-Service -SERVICENAME MSSQLSERVER

Restart-Service3

Example 2:-

PS P:\>Restart-Service -SERVERNAME HQVD0026 -SERVICENAME MSSQLSERVER

Image

Example 3:-Negate the “$” meaning by using “`” for Named Instance.

PS P:\>Restart-Service -SERVERNAME HQVD0026 -SERVICENAME SQLAgent`$KAT

Image

Download the code here Restart-Service

Thanks for reading my space…

Happy Learning!!

Advertisement

About Prashanth Jayaram

DB Technologist, Author, Blogger, Service Delivery Manager at CTS, Automation Expert, Technet WIKI Ninja, MVB and Powershell Geek My Profile: https://social.technet.microsoft.com/profile/prashanth jayaram/ http://www.sqlshack.com/author/prashanth/ http://codingsight.com/author/prashanthjayaram/ https://www.red-gate.com/simple-talk/author/prashanthjayaram/ http://www.sqlservercentral.com/blogs/powersql-by-prashanth-jayaram/ Connect Me: Twitter @prashantjayaram GMAIL powershellsql@gmail.com The articles are published in: http://www.ssas-info.com/analysis-services-articles/ http://db-pub.com/ http://www.sswug.org/sswugresearch/community/
This entry was posted in PowerShell, SQL and tagged , . Bookmark the permalink.

1 Response to PowerShell – Restart Service – Local or Remote Machines

  1. Siva says:

    Hi Prahsanth,

    Thanks for great post. i’m looking for stop/start services in remote machines and send the status report through HTML mail Output. As i’ve found in your posts, only status of the services report in multiple machines. it would be helpful if you can include the stop services in list computers and then send the HTML mail out for all services.

    I”m trying to add some code to stop the services in one of your post . but something is missing at my end i’m not able to figure it out .. I request you to help me on this. I’m posting my code below

    Function Get-ServiceStatusReport
    {
    param(
    [String]$ComputerList,[String[]]$includeService,[String]$To,[String]$From,[string]$SMTPMail
    )
    $script:list = $ComputerList
    $ServiceFileName= “c:\ServiceFileName.htm”
    New-Item -ItemType file $ServiceFilename -Force
    # Function to write the HTML Header to the file
    Function writeHtmlHeader
    {
    param($fileName)
    $date = ( get-date ).ToString(‘yyyy/MM/dd’)
    Add-Content $fileName “”
    Add-Content $fileName “”
    Add-Content $fileName “”
    Add-Content $fileName ‘Service Status Report ‘
    add-content $fileName ”
    add-content $fileName “
    add-content $fileName “”
    Add-Content $fileName “”
    Add-Content $fileName “”

    add-content $fileName “”
    add-content $fileName “”
    add-content $fileName “”
    add-content $fileName “Service Stauts Report – $date
    add-content $fileName “”
    add-content $fileName “”
    add-content $fileName “”

    }

    # Function to write the HTML Header to the file
    Function writeTableHeader
    {
    param($fileName)

    Add-Content $fileName “”
    Add-Content $fileName “ServerName”
    Add-Content $fileName “Service Name”
    Add-Content $fileName “status”
    Add-Content $fileName “”
    }

    Function writeHtmlFooter
    {
    param($fileName)

    Add-Content $fileName “”
    Add-Content $fileName “”
    }

    Function writeDiskInfo
    {
    param($filename,$Servername,$name,$Status)
    if( $status -eq “Stopped”)
    {
    Add-Content $fileName “”
    Add-Content $fileName “$servername”
    Add-Content $fileName “
    $name”
    Add-Content $fileName “
    $Status”
    Add-Content $fileName “”
    }
    else
    {
    Add-Content $fileName “”
    Add-Content $fileName “$servername”
    Add-Content $fileName “$name”
    Add-Content $fileName “$Status”
    Add-Content $fileName “”
    }

    }

    writeHtmlHeader $ServiceFileName
    Add-Content $ServiceFileName “”
    Add-Content $ServiceFileName “”
    Add-Content $ServiceFileName “ Service Details
    Add-Content $ServiceFileName “”

    writeTableHeader $ServiceFileName

    #Change value of the following parameter as needed

    $InlcudeArray=@()

    #List of programs to exclude
    #$InlcudeArray = $inlcudeService

    Foreach($ServerName in (Get-Content $script:list))
    {
    if(Test-Connection -ComputerName $ServerName -Count 1 -ea 0) {
    Write-Warning “$ServerName : Offline”
    Continue
    }
    foreach($service in $ServiceName) {
    try {
    $ServiceObject = Get-WMIObject -Class Win32_Service -ComputerName $ServerName -Filter “Name=’$service'” -EA Stop
    if(!$ServiceObject) {
    Write-Warning “$ServerName : No service found with the name $service”
    Continue
    }
    if($ServiceObject.StartMode -eq “Disabled”) {
    Write-Warning “$ServerName : Service with the name $service already in disabled state”
    Continue
    }

    Set-Service -ComputerName $ServerName -Name $service -EA Stop -StartMode Disabled
    Write-Host “$ServerName : Successfully disabled the service $service. Trying to stop it”
    if($ServiceObject.Status -eq “Running”) {
    Write-Warning “$ServerName : $service already in stopped state”
    Continue
    }
    $retval = $ServiceObject.StopService()

    if($retval.ReturnValue -ne 0) {
    Write-Warning “$ServerName : Failed to stop service. Return value is $($retval.ReturnValue)”
    Continue
    }

    Write-Host “$ServerName : Stopped service successfully”

    } catch {
    Write-Warning “$ServerName : Failed to query $service. Details : $_”
    Continue
    }

    if ($Service -ne $NULL)
    {
    foreach ($item in $service)
    {
    #$item.DisplayName
    Foreach($include in $includeService)
    {

    write-host $inlcude
    if(($item.serviceName).Contains($include) -eq $TRUE)
    {

    Write-Host $item.MachineName $item.name $item.Status
    writeDiskInfo $ServiceFileName $item.MachineName $item.name $item.Status
    }
    }
    }
    }
    }
    }

    Add-Content $ServiceFileName “”

    writeHtmlFooter $ServiceFileName

    function Validate-IsEmail ([string]$Email)
    {

    return $Email -match “^(?(“”)(“”.+?””@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&’\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"
    }

    Function sendEmail
    {
    param($from,$to,$subject,$smtphost,$htmlFileName)
    [string]$receipients="$to"
    $body = Get-Content $htmlFileName
    $body = New-Object System.Net.Mail.MailMessage $from, $receipients, $subject, $body
    $body.isBodyhtml = $true
    $smtpServer = $MailServer
    $smtp = new-object Net.Mail.SmtpClient($smtphost)
    $validfrom= Validate-IsEmail $from
    if($validfrom -eq $TRUE)
    {
    $validTo= Validate-IsEmail $to
    if($validTo -eq $TRUE)
    {
    $smtp.Send($body)
    write-output "Email Sent!!"

    }
    }
    else
    {
    write-output "Invalid entries, Try again!!"
    }
    }

    $date = ( get-date ).ToString('yyyy/MM/dd')

    sendEmail -from $From -to $to -subject "Service Status – $Date" -smtphost $SMTPMail -htmlfilename $ServiceFilename

    }

    Thanks in advance.

    –Siva

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s