Created
February 16, 2024 18:18
-
-
Save brovish/321e5fd4f677eb9ffae839bb1d841db7 to your computer and use it in GitHub Desktop.
Revisions
-
brovish created this gist
Feb 16, 2024 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,41 @@ @echo off setlocal set "SERVICE_NAME=service_name" :: Check if the service exists using PowerShell for /f "delims=" %%i in ('powershell -Command "$service = Get-Service -Name '%SERVICE_NAME%' -ErrorAction SilentlyContinue; if ($null -eq $service) { Write-Output 'NotExists' } else { Write-Output 'Exists' }"') do set "SERVICE_EXISTS=%%i" if "%SERVICE_EXISTS%"=="NotExists" ( echo The service %SERVICE_NAME% does not exist. goto endScript ) :: Use PowerShell to check if the service is DISABLED for /f "delims=" %%i in ('powershell -Command "(Get-Service -Name '%SERVICE_NAME%').StartType"') do set "START_TYPE=%%i" if "%START_TYPE%"=="Disabled" ( echo The service %SERVICE_NAME% is DISABLED, no actions will be performed. goto endScript ) :: Use PowerShell to get the current state of the service for /f "delims=" %%a in ('powershell -Command "(Get-Service -Name '%SERVICE_NAME%').Status"') do set "SERVICE_STATE=%%a" :: Check the service state and act accordingly if "%SERVICE_STATE%"=="Stopped" ( echo The service %SERVICE_NAME% is STOPPED. Attempting to start it... net start "%SERVICE_NAME%" ) else if "%SERVICE_STATE%"=="Running" ( echo The service %SERVICE_NAME% is already RUNNING. Stopping and then restarting... net stop "%SERVICE_NAME%" net start "%SERVICE_NAME%" ) :endScript :: Use PowerShell to print the final status of the service, if it exists if "%SERVICE_EXISTS%"=="Exists" ( powershell -Command "Get-Service -Name '%SERVICE_NAME%' | Format-Table DisplayName, Status, StartType -AutoSize" ) endlocal