Build a command and execute it from within a batch file - code-generation

I have a batch file that outputs a list of commands which themselves can be executed at the command line.
Here is a simplified version of what I'm doing:
set %foldername%="c:\my_folder"
set %exename%="c:\my_utility.exe"
cd %foldername%
FOR /F "tokens=*" %%G IN ('dir *.xml /s /b /a:-d') DO #echo %exename% /x="%%G"
This basically outputs a batch file. It looks like this:
c:\my_utility.exe /x="c:\my_folder\file1.xml"
c:\my_utility.exe /x="c:\my_folder\file2.xml"
c:\my_utility.exe /x="c:\my_folder\file3.xml"
c:\my_utility.exe /x="c:\my_folder\file4.xml"
I want to execute these commands. Currently I have to redirect the output to a batch file and then run that. Is there any way to just say "execute this command I just constructed" in the dos prompt?

Just remove echo in the FOR loop:
FOR /F "tokens=*" %%G IN ('dir *.xml /s /b /a:-d') DO %exename% /x="%%G"

Related

Folder creation - from .bat file to powershell / sharepoint

I use a .bat file to create folders listed in two .txt files and also for deleting empty folders. All works fine but now I need the same to work on sharepoint.
Can anyone describe how or if this can be done? I have read that maybe I need to find put about powershell?
The .bat file looks like this:
echo off
%CHCP 1252
mkdir C:\Temp\MStruktur
Copy "P:\folderstructure\Niv1.txt" "C:\Temp\MStruktur"
Copy "P:\folderstructure\Niv2.txt" "C:\Temp\MStruktur"
cls
REM -----checking for empty characters
for %%a in (.) do set currentfolder=%%~na
if not "%currentfolder%"=="%currentfolder: =%" GOTO error
:home
echo "Folder structure menu:"
echo -------------------------------------
echo - 1 - create level 1
echo - 2 - create level 2
echo.
echo - S - Delete empty folders
echo.
echo - X - Exit
echo.
set /p web=Valg:
if "%web%"=="1" goto niv1
if "%web%"=="2" goto niv2
if "%web%"=="s" goto slet
if "%web%"=="x" goto slut
goto home
:niv1
cls
for /f %%i in (C:\Temp\MStruktur\niv1.txt) do mkdir %~dp0\%%i
echo.
echo Level 1 created
echo.
pause
exit
:niv2
cls
for /f %%i in (C:\Temp\MStruktur\niv2.txt) do mkdir %~dp0\%%i
echo.
echo Level 2 created
echo.
pause
exit
:slet
cls
for /f "delims=" %%d in ('dir %~dp0 /s /b /ad ^| sort /r') do rd "%%d"
echo.
echo Deleted empty folders
echo.
pause
exit
:error
cls
echo.
echo No blanks in folder name
echo.
pause
exit
:slut
RD /S /Q C:\Temp\MStruktur
exit

Running Commands in Batch FIle

I am trying to create a batch file to run start some micro services and database
1 FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :1000') DO #ECHO TaskKill.exe /PID %%P
2 FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :1001') DO #ECHO TaskKill.exe /PID %%P
3 FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :5432') DO #ECHO TaskKill.exe /PID %%P
4 start cd "C:\Program Files\PostgreSQL\10\bin\" & pg_ctl.exe -D "c:\Program Files\PostgreSQL\10\data" start
#REM to start service
5 start javaw -jar -Dserver.port=1000 text-annotation-tool-1.0-SNAPSHOT.jar
Line 1 to 3 and Line 5 execute correctly when executed by commenting line 4.
Line 4 is to start a Postgres server in a new prompt (beacuse of the Dir change). I think the problem is with the way I have used quotes. The 'start' at the beginning and ending of line 4 serve different purpose.
Also, if I execute line 4 in different prompt, How do I close the prompt after execution (nohup equivalent)
There are two errors: You can't "pass" cd to the start command. And start has the quirk to interpret the first quoted parameter as the new window's title. So start "C:\Program Files\PostgreSQL\10\bin\" ... wouldn't work, you need to supply a dummy window title. The & also seems wrong
So you need:
start "Postgres Server" "C:\Program Files\PostgreSQL\10\bin\pg_ctl.exe" -D "c:\Program Files\PostgreSQL\10\data" start
As the full path to pg_ctl.exe is supplied, there is no need for a cd.
But if you want to define the default directory for the new process, you have to use the /D parameter:
start "Postgres Server" /D "C:\Program Files\PostgreSQL\10\bin" pg_ctl.exe -D "c:\Program Files\PostgreSQL\10\data" start
Unrelated, but: putting the Postgres data directory into c:\Program Files\ is a very bad idea. That directory has special permissions for a purpose. You should use %ProgramData% or %AppData% instead

%%G from For Loop changing from index to %G using

