Saving cURL and jq output to a variable in batch script - batch-file

I use this command in order to retrieve a result of a build in Jenkins:
curl -s http://<jenkins_url>/job/<job_name>/lastCompletedBuild/api/json | jq ."result"
Based on that result I need to decide an action to be performed using a batch command,
How do I save the output of the command as a variable?

You should be able to use a For /F command in a batch file to return the output of a command to a variable:
For /F "Delims=" %%A In ('"curl -s http://<jenkins_url>/job/<job_name>/lastCompletedBuild/api/json | jq ."result""') Do Set "test=%%~A"
If /I "%test%"=="failed" ...DoSomething
If /I "%test%"=="success" ...DoSomethingElse
If /I "%test%"=="unstable" ...DoAnotherThing
However there may be no need to set a variable at all, because you can work with the returned metavariable directly:
For /F "Delims=" %%A In ('
"curl -s http://<jenkins_url>/job/<job_name>/lastCompletedBuild/api/json | jq ."result""
') Do (
If /I "%%~A"=="failed" ...DoSomething
If /I "%%~A"=="success" ...DoSomethingElse
If /I "%%~A"=="unstable" ...DoAnotherThing
)

Related

Bat file replace character

I use bat script to backup MySQl database
SET SOURCEDIR="C:\Program Files\MariaDB\data\"
set now=%DATE:~-4%-%DATE:~3,2%-%DATE:~0,2%
for /d %%i in (%SOURCEDIR%\*) do (
if not "%%~ni"=="temp" "C:\Program Files\MariaDB\bin\mysqldump.exe" -uroot -h127.0.0.1 -c -e -q --single-transaction=TRUE %%~ni | "c:\Program Files\7-Zip\7z.exe" a -si"%%~ni_%now%.sql" "D:\backup\SQL\%now%\%%~ni.sql.7z"
)
exit
But if database have dot in name, for exapmle data.2023, then MariDB create folder data#002e2023
So SQL dump is empty.
How can I replace #002e to . in this script here *single-transaction=TRUE %%~ni | *?
%%~ni:#002e=!.!% is not working
Based upon your attempt, %%~ni:#002e=!.!%, I'd assume you need to create a variable, and delay variable expansion to use it.
Example:
#Set "SOURCEDIR=%ProgramFiles%\MariaDB\data"
#Set "now=%DATE%"
#Set "now=%now:~-4%-%now:~-7,2%-%now:~-10,2%"
#For /D %%G In ("%SOURCEDIR%\*") Do #If /I Not "%%~nxG" == "temp" (
Set "dirname=%%~nxG"
SetLocal EnableDelayedExpansion
"%ProgramFiles%\MariaDB\bin\mysqldump.exe" -uroot -h127.0.0.1 -c -e -q --single-transaction=TRUE !dirname:#002e=.!^
| "%ProgramFiles%\7-Zip\7z.exe" a -si"%%~nxG_%now%.sql" "D:\backup\SQL\%now%\%%~nxG.sql.7z"
EndLocal)

How can you run sqlcmd in a batch script with passing variables?

