onlyforbopi
11/13/2018 - 9:43 AM

DOS.Batch.Basics

  1. Variables 1.5 Environmental variables
  2. Conditionals
  3. Date Manip
  4. Input / Output Redirection
  5. Error Level Control
  6. Loops
  7. Command to Variable
@echo off


:: DrivesListaTranc.py


::python DrivesListaTranc.py > tempfile




:::::::::::::::::::::::::::::::::::::::
REM path1
REM path2
:: PATH3=''

SET PYTHONSCRIPTDIR=C:\Users\p.doulgeridis\Desktop\
SET FLASH_DRIVE=''

FOR /F "tokens=*" %%g IN ('python %PYTHONSCRIPTDIR%DrivesListaTranc.py') do (SET FLASH_DRIVE=%%g)
::ECHO %VAR%

SET PATH3=%FLASH_DRIVE%diasnow\
ECHO %PATH3%
::ECHO %PATH%

:: CONTROLS 
@echo off 
echo %DATE%

@echo off 
echo %TIME%

::Date in Format Year-Month-Day
::Example
@echo off 
echo/Today is: %year%-%month%-%day% 
goto :EOF 
setlocal ENABLEEXTENSIONS 
set t=2&if "%date%z" LSS "A" set t=1 

for /f "skip=1 tokens=2-4 delims=(-)" %%a in ('echo/^|date') do ( 
   for /f "tokens=%t%-4 delims=.-/ " %%d in ('date/t') do ( 
      set %%a=%%d&set %%b=%%e&set %%c=%%f)) 
endlocal&set %1=%yy%&set %2=%mm%&set %3=%dd%&goto :EOF
IF %ERRORLEVEL% NEQ 0 ( 
   DO_Something 
   ie EXIT /B 5
)

if not exist c:\lists.txt exit 7 
if not defined userprofile exit 9 
exit 0




Call Find.cmd

if errorlevel gtr 0 exit 
echo “Successful completion”



:: Default error levels and meanings
:: 0	Program successfully completed.
:: 1	Incorrect function. Indicates that Action has attempted to execute non-recognized command in Windows command prompt cmd.exe.
:: 2	The system cannot find the file specified. Indicates that the file cannot be found in specified location.
:: 3	The system cannot find the path specified. Indicates that the specified path cannot be found.
:: 5	Access is denied. Indicates that user has no access right to specified resource.

::9009
::0x2331
::Program is not recognized as an internal or external command, operable program or batch file. Indicates that command, application name or path has been misspelled when configuring the Action.

::221225495
::0xC0000017
::-1073741801
::Not enough virtual memory is available.It indicates that Windows has run out of memory.

::3221225786
::0xC000013A
::-1073741510
::The application terminated as a result of a CTRL+C. Indicates that the application has been terminated either by the user's keyboard input CTRL+C or CTRL+Break or closing command prompt window.

::3221225794
::0xC0000142
::-1073741502

::The application failed to initialize properly. Indicates that the application has been launched on a Desktop to which the current user has no access rights. Another possible
::cause is that either gdi32.dll or user32.dll has failed to initialize.
:: While loop
@echo off
SET /A "index=1"
SET /A "count=5"
:while
if %index% leq %count% (
   echo The value of index is %index%
   SET /A "index=index + 1"
   goto :while
)

:: For loop 
FOR %%variable IN list DO do_something
@echo off 
FOR %%F IN (1 2 3 4 5) DO echo %%F

 syntax-FOR-Files
       FOR %%parameter IN (set) DO command 
   
 syntax-FOR-Files-Rooted at Path   
       FOR /R [[drive:]path] %%parameter IN (set) DO command 
   
 syntax-FOR-Folders
       FOR /D %%parameter IN (folder_set) DO command 
   
 syntax-FOR-List of numbers   
       FOR /L %%parameter IN (start,step,end) DO command 
   
 syntax-FOR-File contents   
       FOR /F ["options"] %%parameter IN (filenameset) DO command 
   
       FOR /F ["options"] %%parameter IN ("Text string to process") DO command
   
 syntax-FOR-Command Results 
       FOR /F ["options"] %%parameter IN ('command to process') DO command



Using variables within a FOR loop
Variables are expanded at the start of a FOR loop and don’t update until the entire DO section has completed. 
The following example counts the files in the current folder, but %count% always returns 1:

