question

IvayloStefanov avatar image
0 Votes"
IvayloStefanov asked ·

Script, that restart services

Hi,

i need a script that must following:
1.Stop Services
2. Delete some folder, data (data older 7 days)
3. Restart the first service by checking if any web services are started, if ok started second service, if not ok start service again.

I wrote this script:



 [Array] $Services = 'LAS_LMB','LAS_LWS','LAS_CORE';
    
 foreach($ServiceName in $Services)
 {
     $arrService = Get-Service -Name $ServiceName
     write-host $ServiceName
     while ($arrService.Status -eq 'Running')
     {
         Stop-Service $ServiceName
         write-host $arrService.status
         write-host $ServiceName stopping
         Start-Sleep -seconds 60
         $arrService.Refresh()
         if ($arrService.Status -eq 'Stopped')
             {
               Write-Host $ServiceName is now Stopped
             }
      }
  }
    
 $las_path = "D:\LAS\"
 $tomcat_core = "tomcat_core"
 $tomcat_web = "tomcat_web"
 $tomcat_lmb = "tomcat_lmb"
 $log_folder = "logs"
 $temp_folder = "temp\*"
 $localhost_folder = "work\Catalina\localhost"
 $PATH = Join-Path $las_path -ChildPath $tomcat_core | Join-Path -ChildPath $localhost_folder
 $PATH1 = Join-Path $las_path -ChildPath $tomcat_web | Join-Path -ChildPath $localhost_folder
 $PATH2 = Join-Path $las_path -ChildPath $tomcat_lmb| Join-Path -ChildPath $localhost_folder
 $TEMPPATH = Join-Path $las_path -ChildPath $temp_folder
 $LOGDIR = Join-Path $las_path -ChildPath $log_folder
 while ((Get-Service $Services).Status -eq 'Stopped')
 {
 Start-Sleep 5
    
 Remove-Item -Path $PATH, $PATH1, $PATH2, $TEMPPATH -Force -Recurse -Verbose
 Get-ChildItem -Path $LOGDIR -Recurse -include *.log -File | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-7)} | Remove-Item -Verbose
    
 Write-Host 'Folders was deleted'
 Break
 } 
    
 foreach($ServiceName in $Services)
 {
     $arrService = Get-Service -Name $ServiceName
     write-host $ServiceName
     while ($arrService.Status -ne 'Running')
     {
         Start-Service $ServiceName
         write-host $arrService.status
         write-host $ServiceName starting
         Start-Sleep -seconds 30
         $arrService.Refresh()
 $CORESt = Get-Service -DisplayName "LAS_CORE" | Where-Object {$_.Status -eq "Running"}
 $WEBSt = Get-Service -DisplayName "LAS_LWS" | Where-Object {$_.Status -eq "Running"}
 $LMBSt = Get-Service -DisplayName "LAS_LMB" | Where-Object {$_.Status -eq "Running"}
 #$servicesToStartLASCORE = { Write-Host "Starting service LASCORE"; Start-Service -Name "LASCORE" -Verbose; Start-Sleep -Seconds $startBreak }
 #$WebResponse = (Invoke-WebRequest "http://.........../" | Select-Object -Property Content).content
 $WebResponse1 = (Invoke-WebRequest "http://........................")
 $uri1  = 'http://.................'
 $user = '..........'
 $pass = '.........' | ConvertTo-SecureString -AsPlainText -Force
 $cred = New-Object Management.Automation.PSCredential ($user, $pass)
 $REMOTEDB = Invoke-WebRequest -Uri $uri1 -Credential $cred 
 $uri2 = '............'
 $cred = New-Object Management.Automation.PSCredential ($user, $pass)
 $LAGOFS = Invoke-WebRequest -Uri $uri2 -Credential $cred
 $uri3  = 'http://.................'
 $cred = New-Object Management.Automation.PSCredential ($user, $pass)
 $Message = Invoke-WebRequest -Uri $uri3 -Credential $cred
         if ($WebResponse1.StatusCode -eq 200 -and $REMOTEDB.StatusCode -eq 200 -and $LAGOFS.StatusCode -eq 200)
         {
           Write-Host $ServiceName is now Running
         }
     }
 }

I tested and works, but i need when i start first service, then after 30 s (for example) to test whether web services are started, If they are started, start next service, if not started, start same service again.

Besides , I need also to show me all started services. Then I need to select any services and implement them in one array. I wrote this code:

 Get-Service | Where-Object {$_.Status -eq "Running"} | Format-Wide -column 3
    
 $Stopservices1 = Read-Host "Enter the Services"
 $Stopservices2 = Read-Host "Enter the Services"
 $Stopservices3 = Read-Host "Enter the Services"
    
 $servicesList = ("'$Stopservices1'","'$Stopservices2'","'$Stopservices3'" -join ",")
    
 [Array] $Services = $servicesList
 When I started, i bekame a fehler. The Result must be
 'LAS_LMB','LAS_LWS','LAS_CORE';

I bekame following:

76242-error.jpg

What i wrong?
Thank you advnace for your answares










windows-server-powershell
error.jpg (214.7 KiB)
· 1
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Why are you placing the service names between single-quotation marks? And why are you joining them with a comma.

If you simply want an array of three service name then this should work:

 $Stopservices1 = Read-Host "Enter the Services"
 $Stopservices2 = Read-Host "Enter the Services"
 $Stopservices3 = Read-Host "Enter the Services"
    
 $Services = $Stopservices1,$Stopservices2,$Stopservices3

