-
File operations are at the heart of scripting and automation. Whether you’re creating temp files, deleting old logs, or renaming backups,
Windows Batch scripting provides a set of straightforward yet powerful commands to manage files directly from the terminal or script.
-
The simplest way to create a file:
ECHO Hello world > file.txt
>creates or overwrites the file>>appends to the file
ECHO. > empty.txt
or:
COPY NUL empty.txt >NUL
COPY NULis the traditional DOS way to create an empty file.
ECHO This is a > symbol > file.txt :: WRONG
This breaks because
>is a redirection operator. Escape it using^:ECHO This is a ^> symbol > file.txt
-
DEL file.txt- Deletes the specified file
- Wildcards are allowed
- No confirmation prompt
DEL /Q /F myfile.txtSwitch Meaning /QQuiet mode (no prompt) /FForce delete (even read-only) DEL /Q *.log
Batch doesn’t prompt by default, so always double-check wildcards.
You can simulate confirmation:
IF EXIST "dangerous.txt" ( ECHO Are you sure? (Y/N) SET /P CHOICE= IF /I "%CHOICE%"=="Y" DEL dangerous.txt )
To delete all
.tmpfiles in a folder and subfolders:DEL /S /Q *.tmpSwitch Description /SInclude subdirectories /QQuiet, no confirmation
-
REN oldname.txt newname.txt-
Does not allow changing directories — just the name
FOR %%F IN (*.txt) DO REN "%%F" "%%~nF.bak"
%%~nFextracts just the filename (no extension)
MOVEcan rename and change directory.MOVE file.txt C:\Archive\You can rename in-place too:
MOVE old.txt new.txt
-
-
DEL /Q /F /S *.logDelete all logs recursively and quietly.
-
FOR %%F IN (*.txt) DO ( MOVE "%%F" "C:\backup\%%~nF_%DATE:/=-%.txt" )
Appends today’s date to each file and moves it to
C:\backup. -
ECHO server=localhost > config.ini ECHO port=8080 >> config.ini
Creates a basic config file line by line.
| Practice | Why it Matters |
|---|---|
| Use quotes for filenames | Prevent errors with spaces or special characters |
| Double-check wildcards | Avoid accidental data loss |
Use /Q for automation |
Prevents hanging scripts |
Use IF EXIST before DEL |
Adds a safety layer |
Prefer MOVE for renaming |
REN doesn’t support changing directories |
| Operation | Command |
|---|---|
| Create file | ECHO Text > file.txt |
| Create empty file | COPY NUL file.txt |
| Delete file | DEL /Q file.txt |
Delete all .log |
DEL /Q *.log |
| Delete recursively | DEL /S /Q *.tmp |
| Rename file | REN old.txt new.txt |
| Move and rename | MOVE file.txt archive\file_2025.txt |
| Rename in loop | FOR %%F IN (*.txt) DO REN "%%F" "%%~nF.bak" |