Script, that restart services

Ivaylo Stefanov 136 Reputation points
2021-03-10T09:04:53.51+00:00

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
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,362 questions
{count} votes

Accepted answer
  1. Rich Matheisen 44,776 Reputation points
    2021-03-11T19:17:54.783+00:00

    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
        }
    }
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Ivaylo Stefanov 136 Reputation points
    2021-03-11T11:53:59.467+00:00

    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.

    0 comments No comments