Also, if you're going to post code, please use the "Code Sample" icon in the formatting bar or Control+K).

0 Votes 0 ·
RichMatheisen-8856 avatar image
0 Votes"
RichMatheisen-8856 answered ·

I modified some of your code, but I left most of it "as is". I wasn't sure if you were supposed to run your web request for every service, or only once after all services were started.

 [Array] $Services = 'LAS_LMB', 'LAS_LWS', 'LAS_CORE';
        
 foreach ($ServiceName in $Services) {
     $MustForce = $false                     # kill process?
     $loopcount = 0
     $arrService = Get-Service -Name $ServiceName
     Write-Host $ServiceName
     while ($arrService.Status -eq 'Running') {  # what about other states? E.g., ContinuePending, Paused, StopPending, etc? Maybe change to "-ne "Stopped"?
                                                 # consider using "-Force if this tries to stop the service more than "X" times, as below
                                                 # and then try killing the service if it hasn't stopped on its own
         $loopcount++
         if ($loopcount -gt 3){
             $MustForce = $true
         }
         elseif ($loopcount -gt 5) {
             Write-Host "Cannot stop or kill service $ServiceName! HELP!!!!" 
             Exit
         }
         Stop-Service $ServiceName -Force:$MustForce
         Write-Host $arrService.status
         Write-Host $ServiceName stopping
         Start-Sleep -seconds 60
         $arrService.Refresh()
         if ($arrService.Status -eq 'Stopped') {
             Write-Host $ServiceName is now Stopped
         }
     }
 }
        
 $las_path = "D:\LAS\"
 $tomcat_core = "tomcat_core"
 $tomcat_web = "tomcat_web"
 $tomcat_lmb = "tomcat_lmb"
 $log_folder = "logs"
 $temp_folder = "temp\*"
 $localhost_folder = "work\Catalina\localhost"
 $PATH = Join-Path $las_path -ChildPath $tomcat_core | Join-Path -ChildPath $localhost_folder
 $PATH1 = Join-Path $las_path -ChildPath $tomcat_web | Join-Path -ChildPath $localhost_folder
 $PATH2 = Join-Path $las_path -ChildPath $tomcat_lmb | Join-Path -ChildPath $localhost_folder
 $TEMPPATH = Join-Path $las_path -ChildPath $temp_folder
 $LOGDIR = Join-Path $las_path -ChildPath $log_folder
    
 if ((Get-Service $Services | Where-Object {$_.Status -eq "Stopped"}).count -eq $Services.count){   # all services are stopped?
     Start-Sleep 5
        
     Remove-Item -Path $PATH, $PATH1, $PATH2, $TEMPPATH -Force -Recurse -Verbose
     Get-ChildItem -Path $LOGDIR -Recurse -include *.log -File | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } | Remove-Item -Verbose
        
     Write-Host 'Folders was deleted'
     Break
 }
 else{
     Write-Host "Something has started one of the services! HELP!!!" -ForegroundColor RED
     exit
 }
        
 foreach ($ServiceName in $Services) {
     $arrService = Get-Service -Name $ServiceName
     Write-Host $ServiceName
     while ($arrService.Status -ne 'Running') {
         Start-Service $ServiceName
         Write-Host $arrService.status
         Write-Host $ServiceName starting
         Start-Sleep -seconds 30
         $arrService.Refresh()
     }
     # don't do any of this unless the service is actually running
     $CORESt = Get-Service -DisplayName "LAS_CORE" | Where-Object { $_.Status -eq "Running" }
     $WEBSt = Get-Service -DisplayName "LAS_LWS" | Where-Object { $_.Status -eq "Running" }
     $LMBSt = Get-Service -DisplayName "LAS_LMB" | Where-Object { $_.Status -eq "Running" }
     #$servicesToStartLASCORE = { Write-Host "Starting service LASCORE"; Start-Service -Name "LASCORE" -Verbose; Start-Sleep -Seconds $startBreak }
     #$WebResponse = (Invoke-WebRequest "http://.........../" | Select-Object -Property Content).content
     $WebResponse1 = (Invoke-WebRequest "http://........................")
     $uri1 = 'http://.................'
     $user = '..........'
     $pass = '.........' | ConvertTo-SecureString -AsPlainText -Force
     $cred = New-Object Management.Automation.PSCredential ($user, $pass)
     $REMOTEDB = Invoke-WebRequest -Uri $uri1 -Credential $cred 
     $uri2 = '............'
     $cred = New-Object Management.Automation.PSCredential ($user, $pass)
     $LAGOFS = Invoke-WebRequest -Uri $uri2 -Credential $cred
     $uri3 = 'http://.................'
     $cred = New-Object Management.Automation.PSCredential ($user, $pass)
     $Message = Invoke-WebRequest -Uri $uri3 -Credential $cred
     if ($WebResponse1.StatusCode -eq 200 -and $REMOTEDB.StatusCode -eq 200 -and $LAGOFS.StatusCode -eq 200) {
         Write-Host $ServiceName is now Running
     }
 }
·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

IvayloStefanov avatar image
0 Votes"
IvayloStefanov answered ·

Thank you RichMatheisen,

i corrected. Can you help me with my script , that resart service? I am new in powershell and now lern, test and correct.

·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.