Windows Batch Scripting

From Torben's Wiki

see "Top 10 DOS Batch tips" and BATch-Dateien - kleine Tipps for more stuff

Empty c:\tmp

@echo off
rmdir /q /s c:\tmp
mkdir c:\tmp

ReadOnly Flag / WriteProtection

Remove

attrib -h -r -s /s /d *.*

Set

attrib +r c:\Users\torben\Desktop\SyncedFolder\*.* /s
 R   Read-only file attribute.
 S   System file attribute.
 H   Hidden file attribute.
 /S  Processes matching files in the current folder and all subfolders.
 /D  Processes folders as well.

Set Current Working Dir to Script Location

This is important if the script is started using a taskmanager etc.

e:
cd %~dp0

Set Window Title

TITLE My Window Title

or when opening via START from another Batch file

START "My Window Title" 2.cmd

Get FolderName

This when excecuted in c:\sub\folder it returns "folder"

for %%* in (.) do set CurrDirName=%%~nx*
echo %CurrDirName%

List of files to Textfile

dir *.* /b > ..\liste.txt

Loops

for %%F in (*.pdf) do (
echo %%F
copy %%F %%~nF.old
)

Variables

:: no spaces around '='!!!
set xyz=myfile.bat
set /p xyz=Variable Eingeben:
set /p xyz= < TMP.dat 
echo %xyz%

Substrings

Substring via ":~"

set year=%date:~-4,4

Path, filename and extension of file stored in variable %%F

set path=%%~pF
set name=%%~nF
set ext=%%~cF

Date & Time

DateString

set DATESTR=%date:~-2,4%%date:~-7,2%%date:~-10,2%_%time:~0,2%%time:~3,2%
:: replace ' ' in small hours with 0
set DATESTR=%DATESTR: =0%
zip.exe -9 %DATESTR%.zip *.bat

for better example of zipping see zip folder in Backup section

DayOfWeek

from here

SETLOCAL enabledelayedexpansion
SET /a count=0
FOR /F "skip=1" %%D IN ('wmic path win32_localtime get dayofweek') DO (
    if "!count!" GTR "0" GOTO next
    set dow=%%D
    SET /a count+=1
)
:next
echo %dow%

Yesterday

from here

set befehl="PowerShell $date = Get-Date; $date=$date.AddDays(-1); $date.ToString('yyyy-MM-dd')"
for /f %%i in ('%befehl%') do set yesterday=%%i


Copy all files from subfolders to one folder

from here

set source=c:\source
set target=c:\target
cd %source%
for /r %%a in (*.*) do (
 COPY "%%a" "%target%"
)

FTP

FTP-Upload

file "ftp.bat"

@echo off
ftp "-s:FtpScript"
pause
cls

file "FtpScript"

open www.xyz.de
[User]
[Password]
BINARY
put [File]
quit

UnixUtils

Using UnixUtils for Windows wget, grep, etc are usable to scripts in Windows. In the UnixUtils.zip the .exe files are located in foltder usr/local/wbin/ . Examples:

head.exe -c 1000 mylog.log > outHead1000Bytes.log
head.exe -n 1000 mylog.log > outHead1000Lines.log
tail.exe -c 1000 mylog.log > outTail1000Bytes.log
tail.exe -n 1000 mylog.log > outTail1000Lines.log
grep.exe -i -B3 -A1 "ERROR" mylog.log > outGrepErrors.log