Rob van der Woude's Scripting Pages

Short Command Line Tips

This page contains a collection of some really short samples of frequently asked functions in batch files.

 

Function Batch Code Remarks
Batch file's directory ECHO "%~dp0" Shows the batch file's directory with trailing backslash (credits: Sean Brannery)
Batch file's directory (SFN) ECHO "%~dps0" Shows the batch file's directory as Short File Name (8.3 notation)
Battery icon in notification area POWERCFG /GlobalPowerFlag ON /Option:BatteryIcon Will even work on desktops and servers
Beep ECHO ˆG ˆG is Ctrl+G (ASCII character 7)
CD Writer or Not? WMIC CDROM Where "Drive='d:'" Get Capabilities | FINDSTR /R /C:"[^0-9]4[^0-9]" Displays a string like {3, 4, 7} and returns errorlevel 0 if drive d: is a CD/DVD writer, or doesn't display anything and returns errorlevel 1 if not (capability value 4 means the drive "Supports writing")
Count files DIR /A | FIND "File(s)" Counts the number of files in the current directory.
Will show its result like this: 47 File(s).
Language dependent, FIND filter shown is for English Windows versions only.
Count files DIR /A-D /B | FIND /C /V "" Counts the number of files in the current directory.
Will show its result like this: 47.
Language independent.
Count files SET Count=0
FOR %%A IN (*.*) DO SET /A Count += 1
ECHO.%Count%
Counts the number of files in the current directory.
Will show its result like this: 47.
Language independent.
"Limited" to 32767 (7FFF) files maximum.
Count files (1) XCOPY * "%TEMP%" /H /L /Q /S /Y Counts the number of files in the current directory.
Will show its result like this: 47 File(s).
Language independent.
Credits: Andrew J. Macbeth
Count files in subfolders FOR /D %%A IN (*) DO (
    ECHO.%%A
    DIR "%%~A" /A-D /B /S | FIND /C /V ""
)
Counts the number of files in each subdirectory.
Will show its result like this:
My Pictures
47

Language independent.
Count files in subfolders (1) FOR /D %%F IN (*) DO (
    ECHO "%%F"
    XCOPY "%%F\*" "%TEMP%" /H /L /Q /S /Y
)
Counts the number of files in each subdirectory.
Will show its result like this:
"My Pictures"
47 File(s)

