Azure DevOps Build Pipeline cmd.exe exited with code '1' - cmd

I'm currently looking to do a "If the service doesn't exist, create it" in my DevOps Pipeline, but I'm consistently getting the " cmd.exe exited with code '1' " error...
The problem I have, is that when I run this exact code in a batch file, it works without any errors:
- task: CmdLine#2
displayName: Create install script for windows service communication
inputs:
script: >-
(
echo #echo off
setlocal EnableDelayedExpansion
set _ServiceName=SalesOrderManagement.WindowsService1
sc query %_ServiceName% | find "does not exist" >nul
if %ERRORLEVEL% EQU 0 sc.exe create %_ServiceName% binpath= C:\appservice\SalesOrderManagement.WindowsService\SalesOrderManagement.WindowsService.exe displayname= %_ServiceName%
sc.exe description %_ServiceName% $(Build.BuildNumber)
net start %_ServiceName%
) > C:\appservice\SalesOrderManagement.WindowsService\ServiceStart.txt
What am I missing?

Related

Running batch script with two msiexec commands causes finishing script just after finishing first command

I am trying to run batch script from jenkins job which has two msiexec commands one for uninstallation and other for installation.
This script is on github so jenkins job clone the repo and then run the script
Jenkins job start execution of second msiexec (installation) command but it ends immediately.If i open Job console i can see message "Process leaked file descriptors." and job status : Success
If i run The same script through cmd without jenkins it is working fine.
setlocal enabledelayedexpansion
IF EXIST "directory path" (
msiexec /uninstall {Product ID} /qb
)
pushd \\shared drive
IF EXIST "directory path" (
msiexec /i "path to exefile" /qb
popd
exit 0
)
ELSE (
ECHO Setup Not Found in current
exit 0
)
The keyword ELSE must be on same line as ) of TRUE branch of IF condition separated from ) by a space character. The ELSE on a separate line is interpreted like name of a console application to run.
if exist "directory path" (
%SystemRoot%\System32\msiexec.exe /uninstall {Product ID} /qb
)
pushd "\\ComputerName\ShareName\"
if exist "directory path" (
%SystemRoot%\System32\msiexec.exe /i "path to exefile" /qb
) else (
echo Setup not found in %CD%.
)
popd
exit /B 0
Hint: For debugging a batch file run it from within a command prompt window and not with double clicking on it after removing or commenting all lines containing echo off. And don't use EXIT without /B as this results always in exiting entire command process and not only in exiting just processing of current batch file. Debugging a batch file in a command prompt window becomes difficult if the batch file contains EXIT without /B and this command is really executed on running the batch file because error messages output during running the batch file can't be seen in this case.

Configuring Jenkins CI Job and FreeFileSync Batch Using Windows Batch Command

