Hi everyone,
I need a Script that check a process is started, and if is it started must stopped. I wrote the following:
$lascore = Get-WmiObject -Class Win32_Service -Filter "Name LIKE 'tomcat9'" | Select-Object -ExpandProperty Services$process = Get-Service -ServiceName $lascore
$process = Get-Service -ServiceName $lascore
When i start $process
PS C:\Users\Administrator\Desktop\Test\command> $process
I see all processes and their status. I need only to see one Process (for example LASCORE) is running and after that i need to stop it.
Status Name DisplayName
------ ---- -----------
...
.
.
Running LanmanServer Server
Running LanmanWorkstation Workstation
Running LASCORE LASCORE
Running LASLMB LASLMB
Running LASWEB LASWEB
.
.
.
Thank you.
ferc
February 26, 2021, 1:51pm
2
I think there may be a confusion between processes and services. You are referring to processes in your post but working with services. Why not use ‘Get-Service’ and ‘Stop-Service’ instead?
$TargetService = 'MyService'
$Services = Get-Service | Select-Object -ExpandProperty Name
If ($TargetService -in $Services) {
Stop-Service -Name $TargetService
}
Else {
Write-Host "`n[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] $TargetService not running" -ForegroundColor Green
}
If you are indeed trying to find and stop a process, then replace “Service” with “Process” in the code.
Hi,
thank you for your replay. I don’t understand how check that a service is running. The answare is that the service is not running, but it’s actually running.
You can use Get-Service -Name LASLMB
to check if there is a service with that name is running or not.
Do it with -ErrorActoin SilentlyContinue
$Service = Get-Service -Name LASLMB -ErrorAction SilentlyContinue`
if($Service){
$Service | Stop-Service -Force -Verbose
}
ferc
February 26, 2021, 2:56pm
5
What is the code of lascore2.ps1?
Again, I would stick to PowerShell cmdlets instead of external commands.
$TargetService = 'LASCORE'
$Services = Get-Service | Select-Object -ExpandProperty Name
If ($TargetService -in $Service) {
Stop-Service -Name $TargetService
}
Else {
Write-Host "`n[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] $TargetService not running" -ForegroundColor Green
}
ferc
February 26, 2021, 3:34pm
7
Ok, so you are indeed dealing with services.
You need to change this:
‘If ($TargetService -in $Service)’
To this:
‘If ($TargetService -in $Services )’
$TargetService = 'LASCORE'
$Services = Get-Service | Select-Object -ExpandProperty Name
If ($TargetService -in $Services) {
Stop-Service -Name $TargetService
}
Else {
Write-Host "`n[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] $TargetService not running" -ForegroundColor Green
}
Thank you ferc. Now it’s work.
1 Like
gcduvm
February 26, 2021, 4:27pm
9
Instead of getting a list of all services and then searching that list, why not just get the one service you’re interested in?
Using -ErrorAction SilentlyContinue
will avoid error messages if that service isn’t present.
$Service = Get-Service -Name $TargetService -ErrorAction SilentlyContinue
If ( $Service) {
$Service | Stop-Service
}
I hope that’s helpful. It’s a good habit to avoid retrieving a full list of items and them filtering them if you can do the filtering in the initial request.
FWIW
Hi there,
I have no experence with powershell, i need a big help.
I need a script, that stop and start 3 services and then check that web sites are started. The Services named LASCORE, LASWEB,LASLMB.
I wrote a Script (See my Post bellow - first script), but sometime don’t work.
The Problem is that sometimes Serviec “LASCORE” don’t stop. After tree services stoped, must some Folder to deleted. (This works). Denn must be first servicee LASCORE to started and then chek that some links are alive (code 200) . When they are aktive, must be started next service - LASWEB, and then must be checked that same links are aktive etc. I wrote another script (see script 2 bellow), but can implement in first.
I will be very, very grateful if anyone can help me.
Thats a lot of code to post . So it will be easier for anyone to read if you can format it better. Use below link to see how.
Guide to Posting Code - Redux - PowerShell Help - PowerShell Forums
Ok,
Thank you kvprasonn for the explanation. I hope it’s clearer now.
It’s a first script:
# define some variables
$servicesToStart = @("LASCORE", "LASWEB", "LASLMB")
$servicesToStop = @("LASCORE", "LASWEB", "LASLMB")
$serviceLASCOREtoStop = 'LASCORE'
# time between status check after trying to stop
$stopBreak = 30
# time between starting services
$startBreak = 15
$ServiceStopMaxRetryCount = $stopBreak
Function StopServices($servicesToStop){
$servicesSuccessfullyStopped = $false
$stoppedServices = @()
Write-Host " "
Write-Host "======================================="
Write-Host "========== STOPPING SERVICES =========="
Write-Host "======================================="
if($servicesToStop -and $servicesToStop.Count -gt 0){
$servicesToStop | % { Write-Host "Stopping service $_"; return $_} |
% {
$triedCount = 0
$service = Get-Service $_
if($service){
Stop-Service $service.Name
$serviceStatus = $service.Status
do {
$triedCount++
Start-Sleep -Milliseconds 1000
$serviceStatus = (Get-Service $_).Status
Write-Host "Service status: $serviceStatus"
} Until (!$service -or $serviceStatus -eq "Stopped" -or $triedCount -gt $ServiceStopMaxRetryCount)
if($triedCount -gt $ServiceStopMaxRetryCount){
Write-Error "Cannot stop the service $_ after $ServiceStopMaxRetryCount tries"
Write-Debug "Trying to kill the process"
return
}
}
return $_
} | % { $stoppedServices += $_ }
}
if($stoppedServices.Count -ne $servicesToStop.Count){
foreach($serviceToStop in $servicesToStop){
if( !($stoppedServices -contains $serviceToStop) ){
Write-Warning "Service $serviceToStop could not be stopped. Attempting to kill the service process"
try{
Kill-ServiceProcess $serviceToStop
$stoppedServices +=$serviceToStop
}
catch{
Write-Error $_.Exception.Message
Return $false
}
}
}
}
if($stoppedServices.Count -eq $servicesToStop.Count){
$servicesSuccessfullyStopped = $true
}
return $servicesSuccessfullyStopped
}
Function Kill-ServiceProcess($service){
$serviceProcess = Get-WmiObject -Class Win32_Service -filter "Name = '$service'"
if(!$serviceProcess) {
throw "Could not identify process for service $service"
}
$processId = $serviceProcess.ProcessId
$process = Get-WmiObject -Class Win32_Process -Filter "ProcessId = $processId"
if($process){
$returnval = $process.Terminate()
if($returnval.returnvalue -eq 0) {
write-host "The process $ProcessName ($processid) terminated successfully"
}
else {
Throw "Encountered problems during the termination of process $ProcessName ($processid)"
}
}
}
Function Kill-ServiceProcess1($serviceLASCOREtoStop){
$TargetService = 'LASCORE'
$Services = Get-Service | Select-Object -ExpandProperty Name
If ($TargetService -in $Services) {
Stop-Service -Name $TargetService
}
Else {
Write-Host "`n[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] $TargetService not running" -ForegroundColor Green
}
}
############## EXECUTION START ##################
Write-Host "Stopping all specified services"
#$folder1 = 'F:\LAS\tomcat_core\temp\*'
#$folder2 = 'F:\LAS\tomcat_lmb\temp\*'
#$folder3 = 'F:\LAS\tomcat_web\temp\*'
#$folder4 = 'F:\LAS\tomcat_core\work\Catalina\localhost'
#$folder5 = 'F:\LAS\tomcat_lmb\work\Catalina\localhost'
#$folder6 = 'F:\LAS\tomcat_web\work\Catalina\localhost'
$stoppedSuccessfully = StopServices $servicesToStop
$folder1 = 'C:\Users\Administrator\Desktop\Delete1\tomcat_core1\temp\*'
$folder2 = 'C:\Users\Administrator\Desktop\Delete1\tomcat_lmb1\temp\*'
$folder3 = 'C:\Users\Administrator\Desktop\Delete1\tomcat_web1\temp\*'
$folder4 = 'C:\Users\Administrator\Desktop\Delete1\tomcat_core\work\Catalina\localhost'
$folder5 = 'C:\Users\Administrator\Desktop\Delete1\tomcat_lmb\work\Catalina\localhost'
$folder6 = 'C:\Users\Administrator\Desktop\Delete1\tomcat_web\work\Catalina\localhost'
if($stoppedSuccessfully){
Write-Host "Sucessfully stopped all services"
Write-Host "Now delete temporary data"
Remove-Item $folder1, $folder2, $folder3, $folder4, $folder5, $folder6 -Force -Recurse -Verbose
} else {
Write-Error "Encountered problems while stopping services"
}
Write-Host "Now starting all services"
$servicesToStart | % { Write-Host "Starting service $_"; Start-Service -Name $_; Start-Sleep -Seconds $startBreak }
############## TEMPORARY DATA DELETE ###############
#Write-Host " "
#Write-Host "==========================================="
#Write-Host "========== TEMPORARY DATA DELETE =========="
#Write-Host "==========================================="
##########################CHECK THAT TOMCAT IS RUNNING####################################
if ((Get-Process "tomcat9" -ea SilentlyContinue) -eq $Null) {
"Tomcat is not Running"
}
else {
"Tomcat is Running"
}
$CORESt = Get-Service -DisplayName "LASCORE" | Where-Object {$_.Status -eq "Running"}
$WEBSt = Get-Service -DisplayName "LASWEB" | Where-Object {$_.Status -eq "Running"}
$LMBSt = Get-Service -DisplayName "LASLMB" | Where-Object {$_.Status -eq "Running"}
$servicesToStartLASCORE = { Write-Host "Starting service LASCORE"; Start-Service -Name "LASCORE" -Verbose; Start-Sleep -Seconds $startBreak }
$WebResponse = (Invoke-WebRequest ".........................................................." | Select-Object -Property Content).content
$WebResponse1 = (Invoke-WebRequest ".......................................................")
$uri1 = '..........................................................................'
$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 = "..................................................."
$cred = New-Object Management.Automation.PSCredential ($user, $pass)
$Message = Invoke-WebRequest -Uri $uri3 -Credential $cred
If($CORESt.Status -eq "Running") {
Write-Host "LASCORE is Running"
Write-Host "Now check LAGO WEB Service"
}
Start-Sleep -s 15
If($WebResponse -like "LAGO RESTful WebServices" -and $WebResponse1.StatusCode -eq 200 -and $REMOTEDB.StatusCode -eq 200 -and $LAGOFS.StatusCode -eq 200 -and $Message.StatusCode -eq 200)
{Write-Host "LagoWebServices, LagoConfigServer, LagoRemoteDBare, LagoFS, LagoMessageBus are Running"}
else {
Write-Host "Not OK"
}
If($WEBSt.Status -eq "Running") {
Write-Host "LASWEB is Running"
Write-Host "Now check LAGO WEB Service"
}
Start-Sleep -s 15
If($WebResponse -like "LAGO RESTful WebServices" -and $WebResponse1.StatusCode -eq 200 -and $REMOTEDB.StatusCode -eq 200 -and $LAGOFS.StatusCode -eq 200 -and $Message.StatusCode -eq 200)
{Write-Host "LagoWebServices, LagoConfigServer, LagoRemoteDBare, LagoFS, LagoMessageBus are Running"}
else {
Write-Host "Not OK"
}
If($LMBSt.Status -eq "Running") {
Write-Host "LASLMB is Running"
Write-Host "Now check LAGO WEB Service"
}
Start-Sleep -s 15
If($WebResponse -like "LAGO RESTful WebServices" -and $WebResponse1.StatusCode -eq 200 -and $REMOTEDB.StatusCode -eq 200 -and $LAGOFS.StatusCode -eq 200 -and $Message.StatusCode -eq 200)
{Write-Host "LagoWebServices, LagoConfigServer, LagoRemoteDBare, LagoFS, LagoMessageBus are Running"}
else {
Write-Host "Not OK"
}
Write-Host "Done"
And this is second teil, that must implement:
$CORESt = Get-Service -DisplayName "LASCORE" | Where-Object {$_.Status -eq "Running"}
$WEBSt = Get-Service -DisplayName "LASWEB" | Where-Object {$_.Status -eq "Running"}
$LMBSt = Get-Service -DisplayName "LASLMB" | Where-Object {$_.Status -eq "Running"}
$servicesToStartLASCORE = { Write-Host "Starting service LASCORE"; Start-Service -Name "LASCORE" -Verbose; Start-Sleep -Seconds $startBreak }
$WebResponse = (Invoke-WebRequest "...................................................." | Select-Object -Property Content).content
$WebResponse1 = (Invoke-WebRequest "...................................................")
$uri1 =
$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 =
$cred = New-Object Management.Automation.PSCredential ($user, $pass)
$Message = Invoke-WebRequest -Uri $uri3 -Credential $cred
Write-Host "Starting service LASCORE"
$servicesLASCOREToStart = Start-Service -Name "LASCORE"; Start-Sleep -s 15
$servicesLASWEBToStart = Start-Service -Name "LASWEB"; Start-Sleep -s 15
$servicesLASLMBToStart = Start-Service -Name "LASLMB"; Start-Sleep -s 15
Write-Host "Starting service LASCORE"
If($CORESt.Status -eq "Running") {
Write-Host "LASCORE is Running"
Write-Host "Now check LAGO WEB Service"
Start-Sleep -s 15
($WebResponse -like "LAGO RESTful WebServices" -and $WebResponse1.StatusCode -eq 200 -and $REMOTEDB.StatusCode -eq 200 -and $LAGOFS.StatusCode -eq 200 -and $Message.StatusCode -eq 200)
}
elseif ($WebResponse -like "LAGO RESTful WebServices" -and $WebResponse1.StatusCode -eq 200 -and $REMOTEDB.StatusCode -eq 200 -and $LAGOFS.StatusCode -eq 200 -and $Message.StatusCode -eq 200) {
$servicesLASWEBToStart
}
else {
Start-Service -Name "LASCORE"; Start-Sleep -s 10
}
If($WEBSt.Status -eq "Running") {
Write-Host "LASWEB is Running"
Write-Host "Now check LAGO WEB Service"
Start-Sleep -s 15
($WebResponse -like "LAGO RESTful WebServices" -and $WebResponse1.StatusCode -eq 200 -and $REMOTEDB.StatusCode -eq 200 -and $LAGOFS.StatusCode -eq 200 -and $Message.StatusCode -eq 200)
}
elseif ($WebResponse -like "LAGO RESTful WebServices" -and $WebResponse1.StatusCode -eq 200 -and $REMOTEDB.StatusCode -eq 200 -and $LAGOFS.StatusCode -eq 200 -and $Message.StatusCode -eq 200) {
$servicesLASLMBToStart
}
else {
Start-Service -Name "LASWEB"; Start-Sleep -s 10
}
If($LMBSt.Status -eq "Running") {
Write-Host "LASLMB is Running"
Write-Host "Now check LAGO WEB Service"
Start-Sleep -s 15
($WebResponse -like "LAGO RESTful WebServices" -and $WebResponse1.StatusCode -eq 200 -and $REMOTEDB.StatusCode -eq 200 -and $LAGOFS.StatusCode -eq 200 -and $Message.StatusCode -eq 200)
}
else {
Start-Service -Name "LASLMB"; Start-Sleep -s 10
}
Write-Host "Done"
Thanks again!
I would like to add that the function for deleting folders has been added, because the same folders must be deleted after the three services have been stopped, after that muss services to started. This works without a problem.
Olaf
March 2, 2021, 2:58pm
14
Another tipp: You can edit your posts again if needed by clicking the pencil button below your post. You don’t have to create new once to add information.
Hi there,
I reworked my script but have another problem. The code that i need a help is:
$servicesLASCOREStart | % {Start-Service -Name "LASCORE"; Start-Sleep -s 10}
$CORESt = Get-Service -DisplayName "LASCORE" | Where-Object {$_.Status -eq "Running"}
If($CORESt.Status -eq "Running") {
Write-Host "LASCORE is Running"
Write-Host "Now check LAGO WEB Services"
If($WebResponse1.StatusCode -eq 200 -and $REMOTEDB.StatusCode -eq 200 -and $LAGOFS.StatusCode -eq 200 -and $Message.StatusCode -eq 200) {
Write-Host "LagoWebServices, LagoConfigServer, LagoRemoteDBare, LagoFS, LagoMessageBus are Running" -and $servicesLASWEBtart | % {Start-Service -Name "LASWEB"; Start-Sleep -s 10}
}
else {
$servicesLASCOREStart | % {Start-Service -Name "LASCORE"; Start-Sleep -s 10}
}
}
I want to start LASCORE and denn to show me that the service is running and nee d to check that all some sites are loading (Code 200). If this is successful, the next service must be started, otherwise the the service must be started again.
Thanks advance.
Olaf
March 3, 2021, 10:49am
16
If you have another problem you might create another new question. And what actually is your problem? You’re just told us what you want to do and should happen. But what is it what’s not working?
Ok,
I want to start serviec “LASCORE”.
Check status. If status is “Running”, then print a message "“LASCORE is Running” and “Now check LAGO WEB Services”
If Statuscode LAGO WEB Services is 200 (Website works), then print a message “… are started” and then started next Windows Services - LASWEB, else “star LASCORE” again.
Olaf
March 3, 2021, 3:11pm
18
You already told that. What is your problem?