Language independent.
Credits: Andrew J. Macbeth
Count files in subfolders (1) FOR /D %%F IN (*) DO (
    FOR /F %%C IN ('XCOPY "%%F\*" "%TEMP%" /H /L /Q /S /Y') DO (
        ECHO.%%C File(s)    %%F
    )
)
Counts the number of files in each subdirectory.
Will show its result like this:
47 File(s)    My Pictures.
Language independent.
Credits: Andrew J. Macbeth
Count files in subfolders FOR /D %%A IN (*) DO (
    FOR /F %%B IN ('DIR "%%~A" /A-D /B /S ˆ| FIND /C /V ""') DO (
        ECHO.%%B File(s)    %%A
    
)
Counts the number of files in each subdirectory.
Will show its result like this:
47 File(s)    My Pictures
Language independent.
Count total files in subfolders DIR /A-D /B /S | FIND /C /V "" Counts the total number of files in the current directory plus subdirectories.
Will show its result like this:
47
Language independent.
Count files modified since ... (1) XCOPY * "%TEMP%" /H /L /S /Q /Y /D:12-29-2005 Counts all files modified since December 29, 2005, in the current directory and subdirectories.
Will show its result like this: 13 File(s)
Regardless of language or international settings, the date format for XCOPY's /D switch is always M-D-Y.
Count files modified before ... (1) FOR /F %%A IN ('XCOPY * "%TEMP%" /H /L /S /Q /Y /D:12-29-2005') DO (
    FOR /F %%B IN ('XCOPY * "%TEMP%" /H /L /S /Q /Y') DO (
        SET /A OldFiles = %%B - %%A
    )
)
ECHO.%OldFiles% File(s)
Counts all files modified before December 29, 2005, in the current directory and subdirectories.
Will show its result like this: 34 File(s)
Regardless of language or international settings, the date format for XCOPY's /D switch is always M-D-Y.
Counter SET /A Counter += 1 Increments the variable %Counter% by 1; if %Counter% is not defined, its starting value is 0
Current Directory CD Displays the current directory (without trailing backslash, unless it is the root directory)
Current Directory ECHO.%CD% Displays the current directory (without trailing backslash, unless it is the root directory)
Current Directory ECHO.%__CD__% Displays the current directory with trailing backslash (note the double underscores before and after CD)
Current Directory ECHO.%__CD__:~0,-1% Displays the current directory without trailing backslash (note the double underscores before and after CD)
Current Directory (SFN) FOR %%A IN ("%CD%") DO ECHO.%%~sfA Displays the current directory as Short File Name (8.3 notation, without trailing backslash, unless it is the root directory)
Current Drive FOR %%A IN ("%CD%") DO ECHO.%%~dA Displays the current drive letter (or \\ for UNC paths)
(Thanks Rob Huston for pointing out the required doublequotes)
Date DATE /T  
Date ECHO.%Date%  
Date FOR %%A IN (%Date:/=%) DO SET Today=%%A Removes forward slashes and day of week, so the result can be used in a file name
Date (YYYYMMDD format) FOR %%A IN (%Date%) DO (
    FOR /F "tokens=1-3 delims=/-" %%B in ("%%~A") DO (
        SET Today=%%D%%B%%C
    )
)
Stores current date in YYYYMMDD format variable %Today%. Code shown is for (US) systems with date in MM/DD/YYYY format. Use %%D%%C%%B for systems with date in DD-MM-YYYY format.
(Credits: Matthew C. Miller)
Date VER | DATE | FIND /V "(" Will also show the text "The current date is" and, depending on OS version and regional settings, the day of the week
Date and Time in file name REN *.LOG "* %Date:/= % %Time::=.%.*" Will append the current date and time to all log file names, replacing forward slashes by spaces and colons by dots
Date and Time in file name SET Today=%Date: =0%
SET Today=%Today:~-4%%Date:~-7,2%%Date:~-10,2%
SET Now=%Time: =0%
FOR /F "tokens=1,2 delims=:.," %%A IN ("%Now%") DO SET Now=%%A%%B
REN *.LOG "*_%Today%_%Now%.*"
Will append the current date and time to all log file names, with the date in YYYYMMDD format and the time in HHmm format. The code shown is for systems with the date in DD*MM*YYYY format, change the order of the Date substrings for other date settings.
(Credits: Ildar Shaimordanov)
Drive letters in use FSUTIL FSINFO DRIVES Lists all drive letters in a single line on screen; however, to parse that line with FOR /F you'll need MORE /E /T0 to remove vertical tabs or orphaned line feeds, as demonstrated in my own DrivUsed.bat
File size FOR %%A IN (filename.ext) DO SET FileSize=%%~zA Will store the size of filename.ext into variable %FileSize%
Hexadecimal to Decimal SET /A DecValue = 0x%HexString% Maximum value 65536 (216)
IP Address PING %ComputerName% Substitute %ComputerName% with a remote computer name to get that computer's IP address.
IP Address NSLOOKUP %ComputerName% DNS only.
Substitute %ComputerName% with a remote computer name to get that computer's IP address.
Instead of a computer name, you can also specify an IP address to get the computer name.
IP Address FOR /F "tokens=2 delims=[]" %%A IN ('PING %ComputerName% -n 1') DO (
    SET IP=%%A
)
Substitute %ComputerName% with a remote computer name to get that computer's IP address.
IP Address FOR /F "tokens=1,2" %%A IN ('NSLOOKUP %ComputerName%') DO (
    IF "%%~B"=="" (SET IP=%%A) ELSE (SET IP=%%B)
)
DNS only.
Substitute %ComputerName% with a remote computer name to get that computer's IP address.
Instead of a computer name, you can also specify an IP address to get the computer name.
Jump to batch file's directory PUSHD "%~dp0" Will map a network drive if the batch file was started from a UNC path, and then make the batch file's location the current (or working) directory.
Use POPD before closing the batch file, otherwise the mapping will persist.
(Credits: Reinhard Irnberger)
Linefeed ECHO. Actually a carriage return/linefeed combination; displays an empty line
Linefeeds –> CR/LF TYPE input_filename | MORE /E /P > output_filename Converts "isolated" linefeeds to carriage return/linefeed pairs
List directories in PATH FOR %%A IN (%PATH%) DO ECHO.%%A Will fail if folder names contain spaces or parenthesis (i.e. all 64-bit Windows and most standard 32-bit Windows as well)
List directories in PATH PATH | RXGREP "(?<=[;=])[^;=]*" No problems with any characters in folder names.
Requires RxGrep.exe.
If "(?<=[;=])[^;=]*" is too hard to remember, use "[^;]" instead, this will prefix the first entry with PATH= but otherwise have identical results.
List files modified since ... (1) XCOPY * "%TEMP%" /H /L /S /Y /D:12-29-2005 Will lists all files modified since December 29, 2005, in the current directory and subdirectories.
Regardless of language or international settings, the date format for XCOPY's /D switch is always M-D-Y.
List internal commands STRINGS %ComSpec% | RXGREP "[\n\r]CLS[\n\r][\w\W\n\r]*COMSPEC[\n\r]" | SORT | RXGREP "([A-Z]+[\n\r]+)+" | SORT Requires RxGrep.exe and Microsoft's Strings.exe.
Tested only in Windows 7, so far.
Math SET /A Integers only
Check if a value is numeric FOR /F "tokens=1 delims=0123456789" %%A IN ("%Value%") DO (
    ECHO.%Value% is NOT a valid decimal, octal or binary number
)
Positive numbers only, no hexadecimal.
If the value is numeric the FOR loop won't iterate, because %VALUE% will contain nothing but delimiters.
Use constructs like SET Invalid=1 inside the loop if you want to use the result outside the loop.
Check if a value is numeric FOR /F "tokens=1 delims=-0123456789abcdefABCDEF" %%A IN ("%Value%") DO (
    ECHO.%Value% is NOT a number
)
All numbers, positive or negative, including hexadecimal without "x" or "0x" prefix.
"False positive" on strings like "0FA7-A33E-7049-E444-1DEA".
Octal to Decimal SET /A DecValue = 0%OctalString% Maximum value 65536 (216)
Script's own startup drive SET MyStartupDrive=%~d0  
Script's own startup folder (without drive) SET MyStartupFolder=%~p0 Double quotes may be necessary for long folder names with spaces: "%~p0"
Script's own startup path SET MyStartupPath=%~dp0 Double quotes may be necessary for long folder names with spaces: "%~dp0"
Short File Name FOR %%A IN ("filename.ext") DO ECHO.%%~snxA Shows filename.ext's Short File Name (8.3 notation)
Short File Name FOR %%A IN ("filename.ext") DO ECHO.%%~sfA Shows filename.ext's fully qualified path as Short File Name (8.3 notation)
String Substitution SET NewString=%OldString:old=new% Substitutes "old" with "new" everywhere in the string %OldString%; case sensitive!
Time ECHO.%Time% Hours, minutes, seconds and hundredths of seconds
Time FOR /F "tokens=1-3 delims=:.," %%A IN ("%Time%") DO (
    SET Time=%%A:%%B:%%C
)
Hours, minutes and seconds
Time TIME /T Hours and minutes only
Time VER | TIME | FINDSTR /R /C:"[0-9]" Hours, minutes, seconds and hundredths of seconds, prefixed by "The current time is"
Open Windows Update in Internet Explorer WUPDMGR Obsolete
Open Windows Update START ms-settings:windowsupdate Windows 8..11
Wipe an empty partition or the empty space on a partition > wipe.txt ECHO AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
FOR /L %%A IN (1,1,1000) DO (TYPE wipe.txt >> wipe.txt)
DEL wipe.txt
This may take some time...
Open .ZIP file in Explorer RUNDLL32.EXE ZIPFLDR.DLL,RouteTheCall zipfile.ZIP Unfortunately, there seems to be no (native) command to copy files into the .ZIP file

 

Notes: (1) When using XCOPY * "%TEMP%".../S on root directory of the drive where the %TEMP% directory is located, you may get an error message stating Cannot perform a cyclic copy.
That's because the XCOPY command tries to copy the contents of the root directory and all its subfolders, including %TEMP%, to %TEMP%.
To prevent this, you may either use a directory on a different drive as an alternative to %TEMP% (the /L switch prevents anything from actually being copied anyway), or use XCOPY's /EXCLUDE switch and exclude the %TEMP% directory.

page last modified: 2023-10-30; loaded in 0.0024 seconds