@echo off
SET count=1 
 FOR /f "tokens=*" %%G IN ('dir /b') DO (
 echo %count%:%%G
 set /a count+=1 )

To update variables within each iteration of the loop we must either use EnableDelayedExpansion or else use the CALL :subroutine mechanism as shown below:

@echo off
SET count=1
FOR /f "tokens=*" %%G IN ('dir /b') DO (call :subroutine "%%G")
GOTO :eof

:subroutine
 echo %count%:%1
 set /a count+=1
 GOTO :eof

Nested FOR commands
FOR commands can be nested FOR %%G... DO (for %%U... do ...) 
when nesting commands choose a different letter for each part. you can then refer to both parameters in the final DO command.

For an example of exiting the inner loop of two nested FOR loops, see the EXIT page.

If Command Extensions are disabled, the FOR command will only support the basic syntax with no enhanced variables:
FOR %%parameter IN (set) DO command [command-parameters]

:: Simple for

:: For - Loop through set of files in folder

:: For - Loop through several folders

:: For - Loop through a range of numbers

:: For - Loop through items in a text file

:: For - Loop through the output of a command

:: FORFILES - Batch process multiple files

:: Looping through ranges


:: Classic Loop


:: Loop through command line arguments


:: Break statement


:: Continue statement
Redirecting Output (Stdout and Stderr)

Dir C:\ > list.txt
Dir C:\ 2> list.txt
DIR C:\ > lists.txt 2>&1

Suppressing Program Output
Dir C:\ > NUL


Stdin
TYPE CON > lists.txt

:: Checking integers
@echo off 
SET /A a=5 
SET /A b=10 
SET /A c=%a% + %b% 
if %c%==15 echo "The value of variable c is 15" 
if %c%==10 echo "The value of variable c is 10"


:: Checking strings
@echo off 
SET str1=String1 
SET str2=String2 
if %str1%==String1 echo "The value of variable String1" 
if %str2%==String3 echo "The value of variable c is String3"


:: Checking command line arguments
@echo off 
echo %1 
echo %2 
echo %3 
if %1%==1 echo "The value is 1" 
if %2%==2 echo "The value is 2" 
if %3%==3 echo "The value is 3"


:: One lien if else
@echo off 
SET /A a=5 
SET /A b=10
SET /A c=%a% + %b% 
if %c%==15 (echo "The value of variable c is 15") else (echo "Unknown value") 
if %c%==10 (echo "The value of variable c is 10") else (echo "Unknown value")


:: One lien if else strings
@echo off 
SET str1=String1 
SET str2=String2 
if %str1%==String1 (echo "The value of variable String1") else (echo "Unknown value") 
if %str2%==String3 (echo "The value of variable c is String3") else (echo "Unknown value")


:: One line - parameter test
@echo off 
echo %1 
echo %2 
echo %3 
if %1%==1 (echo "The value is 1") else (echo "Unknown value") 
if %2%==2 (echo "The value is 2") else (echo "Unknown value") 
if %3%==3 (echo "The value is 3") else (echo "Unknown value")


:: If defined
@echo off 
SET str1=String1 
SET str2=String2 
if defined str1 echo "Variable str1 is defined"
if defined str3 (echo "Variable str3 is defined") else (echo "Variable str3 is not defined")

:: If exist
@echo off 
if exist C:\set2.txt echo "File exists" 
if exist C:\set3.txt (echo "File exists") else (echo "File does not exist")


:: If errorlevel - multiline block
@echo off

if ERRORLEVEL == 0 (
    echo GP Manager is up
    goto Continue7
)
echo GP Manager is down
:Continue7



:: if %ERRORLEVEL% - MULTILINE
@echo off 

if %ERRORLEVEL% == 0 (
msg * 1st line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue1
)
:Continue1
If exist "C:\Python31" (
msg * 2nd line WORKS FINE rem You can relpace msg * with any othe operation...
    goto Continue2
)
:Continue2
If exist "C:\Python31\Lib\site-packages\PyQt4" (  
msg * 3th line WORKS FINE rem You can relpace msg * with any othe operation...
    goto Continue3
)
:Continue3
msg * 4th line WORKS FINE rem You can relpace msg * with any othe operation...
    goto Continue4
)
:Continue4
msg * "Tutto a posto" rem You can relpace msg * with any othe operation...
pause


:: Nested if
@echo off
SET /A a=5
SET /A b=10
if %a%==5 if %b%==10 echo "The value of the variables are correct"


