Issue
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.
Solution
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"))'
Answered By - bitee
Answer Checked By - Candace Johnson (JavaFixing Volunteer)