I have just setup Jenkins CI as my build server but I have an issue with correctly configuring FreeFileSync batch file and the command that calls the batch file used for deploying the application after building it.
call Path\deploy.ffs_batch
The build console displays success if deploy.ffs_batch execution was successful. But in the case of where the deploy.ffs_batch settings was wrong for example wrong path as destination, the build never stops and console log spinner on Hudson keeps spinning without stopping and without giving any information.
What I have tried is adding this command below the one above to the Windows batch command:
if %errorlevel% neq 0 exit %errorlevel%
But build still not happy (spinner keeps spinning).
However, when I check the log folder for FreeFileSync batch file, I see this:
[03:52:46 PM] Info: Starting comparison
[03:52:46 PM] Error: Cannot find the following folders:
D:\Deploy\1\Dev
You can ignore this error to consider each folder as empty. The folders then will be created automatically during
synchronization.
[03:52:46 PM] Error: Synchronization stopped
I do understand the error and I can fix it. But I really do not want to always look in the log folder for answers when this occurs. So my question is how can I output the FreeFileSync error on Hudson console log and also abort the build using Windows batch command?
I discovered that I was missing one vital step when an error occurred and that is stopping the synchronization when an error occurs to prevent hudson job build from running endlessly.
After setting this to stop, I update my batch command to:
cd "Path\FreeFileSync\"
FreeFileSync.exe "Path\deploy.ffs_batch"
echo.
echo.
echo ===============================================================================
echo ##### Results :
echo ===============================================================================
echo.
echo.
#echo off
for /f "delims=" %%x in ('dir "Path\logs\" /od /b') do set recent=%%x
echo.
echo ===============================================================================
if %ERRORLEVEL% == 0 goto SYNCSUCCESS
if %ERRORLEVEL% == 1 goto SYNCWARNINGS
if %ERRORLEVEL% == 2 goto SYNCERRORS
if %ERRORLEVEL% == 3 goto SYNCABORTED
goto SYNCFAIL
:SYNCFAIL
echo ##### FreeFileSync failed.
type "path\logs\%recent%"
exit 2
:SYNCSUCCESS
echo ##### FreeFileSync completed successfully!
exit 0
:SYNCWARNINGS
echo ##### FreeFileSync completed, but with warnings.
type "path\logs\%recent%"
exit 1
:SYNCERRORS
echo ##### FreeFileSync completed, but with warnings.
type "path\logs\%recent%"
exit 2
:SYNCABORTED
echo ##### FreeFileSync aborted.
type "path\logs\%recent%"
exit 3
Please note: Run minimized checkbox needs to be checked also to avoid the job from running continously.
The job runs and stops when there is an error.

Batch file to check Windows services and Start them

I am trying to create a batch file that will sort 7 windows services into a list then check one by one if they're running, and if they aren't, start them.
What I have doesn't seem to be wokring and seems to echo set i=o. I am trying to find out how to properly execute the two for loops and if anybody has any suggestions for syntax that would be awesome
I was able to create a very primitive version but wanted to learn more about batch file "programming". This is what I've come up with so far:
::Enter in CC number
set /p CC=Enter The Site's CC:
#echo off
setlocal EnableDelayedExpansion
::Create vector with names of services
set i=0
for %%s in
("Apache Tomcat"
"OracleServicePD"
"OracleXETNSListener_bqw"
"System Audit Service"
"RPOS ScemComms Service"
"RPOS debit credit service"
"RPOS Remote Device Service"
"RPOS Messaging Service"
) do (
set /A i=i+1
set services[!i!]=%%s
)
::Check if all services are running, if not go to it's respective net start method
::After all is checked, it goes to :check to show services are running
set n=0
:loop
for /L %%G in (0,1,7) do (
net start | find !services[%n%]! > nul 2>&1
if not "%errorlevel%"=="0"
set pathname=!services[%n%]!
set /A n=n+1
goto %pathname%
)
goto check
:"Apache Tomcat"
net start tomcat6
goto loop
:"OracleServicePD"
net start "OracleServicePD%CC%"
goto loop
:"OracleXETNSListener_bqw"
net start "OracleXETNSListener_bqw"
goto loop
:"System Audit Service"
net start "System Audit Service"
goto loop
:"RPOS ScemComms Service"
net start "RPOS ScemComms Service"
goto loop
:"RPOS debit credit service"
net start "RPOS debit credit service"
goto loop
:"RPOS Remote Device Service"
net start "RPOS Remote Device Service"
goto loop
:"RPOS Messaging Service"
net start "RPOS Messaging Service"
goto loop
:check
echo Apache Tomcat && sc query tomcat6 | find "STATE"
echo OracleServicePD%CC% && sc query "OracleServicePD%CC%" | find "STATE"
echo OracleXETNSListener_bqw && sc query "OracleXETNSListener_bqw" | find "STATE"
echo System Audit Service && sc query "System Audit Service" | find "STATE"
echo RPOS ScemComms Service && sc query "RPOS ScemComms Service" | find "STATE"
echo RPOS debit credit service && sc query "RPOS debit credit service" | find "STATE"
echo RPOS Remote Device Service && sc query "RPOS Remote Device Service" | find "STATE"
echo RPOS Messaging Service && sc query "RPOS Messaging Service" | find "STATE"
first, your first service is services[1], but your loop starts with 0.
more importantly, where does %n% come from? you mean %%G here.
sc start AeLookupSvc&&echo Started||(sc start AeLookupSvc|Findstr /c:"1056"&&Echo Already Running||Echo Error starting service)
Your pattern of testing then doing is not a good programming technique. You do and test if it worked.
The above does one service and reports if already running, if it was started, or what error prevents it starting. All in one line.
From MSDos 6.22 Help File.
│The following list shows each exit code and a brief description of its
│meaning:
│
│0
│ The search was completed successfully and at least one match was found.
│
│1
│ The search was completed successfully, but no matches were found.
│
│2
│ The search was not completed successfully. In this case, an error
│ occurred during the search, and FIND cannot report whether any matches
│ were found.
│
│You can use the ERRORLEVEL parameter on the command line in a batch
│program to process exit codes returned by FIND.
A list of command line things.
& seperates commands on a line.
&& executes this command only if previous command's errorlevel is 0.
|| (not used above) executes this command only if previous command's errorlevel is NOT 0
> output to a file
>> append output to a file
< input from a file
| output of one command into the input of another command
^ escapes any of the above, including itself, if needed to be passed to a program
" parameters with spaces must be enclosed in quotes
+ used with copy to concatinate files. E.G. copy file1+file2 newfile
, used with copy to indicate missing parameters. This updates the files modified date. E.G. copy /b file1,,
%variablename% a inbuilt or user set environmental variable
!variablename! a user set environmental variable expanded at execution time, turned with SelLocal EnableDelayedExpansion command
%<number> (%1) the nth command line parameter passed to a batch file. %0 is the batchfile's name.
%* (%*) the entire command line.
%<a letter> or %%<a letter> (%A or %%A) the variable in a for loop. Single % sign at command prompt and double % sign in a batch file.
.

