How to check if a service is running via batch file and start it, if it is not running?

后端 未结 14 1562
暖寄归人
暖寄归人 2020-11-30 18:15

I want to write a batch file that performs the following operations:

  • Check if a service is running
    • If is it running, quit the batch
    • If
相关标签:
14条回答
  • 2020-11-30 18:21

    To toggle a service use the following;

    NET START "Distributed Transaction Coordinator" ||NET STOP "Distributed Transaction Coordinator"

    0 讨论(0)
  • 2020-11-30 18:21

    Language independent version.

    @Echo Off
    Set ServiceName=Jenkins
    
    
    SC queryex "%ServiceName%"|Find "STATE"|Find /v "RUNNING">Nul&&(
        echo %ServiceName% not running 
        echo Start %ServiceName%
    
        Net start "%ServiceName%">nul||(
            Echo "%ServiceName%" wont start 
            exit /b 1
        )
        echo "%ServiceName%" started
        exit /b 0
    )||(
        echo "%ServiceName%" working
        exit /b 0
    )
    
    0 讨论(0)
  • Maybe a much simpler way? Just adding to the list of answers here:

    @for /f "tokens=1,* delims=: " %%a in ('sc queryex state=Inactive') do net start "%%b"
    
    0 讨论(0)
  • 2020-11-30 18:24

    Related with the answer by @DanielSerrano, I've been recently bit by localization of the sc.exe command, namely in Spanish. My proposal is to pin-point the line and token which holds numerical service state and interpret it, which should be much more robust:

    @echo off
    
    rem TODO: change to the desired service name
    set TARGET_SERVICE=w32time
    
    set SERVICE_STATE=
    rem Surgically target third line, as some locales (such as Spanish) translated the utility's output
    for /F "skip=3 tokens=3" %%i in ('""%windir%\system32\sc.exe" query "%TARGET_SERVICE%" 2>nul"') do (
      if not defined SERVICE_STATE set SERVICE_STATE=%%i
    )
    rem Process result
    if not defined SERVICE_STATE (
      echo ERROR: could not obtain service state!
    ) else (
      rem NOTE: values correspond to "SERVICE_STATUS.dwCurrentState"
      rem https://msdn.microsoft.com/en-us/library/windows/desktop/ms685996(v=vs.85).aspx
      if not %SERVICE_STATE%==4 (
        echo WARNING: service is not running
        rem TODO: perform desired operation
        rem net start "%TARGET_SERVICE%"
      ) else (
        echo INFORMATION: service is running
      )
    )
    

    Tested with:

    • Windows XP (32-bit) English
    • Windows 10 (32-bit) Spanish
    • Windows 10 (64-bit) English
    0 讨论(0)
  • 2020-11-30 18:25

    Starting Service using Powershell script. You can link this to task scheduler and trigger it at intervals or as needed. Create this as a PS1 file i.e. file with extension PS1 and then let this file be triggered from task scheduler.

    To start stop service

    in task scheduler if you are using it on server use this in arguments

    -noprofile -executionpolicy bypass -file "C:\Service Restart Scripts\StopService.PS1"

    verify by running the same on cmd if it works it should work on task scheduler also

    $Password = "Enter_Your_Password"
    $UserAccount = "Enter_Your_AccountInfor"
    $MachineName = "Enter_Your_Machine_Name"
    $ServiceList = @("test.SocketService","test.WcfServices","testDesktopService","testService")
    $PasswordSecure = $Password | ConvertTo-SecureString -AsPlainText -Force
    $Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $UserAccount, $PasswordSecure 
    
    $LogStartTime = Get-Date -Format "MM-dd-yyyy hh:mm:ss tt"
    $FileDateTimeStamp = Get-Date -Format "MM-dd-yyyy_hh"
    $LogFileName = "C:\Users\krakhil\Desktop\Powershell\Logs\StartService_$FileDateTimeStamp.txt" 
    
    
    #code to start the service
    
    "`n####################################################################" > $LogFileName
    "####################################################################" >> $LogFileName
    "######################  STARTING SERVICE  ##########################" >> $LogFileName
    
    for($i=0;$i -le 3; $i++)
    {
    "`n`n" >> $LogFileName
    $ServiceName = $ServiceList[$i]
    "$LogStartTime => Service Name: $ServiceName" >> $LogFileName
    
    Write-Output "`n####################################"
    Write-Output "Starting Service - " $ServiceList[$i]
    
    "$LogStartTime => Starting Service: $ServiceName" >> $LogFileName
    Start-Service $ServiceList[$i]
    
    $ServiceState = Get-Service | Where-Object {$_.Name -eq $ServiceList[$i]}
    
    if($ServiceState.Status -eq "Running")
    {
    "$LogStartTime => Started Service Successfully: $ServiceName" >> $LogFileName
    Write-Host "`n Service " $ServiceList[$i] " Started Successfully"
    }
    else
    {
    "$LogStartTime => Unable to Stop Service: $ServiceName" >> $LogFileName
    Write-Output "`n Service didn't Start. Current State is - "
    Write-Host $ServiceState.Status
    }
    }
    
    #code to stop the service
    
    "`n####################################################################" > $LogFileName
    "####################################################################" >> $LogFileName
    "######################  STOPPING SERVICE  ##########################" >> $LogFileName
    
    for($i=0;$i -le 3; $i++)
    {
    "`n`n" >> $LogFileName
    $ServiceName = $ServiceList[$i]
    "$LogStartTime => Service Name: $ServiceName" >> $LogFileName
    
    Write-Output "`n####################################"
    Write-Output "Stopping Service - " $ServiceList[$i]
    
    "$LogStartTime => Stopping Service: $ServiceName" >> $LogFileName
    Stop-Service $ServiceList[$i]
    
    $ServiceState = Get-Service | Where-Object {$_.Name -eq $ServiceList[$i]}
    
    if($ServiceState.Status -eq "Stopped")
    {
    "$LogStartTime => Stopped Service Successfully: $ServiceName" >> $LogFileName
    Write-Host "`n Service " $ServiceList[$i] " Stopped Successfully"
    }
    else
    {
    "$LogStartTime => Unable to Stop Service: $ServiceName" >> $LogFileName
    Write-Output "`nService didn't Stop. Current State is - "
    Write-Host $ServiceState.Status
    }
    }
    
    0 讨论(0)
  • 2020-11-30 18:26
    @Echo off
    
    Set ServiceName=wampapache64
    
    SC queryex "%ServiceName%"|Find "STATE"|Find /v "RUNNING">Nul&&(
    
    echo %ServiceName% not running
    echo  
    
    Net start "%ServiceName%"
    
    
        SC queryex "%ServiceName%"|Find "STATE"|Find /v "RUNNING">Nul&&(
            Echo "%ServiceName%" wont start
        )
            echo "%ServiceName%" started
    
    )||(
        echo "%ServiceName%" was working and stopping
        echo  
    
        Net stop "%ServiceName%"
    
    )
    
    
    pause
    
    0 讨论(0)
提交回复
热议问题