Indice

Dos Batch : Appunti

Variabili d'ambiente Interessanti

Variabile Descrizione Esempio
%date% Restituisce la data di sistema 07/05/2013
%time% Restituisce l'ora di sistema 14.42.35,14

Manipolazione delle variabili d'ambiente

Manipolazione della variabile %date% per trasformarla dal formato dd/mm/yyyy al formato yyyymmdd

SET mydate=%date:~6,4%%date:~3,2%%date:~0,2%

Esecuzione Condizionale (IF)

Sintassi File

IF [NOT] EXIST filename command

IF [NOT] EXIST filename (command) ELSE (command)

Sintassi Stringhe

IF [/I] [NOT] item1==item2 command

IF [/I] item1 compare-op item2 command

IF [/I] item1 compare-op item2 (command) ELSE (command)

Sintassi Controllo Errori

IF [NOT] DEFINED variable command

IF [NOT] ERRORLEVEL number command

IF CMDEXTVERSION number command

Key
item
Può essere una stringa di testo o di una variabile di ambiente
una variabile può essere modificata utilizzando sia
la sintassi stringa che la sintassi di ricerca
command
Il comando da eseguire
NOT
eseguire il comando se la condizione è false.
==
eseguire il comando se le due stringhe sono uguali.
/I
Esegue un confronto fra stringhe in modalità Case Insensitive.
compare-op
Può essere una delle:
  • EQU : Uguale
  • NEQ : Diverso
  • LSS : Minore di (<)
  • LEQ : Minore o Uguale ( < = )
  • GTR : Maggiore di (>)
  • GEQ : Maggiore o Uguale ( >= )

Questa sintassi a 3 cifre è necessaria perché i simboli > e < sono riconosciuti come operatori di reindirizzamento

IF ERRORLEVEL n statements devono essere letto come IF Errorlevel >= number

Esemio: IF ERRORLEVEL 0 ritorna TRUE quando errorlevel è 64

Spesso anzichè interrogare la variabile ERRORLEVEL è preferibile utilizzare la sua versione stringa %ERRORLEVEL%:

IF %ERRORLEVEL% GTR 0 Echo An error was found
IF %ERRORLEVEL% LSS 0 Echo An error was found
 
IF %ERRORLEVEL% EQU 0 Echo No error found
IF %ERRORLEVEL% EQU 0 (Echo No error found) ELSE (Echo An error was found)
IF %ERRORLEVEL% EQU 0 Echo No error found || Echo An error was found

L'ultimo caso può essere usato solo su piattaforme NT Style

Alcuni errori possono avere numeri negativi.

Quando si lavora con errorlevels in un file batch, è una buona idea utilizzare anche SETLOCAL in modo che la variabile %ERRORLEVEL% viene resettata ogni volta che il file batch viene eseguito.

IF EXIST filename restituisce true se il file esiste (non è case sensitive).

Esempi
IF EXIST C:\install.log (echo complete) ELSE (echo failed) 
IF DEFINED _department ECHO Got the department variable
IF DEFINED _commission SET /A _salary=%_salary% + %_commission% 
IF CMDEXTVERSION 1 GOTO start_process
IF %ERRORLEVEL% EQU 2 goto sub_problem2
%1 esiste?

Per verificare l'esistenza di un parametro della riga di comando utilizzare le parentesi vuote come riportato di seguito

IF [%1]==[] ECHO Value Missing

oppure

IF [%1] EQU [] ECHO Value Missing

In the case of a variable that may be NULL - a null variable will remove the variable definition altogether, so testing for NULLs becomes easy: Assegnando NULL ad una variabile, la sua definizione viene eliminata. In questo modo testare se una variabile è NULL diventa facile:

IF NOT DEFINED _example ECHO Value Missing

IF DEFINED restituirà True se la variabile contiene qualsiasi valore (anche se il valore è solo uno spazio)

Verificare l'esistenza di file e cartelle

IF EXIST name - Rileva l'esistenza di un file o di una cartella.

Parentesi

Le parentesi possono essere usate per dividere i comandi su più righe. Ciò consente la scrittura di istruzioni if … else … più complesse:

IF EXIST filename.txt (
    Echo deleting filename.txt
    Del filename.txt
 ) ELSE ( 
    Echo The file was not found.
 )

Quando si utilizzano le parentesi, la shell CMD espande [legge] tutte le variabili all'inizio del blocco di codice e utilizza tali valori anche se il contenuto delle variabili è appena stato cambiato.
Attivare DelayedExpansion costringerà la shell a leggere le variabili all'inizio di ogni riga.

