I've to stop multiples services, check the services if they are correctly stopped THEN run multiple batch files. When the batch jobs are done, start again the stopped services at the first place. I started the following script but could not go further.
#Define Services
$service1 = 'StiSvc'
$service2 = 'AdobeARMservice'
$services = #(
$service1,
$service2
)
#Stop Services
Get-Service |
Where { $services -contains $_.Name } |
Foreach {
$_ | Stop-Service
}
#Verify Services
Get-Service |
Where { $services -contains $_.Name } |
Foreach {
if ((Get-Service $_.Name).Status -eq "stopped") {
Write-Host 'Service Stop Pass (0)'
} else {
Write-Host 'Service Stop Failed (1000)';
exit '1000'
}
}
#Start batch
if ($services.Status -eq "Stopped") {
Start-Process "cmd.exe" "/c C:\download\hello.bat"
} else {
Start-Sleep -s 10
}
The following should work:
$services = 'StiSvc', 'AdobeARMservice'
Stop-Service $services -ErrorAction Stop
& 'C:\download\hello.bat'
& 'C:\path\to\other.cmd'
#...
Start-Service $services
If it doesn't, you need to provide more information about what exactly fails, and how. Include all error and status messages.
Thank you all,
I modified the script as follow. The script stops 2 services, when the 2 services are stopped it start the batch file.
#Stop Services
Get-Service StiSvc, AdobeARMservice | Stop-Service
#Verify Services
if (((Get-Service StiSvc).Status -eq "stopped") -and
((Get-Service AdobeARMservice).Status -eq "stopped"))
# Start batch
{Start-Process "cmd.exe" "/c C:\download\hello.bat"}
I’m working on to improve the script. I’ll come back to you asap.
Regards
Related
I need to kill the process if start time is less than 2 hours.
I have written the below cmdlet to find out the starttime but how to find out if is it less than 2 hours:
get-process process1 | select starttime
There is also a possibility that on some hosts process1 is not running. so I need to check first if the process1 is running
You can use a loop of your choice, in this example ForEach-Object in addition to an if condition to check if the StartTime value is lower than 2 hours.
If you need to check first is the process is running then you would need to get all processes and filter by the process name you're looking for. Then check if the returned value from Where-Object is $null or not.
$procName = 'myprocess'
$process = Get-Process | Where-Object Name -EQ $procName
if(-not $process) {
Write-Warning "$procName not found!"
}
else {
$process | ForEach-Object {
if($_.StartTime -lt [datetime]::Now.AddHours(-2)) {
try {
'Attempting to stop {0}' -f $_.Name
Stop-Process $_ -Force
'{0} successfully stopped.' -f $_.Name
}
catch {
Write-Warning $_.Exception.Message
}
}
}
}
I need to check for running Services on different Windows Servers.
there can be two services running (old or new version or both, with slightly different names)
need the output like: "new version" , "old version" or "both versions"
I wanted to simply check with the Get-Process command but I can't really get to a conclusion how to get my output and how to check if both are running.
Started like the following: how can I finish my script? or am I completely wrong? couldn't find anything that helps.
if (Get-Service "NAME" -ErrorAction SilentlyContinue | Where-Object {$_.Status -eq "Running"})
{Write-Host "New Client running"
}
if (Get-Service "NAME_old" -ErrorAction SilentlyContinue | Where-Object {$_.Status -eq "Running"})
{Write-Host "old Client running"
}
Else {Write-Host ”No Client found”}
obviously this script doesn't quite work. tested on a Server where only the new client is running and it outputs:
New Client running
No Client found
Change the second if statement to elseif - this way the else block only runs if neither of the two preceding conditions hold true:
if (Get-Service "NAME" -ErrorAction SilentlyContinue | Where-Object {$_.Status -eq "Running"})
{
Write-Host "New Client running"
}
elseif (Get-Service "NAME_old" -ErrorAction SilentlyContinue | Where-Object {$_.Status -eq "Running"})
{
Write-Host "old Client running"
}
else {
Write-Host "No Client found"
}
You can do this with your three if statements if you track your Get-Service results:
if ($newclient = Get-Service "NAME" -ErrorAction SilentlyContinue | Where Status -eq Running) {
Write-Host 'New Client running'
}
if ($oldclient = Get-Service "NAME_old" -ErrorAction SilentlyContinue | Where Status -eq Running) {
Write-Host 'old Client running'
}
if (-not ($newclient -or $oldclient)) {
Write-Host 'No Client found'
}
Slightly different approach :
"name1", "name2" | Get-Service | foreach-object {
write-host $_.name $_.status
}
Of course depends on logic required after
if you are interested in a little more scalable solution, I would suggest following:
I used $appsRunning to increment each time the script find a running service, so if you are interested in a total count of running services (from the $services list) you could use that variable.
$services = #(
[pscustomobject]#{ Name = "NAME"; Description = "New App" },
[pscustomobject]#{ Name = "NAME_old"; Description = "Old App" }
)
$appsRunning = 0
foreach ($service in $services) {
$app = Get-Service $service.Name
if ($app.status -eq "Running"){
write-host $service.Description is $app.status
$appsRunning++
}
}
if ($appsRunning -eq 0) {
Write-Host "No app Running"
I have a program foo.exe
foo.exe sometxtfile -arg0 10 -arg1 "cats" -arg3 666
It currently crashes with an exception. I have the project in visual studio and could put that command line into the visual studio debug startup but I'd like to be more flexible and be able to start this from powershell.
I am aware of Debug-Process but that only debugs a currently running process. Would it be possible to use this to launch and debug?
The trick is to wait for the process to start the job as a background process and then call Debug-Process on it.
start-job {
foo.exe sometxtfile -arg0 10 -arg1 "cats" -arg3 666
}
$process="foo"
Write-Host "Waiting for $process to start"
Do {
$status = Get-Process $process -ErrorAction SilentlyContinue
If (!($status)) {
Write-Host -NoNewline '.'
}
Else {
Write-Host ""
Write-Host "$process has started"
$started = $true
}
}
Until ( $started )
debug-process -Name ${process}
debug-process -Name ${process}
I am trying to run a perl script whenever there is a service crash. The perl script intends to restart the service and send a mail to all the developers.
I have used windows recovery options for that, where it has an option to run a program . I have filled the required details in the command line option but the script doesn't seem to get executed. Can you please help me by sharing your knowledge on this?
Recovery tab configuration
I have tried with Restart service option and that is working fine but the run a program isn't executing the script. Am I missing something?
Any comment on this will be helpful.
I recently implemented a recovery option to run a powershell script that attempts to restart the service a defined number of times and sends an email notification at the conclusion, it also attaches a txt file with recent relevant logs.
After several attempts (and despite all the other things I have seen) The configuration of fields on the recovery tab in services is as follows:
Program: Powershell.exe
**Not C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe
Command line parameters: -command "& {SomePath\YourScript.ps1 '$args[0]' '$args[1]' '$args[n]'}"
eg: -command "& {C:\PowershellScripts\ServicesRecovery.ps1 'Service Name'}"
**The $args are parameters that will be passed to your script. These are not required.
here is the powershell script:
cd $PSScriptRoot
$n = $args[0]
function CreateLogFile {
$events = Get-EventLog -LogName Application -Source SomeSource -Newest 40
if (!(Test-Path "c:\temp")) {
New-Item -Path "c:\temp" -Type directory}
if (!(Test-Path "c:\temp\ServicesLogs.txt")) {
New-Item -Path "c:\temp" -Type File -Name "ServicesLogs.txt"}
$events | Out-File -width 600 c:\temp\ServicesLogs.txt
}
function SendEmail {
$EmailServer = "SMTP Server"
$ToAddress = "Name#domain.com"
$FromAddress = "Name#domain.com"
CreateLogFile
$Retrycount = $Retrycount + 1
send-mailmessage -SmtpServer $EmailServer -Priority High -To $ToAddress -From $FromAddress -Subject "$n Service failure" `
-Body "The $n service on server $env:COMPUTERNAME has stopped and was unable to be restarted after $Retrycount attempts." -Attachments c:\temp\ServicesLogs.txt
Remove-Item "c:\temp\ServicesLogs.txt"
}
function SendEmailFail {
$EmailServer = "SMTP Server"
$ToAddress = "Name#domain.com"
$FromAddress = "Name#domain.com"
CreateLogFile
$Retrycount = $Retrycount + 1
send-mailmessage -SmtpServer $EmailServer -Priority High -To $ToAddress -From $FromAddress -Subject "$n Service Restarted" `
-Body "The $n service on server $env:COMPUTERNAME stopped and was successfully restarted after $Retrycount attempts. The relevant system logs are attached." -Attachments c:\temp\ServicesLogs.txt
Remove-Item "c:\temp\ServicesLogs.txt"
}
function StartService {
$Stoploop = $false
do {
if ($Retrycount -gt 3){
$Stoploop = $true
SendEmail
Break
}
$i = Get-WmiObject win32_service | ?{$_.Name -imatch $n} | select Name, State, StartMode
if ($i.State -ne "Running" -and $i.StartMode -ne "Disabled") {
sc.exe start $n
Start-Sleep -Seconds 35
$i = Get-WmiObject win32_service | ?{$_.Name -imatch $n} | select State
if ($i.state -eq "Running"){
$Stoploop = $true
SendEmailFail}
else {$Retrycount = $Retrycount + 1}
}
}
While ($Stoploop -eq $false)
}
[int]$Retrycount = "0"
StartService
I need to start an ordered sequence of services, i need that each service will be up and running before try to start the next one, how can I achieve this in Powershell? How can I wait for the stop too?
Thanks,
DD
Don't do this manually (regardless of scripting language). Define proper dependencies between the services and Windows will start/stop them in the correct order. You can use the sc utility to define the dependencies:
sc config Svc2 depend= Svc1
If a service should depend on more than one other service you separate the dependent services with forward slashes:
sc config Svc5 depend= Svc3/Svc4
Note that the = must be followed by a space and must not be preceded by one.
If you have a list of service names (say in an array), then foreach service:
Get its status
If not running, then start it
With a delay in the loop, check its status until it is running
The key is likely to be handling all the possibilities for #3 including the service failing.
But an outline would be something like (without handling the error cases):
$serviceNames | Foreach-Object -Process {
$svc = Get-Service -Name $_
if ($svc.Status -ne 'Running') {
$svc.Start()
while ($svc.Status -ne 'Running') {
Write-Output "Waiting for $($svc.Name) to start, current status: $($svc.Status)"
Start-Sleep -seconds 5
}
}
Write-Output "$($svc.Name) is running"
}
Get-Service returns an instance of System.ServiceProcess.ServiceController which is "live"—indicating the current state of the service, not just the state when the instance was created.
A similar stop process would replace "Running" with "Stopped" and the "Start" call with "Stop". And, presumably, reverse the order of the list of services.
To stop Services
$ServiceNames = Get-Service | where {($_.Name -like "YourServiceNameHere*")-and ($_.Status -eq "Running")}
Foreach-Object {$_.(Stop-Service $serviceNames)}
To start Services
$ServiceNames = Get-Service | where {($_.Name -like "YourServiceNameHere*")-and ($_.Status -ne "Running")}
Foreach-Object {$_.(Start-Service $ServiceNames)}
To start and wait in order
[array]$Services = 'svc1', 'svc2', 'svc3'
$Services | foreach {
start-service $_
(get-service $_).WaitForStatus('Running')
}
The wait for status might not be needed. I have no system that have slow services to test with.
To stop and wait in order
[array]$Services = 'svc1', 'svc2', 'svc3'
[array]::Reverse($Services)
$Services | stop-service