customer relationships

Restart a Service Remotely Using PowerShell on Multiple Servers

I threw a quick PowerShell function together that would allow me to restart one service on 1 or more servers in one command.  I hadn’t found an easy way to do this in PowerShell before so I threw this together.  What I did was pasted the function code into my PowerShell profile at c:\users\%USERNAME%\Documents\WindowsPowershell\Microsoft.PowerShell_profiles.ps1 to ensure it was loaded each time I started my PowerShell window.  The syntax of the script is simple:

 

Restart-MultipleServerServices -ServiceName MSExchangeTransport -ServerNames Server1,Server2

The service name is a simple string, and should be the short name of the service.  The ServerNames option should be a comma separated list of servers that you want to restart the service on.  It can be any number of servers, meaning you can use this to remotely stop the service on just 1 servers or 100.  The output of the service being restarted looks like this:

image

Copy the below script:

function Restart-MultipleServerServices([string]$ServiceName, [array]$ServerNames)
{

foreach ($i in $ServerNames)
{
$service = Get-Service -ComputerName "$i" -name $ServiceName
    $service.stop()
    do { Start-sleep -Milliseconds 200}
    until ((Get-Service -ComputerName "$i" -Name $ServiceName).status -eq 'Stopped')
    Write-Host "Attempting to Stop Service $($ServiceName) on Server $i" -ForegroundColor Green
    Start-Sleep 10
    $service.start()
    do { Start-sleep -Milliseconds 200}
    until ((Get-Service -ComputerName "$i" -Name $ServiceName).status -eq 'Running')
    Write-Host "Attempting to Start Service $($ServiceName) on Server $i" -ForegroundColor Green

    }
    }

Into your PowerShell profile at the below path.  If the PS1 file isn’t there, you can manually create it:

   1: C:\Users\%USERNAME%\Documents\WindowsPowershell\Microsoft.PowerShell_profile.ps1

image

Save and close the file and you should be ready to rock!


Got a project that needs expert IT support?

From Linux and Microsoft Server to VMware, networking, and more, our team at CR Tech is here to help.

Get personalized support today and ensure your systems are running at peak performance or make sure that your project turns out to be a successful one!

CONTACT US NOW
best vpn deal