Delimitatori

If the string being compared by an IF command includes delimiters such as [Space] or [Comma], then either the delimiters must be escaped with a caret ^ or the whole string must be “quoted”. This is so that the IF statement will treat the string as a single item and not as several separate strings.

Se la stringa da confrontare comprende delimitatori come [Spazio] o [virgola], per entrambi i delimitatori devono essere usate le sequenze di escape (carattere ^) o l'intera stringa deve essere “citata”. In questo modo l'istruzione IF tratterà la stringa come un singolo elemento e non come più stringhe separate.

Verificare valori numerici

IF analizza solo i numeri quando si utilizza uno dei seguenti operatori di confronto: EQU, NEQ, LSS, LEQ, GTR, GEQ. L'operatore di confronto == si traduce sempre in un confronto di stringhe.

This is an important difference because if you compare numbers as strings it can lead to unexpected results: “2” will be greater than “19” and “026” will be greater than “26”.

Questa è una differenza importante, perché se si confrontano i numeri come stringhe si possono ottenere risultati imprevisti:
“2” sarà maggiore di “19” e “026” sarà maggiore di “26”.

Corretto confronto numerico:

IF 2 GEQ 15 echo "bigger"

Utilizzando parentesi o citazioni forzerà il confronto fra stringhe:

IF (2) GEQ (15) echo "bigger"
IF "2" GEQ "15" echo "bigger"

This behaviour is exactly opposite to the SET /a command where quotes are required. Questo comportamento è esattamente opposto a quello di SET / comando in cui sono richieste le virgolette.

Caratteri Jolly (Wildcards)

I caratteri jolly non sono supportati da IF, quindi %COMPUTERNAME% == SS6* non corrisponderà a SS64

Una soluzione è quella di recuperare la sotto-stringa e confrontare solo quei caratteri:

SET _prefix=%COMPUTERNAME:~0,3%
IF %_prefix%==SS6 GOTO they_matched
Concatenamento Comandi (Pipes)

Quando si concatenano comandi, l'espressione viene valutata da sinistra a destra, in questo modo:
IF… | … è equivalente a (IF … ) | …
è anche possibile utilizzare la sintassi esplicita IF (… | …)

ERRORLEVEL

Per generare deliberatamente un errore e la conseguente valorizzazione di ERRORLEVEL in uno script batch usare il comando EXIT /B.

E' possibile (anche se non è una buona idea) creare una variabile stringa chiamata %ERRORLEVEL% (variabile utente) Se presente una tale variabile impedirà al vero ERRORLEVEL (una variabile di sistema) di essere utilizzato da comandi come ECHO e IF.

Per verificare l'esistenza di una variabile utente con tale nome, usare SET ERRORLEVEL, o IF DEFINED ERRORLEVEL

Se le Command Extensions sono disattivate ​​IF supporterà solo i confronti diretti:
IF == , IF EXIST, IF ERRORLEVEL ed anche la variabile di sistema CMDEXTVERSION verrà disabilitata.

IF è un comando interno.

Acquisizione Input Utente

In alcuni batch è richiesto che l'utente inserisca dati, per evitare di dover ricorrere a programmi esterni esiste la sintassi seguente:

set /p nome_var= prompt di richiesta 

ecco un esempio di utilizzo:

:START
cls
@echo off
echo.
echo Remote Desktop Client - shutdown or restart
echo.
echo When you use Remote Desktop you do not have
echo the usual restart/shutdown choices.
echo This will RESTART or SHUTDOWN the remote client
echo according to your choice.
echo.
echo 1. Restart
echo 2. Shutdown
echo 3. Abort
echo.
set /p userinp= Choose a number(1-3):
set userinp=%userinp:~0,1%
if "%userinp%"=="1" goto restart
if "%userinp%"=="2" goto shutdown
if "%userinp%"=="3" goto end
echo invalid choice
goto start
 
:restart
Echo Program: Please wait....
shutdown -r -t 01
goto end
 
:shutdown
shutdown -s -t 01
goto end
 
:end 

XCOPY Exit Code

Exit code Description
0 Files were copied without error.
1 No files were found to copy.
2 The user pressed CTRL+C to terminate xcopy.
4 Initialization error occurred. There is not
enough memory or disk space, or you entered
an invalid drive name or invalid syntax on
the command line.
5 Disk write error occurred.

Fonti