:: if errorlevel
if errorlevel n somecommand


:: if + go to
@echo off 
SET /A a=5 

if %a%==5 goto :labela 
if %a%==10 goto :labelb

:labela 
echo "The value of a is 5" 

exit /b 0

:labelb 
echo "The value of a is 10"
1
$ set /?
Help
Help
Syntax
Syntax of the set command is very simple. [variable] and [string] parts are optional and used according to situation

SET [variable=[string]]
1
SET [variable=[string]]
List All Environment Variables
Environment variables holds a lot of information about the operating system and user . All these information can be listed just issuing the set command without any parameter like below.

$ set
1
$ set
List All Environment Variables
List All Environment Variables
Get/Print Single Environment Variable
In previous example we have listed all environment variables without selecting particular one. We can print only single variable just proving the variable name to the set command. In this example we will print the values of APPDATA environment variable.

$ set APPDATA
1
$ set APPDATA
Get/Print Single Environment Variable
Get/Print Single Environment Variable
Change/Create Environment Variable
Now the last function of the set command. We can create  or change and environment variable and its value by giving both the variable name and the variable data. In this example we create a new variable named Test with value 1

$ set Test=1
1
$ set Test=1
Get Home Path
Home is the current users location where his personal files and folders stored. This path can be printed like below.

LEARN MORE  Javascript Array Variable Types
$ set HOMEPATH
1
$ set HOMEPATH
Get Logon Server
Logon server is used to authenticate the user to login a system. In active directory system user credentials are authenticated in these authority servers.

$ set LOGONSERVER
1
$ set LOGONSERVER
Get Path Variable
Path variable is used to find executable files. Path variable stored more than one path and if a command is issued these path are checked for this command executables to run.

$ set PATH
1
$ set PATH
Get Program Files Path
Windows operating system stores built-in and 3 party applications files and folder in Program Files directory. This directory path can be printed like below.

$ set ProgramFiles
1
$ set ProgramFiles
Get System Root
Windows operating system files, folders and libraries are stored in System Root and this root directory generally named windows . By default this path is C:\Windows . The system root can be printed like below.


 
$ set SystemRoot
1
$ set SystemRoot
Get Username
The currently logged users user name can be printed like below.

$ set USERNAME
1
$ set USERNAME
:: Command Line Arguments

@echo off 
echo %1 
echo %2 
echo %3


:: Set Command
set /A variable-name=value

:: where,
::variable-name is the name of the variable you want to set.
::value is the value which needs to be set against the variable.
::/A – This switch is used if the value needs to be numeric in nature.

:: Ex 1
@echo off 
set message=Hello World 
echo %message%


:: Working with Numbers
@echo off 
SET /A a=5 
SET /A b=10 
SET /A c=%a% + %b% 
echo %c%


@echo off 
SET /A a=5 
SET /A b=10 
SET /A c=%a% + %b% 
echo %c% 
SET /A c=%a% - %b% 
echo %c% 
SET /A c=%b% / %a% 
echo %c% 
SET /A c=%b% * %a% 
echo %c%


:: Local vs Global vars
@echo off 
set globalvar=5
SETLOCAL
set var=13145
set /A var=%var% + 5
echo %var%
echo %globalvar%
ENDLOCAL

:: Environment Variables

@echo off 
echo %JAVA_HOME%
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: SOURCE BAT FILE

SET ENV=CURVES
SET DIR_IN=H:\COMPLETEDTHALIS\InputXml
SET BK_DIR=H:\COMPLETEDTHALIS\OldXml\
SET SCRIPT_DIR=C:\stratik\COMPLETEDTHALIS\
SET OT_TEMP=H:\COMPLETEDTHALIS\InputXml\NEW3.xmlout5.xml
SET OT_DIR=H:\COMPLETEDTHALIS\InputXml\OutputXml\


::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: CALLER BAT FILE

echo Setting Environment for execution
CALL CurveEnv.bat
pause

ECHO %ENV%


:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: SOURCING SUBROUTINES

Lets have the following file called library.cmd :

@echo off

echo -/-/- Batch Functions Library -/-/-

:function1
    echo argument1 - %1
    goto :eof
To execute only the :function1 without the code of the rest of the file you should put a label :function1 in the caller bat and use it like this:

@echo off

call :function1 ###
exit /b %errorlevel%

:function1
    library.bat %*
the output will be (the code outside the function in library.cmd is not executed):

argument1 - ###

For more info check this.