I am trying to write a batch file to automate some routine Matlab processes. The batch file loops through from 0 to a set value (usually between 50 and 75) using the For /L structure. The script copies the main Matlab script to the subfolder and runs it. The batch would normally continue onward so I put a :loop to wait until the Matlab ends.
echo off
setlocal EnableDelayedExpansion
REM The format is matlab_auto.in (max value).
For /L %%G in (0,1,%1) do (
REM Sanity check
echo 1 %%G
REM Create Outputs folder if non-existent
if not exist Outputs md Outputs
REM Copy .m file into deg folder and cd to folder
copy values_calc.m %%Gsort\values_calc.m
cd %%Gsort
echo Got to folder
REM Running .m script and sanity check
echo 2 %%G
matlab -nosplash -nodesktop -noFigureWindows -logfile output.log -r "run('values_calc.m');"
echo 3 %%G
REM Waiting for matlab to finish
:loop
tasklist /fi "imagename eq MATLAB.exe" |find ":" > nul
echo 4 %%G
if errorlevel 1 goto loop
echo Finished Matlab
echo 5 %%G
REM Copy .m outputs into outputs folder, ignoring confirmation
copy Output_*.* ..\Outputs /Y
echo Copied outputs
REM Sanity check and return home
echo 6 %%G
cd %~dp0
echo Home again
)
The problem I'm having is that when it ends after the first iteration of the For loop. Echo 1, 2, 3 are 0. Echo 4 shows 0 the first time through :loop but then it shows %G for the remainder of the loops and at Echos 5 and 6. It also does not continue into further iterations of the For loop. I'm assuming this is because %%G is no longer a number (or in the range specified).
I have tried implementing a call subroutine to use the goto outside the loop but then it opens the Matlab dozens of times, crashing the computer.
Any insight or advice is appreciated. Thank you.
EDIT: Changed the :: for commenting to REM. It did not resolve this issue but looks better.
EDIT 2: I have a test case that demonstrates the problem. Its something with the :loop or goto.
echo off
setlocal EnableDelayedExpansion
for /l %%G in (0,1,5) do (
:loop
echo %%G
pause
if %%G==0 goto loop
)
Yes. The execution of a GOTO command cancel any active (pending) FOR or IF commands that may be nested inside parentheses at any level. This way, the commands placed below the :loop label are executed inside the FOR context the first time, but after the goto command they are executed as if they were placed outside the FOR loop! The way to solve this problem is extracting the code below the label into a subroutine and then call :loop in the FOR.
echo off
setlocal EnableDelayedExpansion
REM The format is matlab_auto.in (max value).
For /L %%G in (0,1,%1) do (
REM Sanity check
echo 1 %%G
REM Create Outputs folder if non-existent
if not exist Outputs md Outputs
REM Copy .m file into deg folder and cd to folder
copy values_calc.m %%Gsort\values_calc.m
cd %%Gsort
echo Got to folder
REM Running .m script and sanity check
echo 2 %%G
matlab -nosplash -nodesktop -noFigureWindows -logfile output.log -r "run('values_calc.m');"
echo 3 %%G
REM Waiting for matlab to finish
call :loop
echo Finished Matlab
echo 5 %%G
REM Copy .m outputs into outputs folder, ignoring confirmation
copy Output_*.* ..\Outputs /Y
echo Copied outputs
REM Sanity check and return home
echo 6 %%G
cd %~dp0
echo Home again
)
goto :EOF
:loop
tasklist /fi "imagename eq MATLAB.exe" |find ":" > nul
REM echo 4 %%G
if errorlevel 1 goto loop
exit /B

Delete all files after date, code is slow

I made a question last week about getting a batch file or code to delete all .txt files in a folder that were created before the last 60 days and I was directed to use the code below.
forfiles -p "J:\Test_Files" -s -m *.txt* -d 60 -c "cmd /c del #path"
This code does the job and works fine but it goes too slow deleting 250 files per minute. I need to delete a total of 2,600,000 files and this would take too long.
The code I used below deletes 200 files a second but deletes all .txt files
cd /BASE_PATH
del /s *.txt
How can I edit this code to delete files created before 60 days? I need it to delete at a faster pace.
Thank you for helping! :D
You can try with
#echo off
setlocal enableextensions disabledelayedexpansion
rem Configure script
set "target=J:\Test_Files"
set "fileMask=*.txt"
set "age=60"
rem We will use a temporary file.
for %%t in ("%temp%\%~nx0.%random%%random%%random%.tmp") do (
rem Send to temp file the list of matching files retrieved by the robocopy command
>"%%~ft" robocopy "%target%." "%target%." "%fileMask%" /minage:%age% /l /nocopy /is /s /njh /njs /ndl /nc /ns
rem Process temporary file deleting the selected files
for /f "usebackq tokens=*" %%f in ("%%~ft") do echo del "%%~ff"
rem Once done, remove the temporary file
) & del /q "%%~ft"
del commands are only echoed to console. If the output is correct, remove the echo command.

How to make a OR statement in a batch file?

Hi want to exclude 2 or more files from my batch file.
My batch file executes all SQL files in that folder.
Here is the code:
ECHO %USERNAME% started the batch process at %TIME% >output.txt
FOR %%G IN (*.sql) DO (
//IF would go here to skip unwanted files
sqlcmd.exe -S RMSDEV7 -E -d ChaseDataMedia7 -i "%%G" >>output.txt
)
pause
So, how would i add and if statemant to skip the files in the loop that i don't want to execute?
You can chain IFs;
FOR %%G IN (*.sql) DO (
if not %%G==foo.sql if not %%G==bar.sql (
some command "%%G"
)
)
#echo off
setlocal EnableDelayedExpansion
set unwantedFiles=foo bar baz
for %%g in (*.sql) do (
set "test=!unwantedFiles:%%~Ng=!"
if "!test!" == "!unwantedFiles!" (
echo %%~Ng.sql is not unwanted, process it:
echo Process with %%g
)
)
Take a name and copy unwantedFiles by removing current name. If the result is the same as before, this name is NOT in unwantedFiles, so process it...