Windows batchfile tips and tricks

From WickyWiki


Note: the %% and %~ notation is used within a batchfile and will not work on the DOS prompt.


Batchfile information

Within a batchfile the '%0' parameter will contain the full path and name of the batchfile.

@echo off
set fullpath=%~dp0
for %%i in ( %0 ) do set basefile=%%~ni
for %%i in ( %0 ) do set basepath=%%~pi
for %%i in ( %0 ) do set basedrive=%%~di
for %%i in ( %0 ) do set filesize=%%~zi

echo batchfile=%0
echo fullpath=%fullpath%
echo basedrive=%basedrive%
echo basepath=%basepath%
echo basefile=%basefile%
echo filesize=%filesize% bytes
D:\path\to> example.bat
batchfile=D:\path\to\example.bat
fullpath=D:\path\to\
basedrive=D:
basepath=\path\to\
basefile=example
filesize=101 bytes
D:\path\to>

In general:

Use Meaning
%~1 expands %1 removing any surrounding quotes (")
%~f1 expands %1 to a fully qualified path name
%~d1 expands %1 to a drive letter only
%~p1 expands %1 to a path only
%~n1 expands %1 to a file name only
%~x1 expands %1 to a file extension only
%~s1 expanded path contains short names only
%~a1 expands %1 to file attributes
%~t1 expands %1 to date/time of file
%~z1 expands %1 to size of file

Timestamp

@echo off
call :get_timestamp
echo timestamp=%timestamp%
goto :EOF

:get_timestamp
rem timestamp YYYYMMDD-HHMMSS (werkt alleen in batchfile)
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
rem set "timestamp=%YYYY%.%MM%.%DD%-%HH%.%Min%.%Sec%"
set "timestamp=%YYYY%.%MM%.%DD%-%HH%.%Min%"
goto :EOF
timestamp=2020.04.25-11.53

Timestamp v2

Format date/time:

dos> echo %date% %time%
10/08/2025 10:38:23,14

Create timestamp:

dos> set dt=%date%
dos> set tt=%time%
dos> echo %dt:~6,4%%dt:~3,2%%dt:~0,2%_%tt:~0,2%%tt:~3,2%%tt:~6,2%
20250810_102614

Find file

for /F "delims=" %%a in ('dir /B /A:-D "%basedrive%%basepath%*fun*.*" 2^>NUL') do echo FOUND %%~Fa

Check if application is running

set filter1=%%cmd.exe%%
set filter2=batchfile.bat
if "%filter2%"=="" set filter=%1
wmic PROCESS where "name like '%filter1%'" get Name,Processid,Caption,Commandline 2>NUL | find /I /N "%filter2%" >NUL
rem tasklist /FI "IMAGENAME eq %1" 2>NUL | find /I /N "%1">NUL
if "%ERRORLEVEL%"=="0" goto :check_app_running_isrunning
echo Program %1 %2 is NOT running
goto :einde
:check_app_running_isrunning
echo Program %1 %2 is running
:einde

Check if service is running

set unquoted=W32Time
sc query "%unquoted%" | findstr "STATE..............:.4..RUNNING" >NUL
if "%ERRORLEVEL%"=="0" goto :check_svc_running_isRunning
echo Service %unquoted% is NOT running
goto :einde
:check_svc_running_isRunning
echo Service %unquoted% is running
:einde

See also