I'm trying to use a Windows command prompt on Server 2012 R2 to run a batch file with the following command line. I want to run an SQL command (sqlcmd) and return the results to the console window.
This is what I'm currently trying, but sqlcmd keeps throwing back:
Sqlcmd: 'test': Invalid argument. Enter '-?' for help.
FOR /F "tokens=* USEBACKQ" %%F IN (`sqlcmd -S localhost -E -i "backup.sql" -v dbname="test"`) DO (
Echo %%F
)
Note: I have also tried to run just this sqlcmd command (above) in a command prompt with no issues. It's like it does not like the FOR /F loop or something.
However if I try it without parameters/variables it works perfectly!
FOR /F "tokens=* USEBACKQ" %%F IN (`sqlcmd -S localhost -E -i "backup.sql"`) DO (
Echo %%F
)
Does anyone know a way around getting the variables passed to my SQL query using sqlcmd, Windows CMD, as well as a FOR /F loop such as in my first example?
When a line batch code is processed it goes through multiple phases, in a specific order. The order of these phases means that in this case your equals character, = requires special attention. For a full explanation on these phases read this information.
Here's two methods, one of which was already given in the comment area.
I have formatted the command over three lines so that it's clearer, whether you do that too is optional.
Escape the equals character = with a caret ^:
For /F "Delims=" %%A In ('
sqlcmd -S localhost -E -i backup.sql -v dbname^=test
') Do Echo %%A
Or if you wish to doublequote your filename and value:
For /F "Delims=" %%A In ('
sqlcmd -S localhost -E -i "backup.sql" -v dbname^="test"
') Do Echo %%A
Surround the command in doublequotes, ":
For /F "Delims=" %%A In ('
"sqlcmd -S localhost -E -i backup.sql -v dbname=test"
') Do Echo %%A
 
For /F "Delims=" %%A In ('
"sqlcmd -S localhost -E -i "back up.sql" -v dbname="my test""
') Do Echo %%A
Please note as shown above, whilst it's probably good practice, Microsoft state, 'File paths that contain spaces must be enclosed in quotation marks' and 'Enclose the value in quotation marks if the value contains spaces'. They were not needed in your case and could have been omitted.

Batch File to check text files for a string

im trying to create a batch file that goes thorugh each text file in a folder and looks for specific words such as "msg" "file" "size" in each line. If those words are found then it sends and me an email.
Im using SQL server to send the email, and im calling the email stored procedure from my batch file like this:
set MYDB= yourDBname
set MYUSER=youruser
set MYPASSWORD=yourpassword
set MYSERVER=yourservername
sqlcmd -S %MYSERVER% -d %MYDB% -U %MYUSER% -P %MYPASSWORD% -h -1 -s "," -W -Q "exec yourstoredprocedure"
I just need help writing the script which checks for specific words in each line in each .txt file
Just give a try for this batch file :
#echo off
Title Search String into text files
Set "ROOT=%~dp0"
set "String2Search=msg size file"
For %%a in (%String2Search%) do (
FOR /f "delims=" %%f IN ('dir /b /s "%ROOT%\*.txt"') DO (
(find /I "%%a" "%%f" >nul 2>&1) && ( Call :FoundString "%%a" "%%f" ) || ( Call :NoFound "%%a" "%%f" )
)
)
pause & exit
::*************
:FoundString
echo found %1 on file %2
goto :eof
::*************
:NoFound
echo no string like %1 found on file %2
goto :eof
::*************
Few suggestions as i cannot comment.I had done a project few years back and i had to do search files with a particular extension and read them to find particular words and do something with them.I remember few things only.I hope it helps you.
To find all txt files:
find /home/user/Downloads/etc -name '*txt'
To read a whole file and search for "msg" "file" "size":
while read -r LINE
do
grep -i "msg" | grep -i "file" | grep -i "size"
to check all in one line
Or you can do it executing one by one without "pipelining".
P.S I don't have linux installed otherwise I would have checked before posting.Sorry if not correct.
This should do the job:
#ECHO OFF
CD C:\wherever\your\.txt\files\are\at
FOR /R %%G IN ("*.txt") DO (FINDSTR /I /C:"msg" /C:"file" /C:"size" "%%G" >nul && GOTO match_found)
GOTO no_match
:match_found
ECHO Match found^!
set MYDB= yourDBname
set MYUSER=youruser
set MYPASSWORD=yourpassword
set MYSERVER=yourservername
sqlcmd -S %MYSERVER% -d %MYDB% -U %MYUSER% -P %MYPASSWORD% -h -1 -s "," -W -Q "exec yourstoredprocedure"
:no_match
ECHO No match found^!
PAUSE
If the batch file is in the same folder as the .txt files you can delete the CD line.
If the search should be case-sensitive remove the /I option.
To satisfy your question as asked, this should suffice:
#Echo Off
FindStr /IR "\<msg\> \<file\> \<size\>" "C:\Users\NT-Hero\*.txt">Nul||Exit /B
Rem Your 'match found' commands here
If you wanted to also search in sub-directories change the FindStr options to /SIR. (See FindStr /? for more options).

I want to run more than 1 command with the FOR /F

I'm trying to make a script to:
send a request to an url, then append (>>) the %%a variable i set in the FOR /F command IF i get a certain response from the command i run with FOR /F.
I tried with 2 scripts that are the followings:
FOR /F %%a in (usernames.txt) do (
IF "curl -k -d name=%%a https://club.pokemon.com/api/signup/verify-username" EQU "{"valid":true,"suggestions":[],"inuse":false}" %%a >> usernames1.txt
and
set /p VAR = < tmpFile
FOR /F %%a in (usernames.txt) do (
curl -k -d name=%%a https://club.pokemon.com/api/signup/verify-username
> tmpFile
IF VAR={"valid":true,"suggestions":[],"inuse":false}
%%a >> usernames1.txt)
EDIT: good enough with that script, thanks guys. but i've got another thing: can i add more than 1 variable to the script? I mean a variable like %%a, that takes every line from another txt file
First, you set VAR once, whereas your temporary file does not exist. Then you test with = instead of == and without the ! chars.
And don't put too many spaces like if you were using a real shell like bash :)
As Magoo noted, I also had to fix set /p VAR = < tmpFile to remove the extra spaces. Batch has a tendency to take them literaly.
(another example: echo foo > file: file now contains "foo ".
(needless to say that without enabledelayedexpansion it wouldn't work either because lots of things happen inside the FOR loop)
The fixed code (also had to protect the test string with extra quotes or it wouldn't work):
setlocal enabledelayedexpansion
del usernames1.txt >NUL 2>NUL
FOR /F %%a in (usernames.txt) do (
curl -k -d name=%%a https://club.pokemon.com/api/signup/verify-username > tmpFile 2>NUL
set /p VAR=<tmpFile
IF "!VAR!"=="{"valid":true,"suggestions":[],"inuse":false}" echo %%a >> usernames1.txt
)
I tested it with a random list of user names and changing "valid":true by "valid":false and the names were issued.

Batch to compare strings from 1st file to remove complete line on 2nd file

I need a batch file to pick each string (1 string = 1 line) in a FileA and search for it in FileB and remove the complete line from this FileB that has this string.
I tried several combinations using:
findstr /vixg:"FileA" "FileB" >"File.new"
type FileA.txt |findstr /v I%%
Do you guys have a solution for that?
Thanks
try something like this:
for /f "tokens=*" %%i in (fileA.txt) do ( type fileB.txt | find "%%~i" /v > fileB.txt )
I hope that these statemets can help you:
#echo off
set /p A="Insert first file path: "
:: FileA
set /p B="Insert second file path: "
:: FileB
for /f "delims=¶" %%g in (%B%) do (
findstr /c:"%%g" %A% > nul || echo %%g >> TEMP.txt
)
del /P %B%
ren TEMP.txt %B%
pause
However, with these statements it is possible to compare entire lines rather than only parts of a line, but I hope this is anyway what are you looking for.
Likely the shortest solution is to use grep, the right tool for this particular job. Use the -f option to read the patterns from FileA instead of from the command line, and the -v option to negate matches (i.e. print any line that's not matching):
grep -v -f FileA FileB

Resources