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

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

Related

SSMS agent job using scp command to transfer files to sftp is going to loop and not completing

Have tried different approaches to make the SSMs job working with SCP command with perl script. but the job is going into loop with out having a result.
PS : The script is working fine with running from command prompt directly.
command used in the perl script:-
$Command = "scp -i D:\File1\RS2\DataFeed\Code\PrivateKey.ppk -s $InternalFile admin#sftp.world.com:$VendorName/$DestFileName";
system command used in perl
system($command);
While running the command directly from windows cmd it is correctly placing file to the SFTP. but while running this perl script from ssms agent job it seems not working and the job is keep running without any results.
Any possible leads to the actual errors will be much appreciated
Detailed Steps :
Job in SSMS :
Step :
DataFeed.cmd
%_Debug% echo off
cd /d %0\..
pushd .
setlocal
rem -----------------------------------------------------------------
rem Localize environment
rem -----------------------------------------------------------------
if exist DataFeed_Environment.cmd (
call DataFeed_Environment.cmd
) else (
echo DataFeed_Environment.cmd not found!!!
echo
goto CmdUsage
)
rem -----------------------------------------------------------------
rem Run perl package
rem -----------------------------------------------------------------
C:\Perl\bin\perl.exe DataFeedProd1.pl
if %ERRORLEVEL% NEQ 0 goto ErrorExit
goto Exit
rem -----------------------------------------------------
rem Command Usage
rem -----------------------------------------------------
:CmdUsage
Echo ---------------------------------------------------------------------
echo.
echo DataFeed.cmd
echo Wraps the call to DataFeed.pl,
echo mails log upon errors.
echo.
echo Usage:
echo DataFeed.cmd
echo.
echo ----------------------------------
rem endlocal
rem popd
rem exit 1
rem -----------------------------------------------------------------
rem Error exit
rem -----------------------------------------------------------------
:ErrorExit
echo DataFeedProd1.pl failed !!!
echo
rem endlocal
rem popd
rem exit 1
rem -----------------------------------------------------------------
rem Exit
rem -----------------------------------------------------------------
rem endlocal
rem popd
:Exit
rem exit 0
sub CopyDataFeedFileToSftp{
my ($DataFeedFileInternal, $DataFeedVendorName,$DataFeedFileName) = #_;
my($DestFileName)=$DataFeedFileName.".zip";
my($Command);
my($RetValue) = 1;
$Command = "C:\\Users\\hprasu\\Downloads\\OpenSSH-Win64\\scp.exe -i D:\\File1\\RS2\\DataFeed\\Code\\PrivateKey.ppk -s $DataFeedFileInternal a_Tne\#nasftp\.egencia.com:$DataFeedVendorName/$DestFileName";
$RetVal = &CallSystem($Command);
if ($RetVal == 0) {
&AppendFileToLog($TempFile);
&ErrorExit("Unable to copy data feed file using SCP command:\n".$Command);
}
}
The above perl method is executing the System command
You should:
have full path to perl.exe and your perl script in job's command
escape all special characters in interpolated strings for Perl and
use full path for scp command since
operating system don't know where scp.exe is located (until it in the $PATH):
check filesystem permissions for all files in the command and perl script. Job should has access those files.
So command would be
$Command = "full_path\\scp.exe -i D:\\File1\\RS2\\DataFeed\\Code\\PrivateKey.ppk -s $InternalFile admin\#sftp.world.com:$VendorName/$DestFileName";
Read this:
https://www.geeksforgeeks.org/perl-quoted-interpolated-and-escaped-strings/

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

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...

Build a command and execute it from within a batch file

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"