Reputation: 111
I have been playing with a script I found here...and it is a very elegant one. However, I am breaking it every time I try to modify it to perform the stop/start on multiple services. Short of individual listing each one. Any ideas? Here is the script for starting/stopping a service.
$SvcName
needs to read these services: ftSysPolicy
, ftSysInventory
, ftSysAlarm
, ftSysSSN
, ftSysRpcProv
, ftSysEService
, ftSysRAS
, ftSysMad
#Change these values to suit your needs:
$SvcName = 'Spooler'
$SvrName = 'localhost'
#Initialize variables:
[string]$WaitForIt = ""
[string]$Verb = ""
[string]$Result = "FAILED"
$svc = (Get-Service -ComputerName $SvrName -Name $SvcName)
Write-Host "$SvcName on $SvrName is $($svc.status)"
switch ($svc.Status) {
'Stopped' {
Write-Host "Starting $SvcName..."
$Verb = "start"
$WaitForIt = 'Running'
$svc.Start()}
'Running' {
Write-Host "Stopping $SvcName..."
$Verb = "stop"
$WaitForIt = 'Stopped'
$svc.Stop()}
Default {
Write-Host "$SvcName is $($svc.Status). Taking no action."
}
}
if ($WaitForIt -ne "") {
try { # For some reason, we cannot use -ErrorAction after the next statement:
$svc.WaitForStatus($WaitForIt, '00:02:00')
} catch {
Write-Host "After waiting for 2 minutes, $SvcName failed to $Verb."
}
$svc = (Get-Service -ComputerName $SvrName -Name $SvcName)
if ($svc.status -eq $WaitForIt) {$Result = 'SUCCESS'}
Write-Host "$Result`: $SvcName on $SvrName is $($svc.Status)"
}
Upvotes: 1
Views: 259
Reputation: 22831
Create an array of the service names and loop over the logic that restarts them:
$svcs = @('ftSysPolicy', 'ftSysInventory', 'ftSysAlarm', 'ftSysSSN', 'ftSysRpcProv', 'ftSysEService', 'ftSysRAS', 'ftSysMad')
foreach (svcName in $svcs) {
[string]$WaitForIt = ""
[string]$Verb = ""
[string]$Result = "FAILED"
$svc = (get-service -computername $SvrName -name $SvcName)
Write-host "$SvcName on $SvrName is $($svc.status)"
Switch ($svc.status) {
'Stopped' {
Write-host "Starting $SvcName..."
$Verb = "start"
$WaitForIt = 'Running'
$svc.Start()}
'Running' {
Write-host "Stopping $SvcName..."
$Verb = "stop"
$WaitForIt = 'Stopped'
$svc.Stop()}
Default {
Write-host "$SvcName is $($svc.status). Taking no action."}
}
if ($WaitForIt -ne "") {
Try { # For some reason, we cannot use -ErrorAction after the next statement:
$svc.WaitForStatus($WaitForIt,'00:02:00')
} Catch {
Write-host "After waiting for 2 minutes, $SvcName failed to $Verb."
}
$svc = (get-service -computername $SvrName -name $SvcName)
if ($svc.status -eq $WaitForIt) {$Result = 'SUCCESS'}
Write-host "$Result`: $SvcName on $SvrName is $($svc.status)"
}
}
Or, even better, put the logic into a function and call that.
Also, check out the get-service
, stop-service
and start-service
cmdlets
Upvotes: 2