oncode
12/17/2014 - 10:41 AM

Cheatsheet for windows batch.

Cheatsheet for windows batch.

Cheatsheet for windows batch

Deactivate echo:

@echo off

Prevent closing:

pause > nul
:: or
cmd \k COMMAND

Comments

:: like this
REM or like this

Variables

:: set variable root
set root=%cd%\..\

:: access root variable
cd %root%

Input

Get input from user:

set /p age="How old are you?"
echo You are %age% years old

Goto

goto YES

:YES
echo YES
goto END

:NO
echo NO
goto END

:END
echo END

User decision:

set /p res=(Y)es or (N)o?
if /i "%res%"=="Y" goto :YES
if /i "%res%"=="N" goto :NO
goto ENDE

File/folder management

Get current folder:

echo %cd%

Remove file (quiet & recursive)

del "file1.txt" "file2.txt" /q /s

Remove folder (quiet & recursive):

rd "scss" /q /s

Delete folder contents:

del uploads /s /f /q
for /d %%a in ("folder\*.*") do rd /q /s "%%a"

Delete only subfolders:

for /r /d %%a in ("folder\*") do rd %%a /q /s

Delete all matching folders in all (sub)folder(s) (e.g. hidden .svn folders):

for /f "tokens=*" %%g in ('dir /b /ad /s *.svn*') do rmdir /q /s %%g

Delete all matching files (e.g. cmd files):

for /f %%a IN ('dir /b /s *.cmd') do call del %%a

Call bash script in subfolders:

for /f "tokens=*" %%g in ('dir /b /ad /s *') do (
  cd %%g
  call "SCRIPT.cmd"
)

Remove all files in folder (with exceptions):

cd "folder/"
attrib +r +s "file_to_keep1.txt"
attrib +r +s "file_to_keep2.txt"
attrib /s /d +r +s "folder-with-files-to-keep/*.*"
del /q /s "*.*"
attrib -r -s "file_to_keep1.txt"
attrib -r -s "file_to_keep2.txt"
attrib /s /d -r -s "folder-with-files-to-keep/*.*"