how to check the windows taks services through unix batch

Daily I am checking windows services by manualy (start -> run ->services.msc).
But i want to automat it through scripts.
How can I check the status (started or stopped) of the particular window service (eg.tomcat) using UNIX script(.bat)?
You can use sc query or net start to do this.
For eg.
#echo off
sc query "ServiceName" | findstr RUNNING
if %ERRORLEVEL% == 0 goto working
echo Not Running
:working
echo Running
goto end
:end
or
#echo off
net start | findstr "ServiceName"
if %ERRORLEVEL% == 0 goto working
echo Not Running
goto end
:working
echo Running
:end

How to test whether a service is running from the command line

I would like to be able to query whether or not a service is running from a windows batch file. I know I can use:
sc query "ServiceName"
but, this dumps out some text. What I really want is for it to set the errorlevel environment variable so that I can take action on that.
Do you know a simple way I can do this?
UPDATE
Thanks for the answers so far. I'm worried the solutions that parse the text may not work on non English operating systems. Does anybody know a way around this, or am I going to have to bite the bullet and write a console program to get this right.
sc query "ServiceName" | find "RUNNING"
Let's go back to the old school of batch programing on windows
net start | find "Service Name"
This will work everywhere...
if you don't mind to combine the net command with grep you can use the following script.
#echo off
net start | grep -x "Service"
if %ERRORLEVEL% == 2 goto trouble
if %ERRORLEVEL% == 1 goto stopped
if %ERRORLEVEL% == 0 goto started
echo unknown status
goto end
:trouble
echo trouble
goto end
:started
echo started
goto end
:stopped
echo stopped
goto end
:end
You could use wmic with the /locale option
call wmic /locale:ms_409 service where (name="wsearch") get state /value | findstr State=Running
if %ErrorLevel% EQU 0 (
echo Running
) else (
echo Not running
)
Thinking a little bit outside the box here I'm going to propose that powershell may be an answer on up-to-date XP/2003 machines and certainly on Vista/2008 and newer (instead of .bat/.cmd). Anyone who has some Perl in their background should feel at-home pretty quickly.
$serviceName = "ServiceName";
$serviceStatus = (get-service "$serviceName").Status;
if ($serviceStatus -eq "Running") {
echo "Service is Running";
}
else {
#Could be Stopped, Stopping, Paused, or even Starting...
echo "Service is $serviceStatus";
}
Another way, if you have significant investment in batch is to run the PS script as a one-liner, returning an exit code.
#ECHO off
SET PS=powershell -nologo -command
%PS% "& {if((get-service SvcName).Status -eq 'Running'){exit 1}}"
ECHO.%ERRORLEVEL%
Running as a one-liner also gets around the default PS code signing policy at the expense of messiness. To put the PS commands in a .ps1 file and run like powershell myCode.ps1 you may find signing your powershell scripts is neccessary to run them in an automated way (depends on your environment). See http://www.hanselman.com/blog/SigningPowerShellScripts.aspx for details
#ECHO OFF
REM testing at cmd : sc query "MSSQLSERVER" | findstr RUNNING
REM "MSSQLSERVER" is the name of Service for sample
sc query "MSSQLSERVER" %1 | findstr RUNNING
if %ERRORLEVEL% == 2 goto trouble
if %ERRORLEVEL% == 1 goto stopped
if %ERRORLEVEL% == 0 goto started
echo unknown status
goto end
:trouble
echo Oh noooo.. trouble mas bro
goto end
:started
echo "SQL Server (MSSQLSERVER)" is started
goto end
:stopped
echo "SQL Server (MSSQLSERVER)" is stopped
echo Starting service
net start "MSSQLSERVER"
goto end
:erro
echo Error please check your command.. mas bro
goto end
:end
I would suggest
WMIC Service WHERE "Name = 'SericeName'" GET Started
or WMIC Service WHERE "Name = 'ServiceName'" GET ProcessId (ProcessId will be zero if service isn't started)
You can set the error level based on whether the former returns "TRUE" or the latter returns nonzero
sc query "servicename" | findstr STATE
for example:
sc query "wuauserv" | findstr STATE
To report what the Windows update service is doing, running/paused etc.This is also for Windows 10. Thank me later.
Try
sc query state= all
for a list of services and whether they are running or not.
I've found this:
sc query "ServiceName" | findstr RUNNING
seems to do roughly the right thing. But, I'm worried that's not generalized enough to work on non-english operating systems.
Just to add on to the list if you are using Powershell.
sc.exe query "ServiceName" | findstr RUNNING
The command below does not work because sc is an alias to Set-Content within Powershell.
sc query "ServiceName" | findstr RUNNING
find also does not work on Powershell for some reason unknown to me.
sc.exe query "ServiceName" | find RUNNING
SERVICO.BAT
#echo off
echo Servico: %1
if "%1"=="" goto erro
sc query %1 | findstr RUNNING
if %ERRORLEVEL% == 2 goto trouble
if %ERRORLEVEL% == 1 goto stopped
if %ERRORLEVEL% == 0 goto started
echo unknown status
goto end
:trouble
echo trouble
goto end
:started
echo started
goto end
:stopped
echo stopped
goto end
:erro
echo sintaxe: servico NOMESERVICO
goto end
:end
I noticed no one mentioned the use of regular expressions when using find/findstr-based Answers. That can be problematic for similarly named services.
Lets say you have two services, CDPUserSvc and CDPUserSvc_54530
If you use most of the find/findstr-based Answers here so far, you'll get false-positives for CDPUserSvc queries when only CDPUserSvc_54530 is running.
The /r and /c switches for findstr can help us handle that use-case, as well as the special character that indicates the end of the line, $
This query will only verify the running of the CDPUserSvc service and ignore CDPUserSvc_54530
sc query|findstr /r /c:"CDPUserSvc$"
Use Cygwin Bash with:
sc query "SomeService" |grep -qo RUNNING && echo "SomeService is running." || echo "SomeService is not running!"
(Make sure you have sc.exe in your PATH.)
I have created one based from above but will show if the service is installed first then get whether it is running or not.
sc query "YourService" | find /i "failed" 2>&1>nul && echo.'YourService Not Installed' || (sc query "YourService"| find /i "running" 2>&1>nul && echo.Yes || echo.No)

Resources