-2

I found a Powershell script that checks all automatic services on Windows servers and if they are not started, tries to start them. Here is the link http://doitcloudy.blogspot.de/2014/07/scriptgesteuerter-neustart-von-windows.html (It's German, but the script on the bottom of the page is all English). I would like to customize it a bit. However, I need some help with this part (lines 130 and following):

foreach ($item in $report){
 Write-Host "Starting Service " $item.Name " on server: " $item.Server -Foregroundcolor yellow
$start = Get-Date
$startSVCblock = {param($item) Start-Service -InputObject (Get-Service -ComputerName $item.Server -Name $item.Name)}
$j = Start-Job -ScriptBlock $startSVCblock -Arg $item
do {
 if ($j.State -ne 'Running') { break} 
 $j | Receive-Job
 } while (((Get-Date) - $start) -le $timeout)
}

I see that this is the part where the script starts a service, but I'm not used to "jobs" in Powershell. How should I edit the script so that when starting the service fails, it writes the service name to a log file? Maybe with try/catch?

Any help is greatly appreciated!

Peter
  • 27
  • 2
  • 7

2 Answers2

0

On lines 103, 123, and 137 write to your log before the break.

So change

 if ($j.State -ne 'Running') { break} 

to

 if ($j.State -ne 'Running') { Add-Content c:\log.txt "$item Did not Start" ; break} 
Eric
  • 554
  • 1
  • 5
  • 15
  • Hey, thank you for your answer. However, this writes to the log before an attempt was made to start the service. I'd like to write to the log if starting the service was not successful. I think this should be where "Receive-Job" is, but I can't make that output go to the logfile. Any ideas? – Peter Oct 28 '15 at 07:51
0

If anyone stumbles upon this and wants to know how I solved it: After a lot of research I found out that it is extremely difficult to write the output of Receive-Job to a log file. So I chose a different approach: I check if the server is running after the job has finished. Here's the code:

foreach ($item in $report){
Write-Output "Starting Service " $item.Name " on server: " $item.Server
$start = Get-Date
$startSVCblock = {param($item) Start-Service -InputObject (Get-Service -ComputerName $item.Server -Name $item.Name)}
$j = Start-Job -ScriptBlock $startSVCblock -Arg $item
do {
    if ($j.State -ne 'Running') { break} 
    $j | Receive-Job
} while (((Get-Date) - $start) -le $timeout)
$newService = Get-Service -ComputerName $item.Server -Name $item.Name
if ($newService.Status -ne "Running") { LogWrite "$item could not start" }

}

Peter
  • 27
  • 2
  • 7