Here is the bat command which uses for checking service status and according to condition either stop the service or start service.
//Bat Command
for /F "tokens=3 delims=: " %%H in ('sc query wuauserv ^| findstr "STATE"') do ( if /I "%%H" NEQ "Running" ( net start wuauserv ) else (echo "Hello World"))
//JenkinsFile
bat 'for /F "tokens=3 delims=: " %%H in ('sc query wuauserv ^| findstr "STATE"') do ( if /I "%%H" NEQ "Running" ( net start wuauserv ) else (echo "Hello World"))'
when I put the batch command in the Jenkins file showing a syntax error. in the end when I remove the syntax Error but now command did not work properly
//Without Syntax Error Jenkins file
bat 'for /F "tokens=3 delims=: " %%H in ("sc query wuauserv ^| findstr "STATE"") do ( if /I "%%H" NEQ "Running" ( net start wuauserv ) else (echo "Hello World"))'
I just want that batch command to fit in the Jenkins file and work properly.
CodePudding user response:
The command you are using in your batch file is unnecessary for the purposes you are using it.
Perhaps the following batch file command would serve you better:
@%SystemRoot%\System32\sc.exe Query wuauserv | %SystemRoot%\System32\findstr.exe /R /C:"STATE *: 1 *" 1>NUL && (Start %SystemRoot%\System32\sc.exe Start wuauserv) || Echo "Hello World"
Please note however that || Echo "Hello World"
is probably not necessary as is, because the host would have exited before you ever have time to have read that.
@%SystemRoot%\System32\sc.exe Query wuauserv | %SystemRoot%\System32\findstr.exe /R /C:"STATE *: 1 *" 1>NUL && Start %SystemRoot%\System32\sc.exe Start wuauserv
You may note that I've used 1
, (STOPPED), instead of RUNNING
for my check. Not only does that keep the command non language dependent, it is possible that 2
(START_PENDING), 3
(STOP_PENDING), and 4
(RUNNING), are returned, non of which are in a current state to be started. Your method treats anything which is not RUNNING as if it can be started, but as you can see above, that is not the case.
CodePudding user response:
I figure it out by simply skipping the ('') because these are used again in the command causing the syntax error so I skip them by using \ in the command. the command now works perfectly fine without groovy syntax Error.
//Here is the Example
bat 'for /F "tokens=3 delims=: " %%H in (\'sc query wuauserv ^| findstr "STATE"\') do ( if /I "%%H" EQU "Running" ( net stop wuauserv ) else (echo "Service already stopped"))'