Windows Batch Scripting

From Torben's Wiki
(Redirected from Batch)

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

current dir and filename

# current working dir
echo %CD%
# path of current file
echo %0
  1. filename without the extension.
echo %~n0
  1. filename and extension.
echo %~nx0
  1. or
echo %~n0%~x0

Title to Dirname

@echo off
for %%f in (%cd%) do set dirname=%%~nxf
title %dirname%

Empty c:\tmp

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

find files / search (and delete) old files

via forfiles

forfiles /P "C:\tmp\test-del" /S /D -30 /C "cmd /c echo @path"
forfiles /P "C:\tmp\test-del" /S /D -30 /C "cmd /c del @path"
forfiles /P "C:\tmp\test-del" -S -D 90 -m *.log -c "cmd /c del @path"

via robocopy

robocopy "C:\tmp\test-del" "*.log" "C:\cleanup-logs" /mov /minage:90 /NP
del C:\cleanup-logs /q

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 (%CD%) do set CurrDirName=%%~nx*
echo %CurrDirName%

List of files to Textfile

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

Pipe output to textfile

From [1] You can print the errors and standard output to a single file by using the "&1" command to redirect the output for STDERR to STDOUT and then sending the output from STDOUT to a file:

some_command > output.log 2>&1
some_command 1> output.log 2> error.log

exit if command fails with error

some_command1
IF %ERRORLEVEL% NEQ 0 exit /b %ERRORLEVEL%
some_command2
IF %ERRORLEVEL% NEQ 0 exit /b %ERRORLEVEL%

Loops

if

check if mounting (net use) was successful

net use q: \\server\share
q:
cd \
IF NOT EXIST dir1\dir2 (
  echo mouting of share failed
  pause
  c:
  net use q: /delete
  EXIT /B 1
)

for

loop over values

for %%L in (cn, de, en, es, fr, ko, sk, vn) do (
echo %%L
)

loop over all dirs

FOR /D %%D in ("*") DO (
echo %%D
)

double loop over all dirs

FOR /D %%P in ("*") DO (
echo parent = %%P
  FOR /D %%C in ("%%P\*") DO (
  echo child = %%C
  )
)

loop over files

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

for and grep.exe

using UnixUtils grep.exe one can easily extract exceptions from logs:

for %%F in (*.log) do (
  grep -B3 -A3 "exception" %%F > %%~nF-error.txt 
)

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

Set Variable to Program Output

for /f "delims=" %%a in (' powershell -c "$lastmonth = (Get-Date).addMonths(-3); $lastmonth.tostring(\"yyyy-MM\")" ') do set "MONTH=%%a"
echo %MONTH%

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

TOP CPU RAM Disk I/O

  1. CPU + RAM
top
  1. I/O
sudo iotop -o -d 2 -k

Run as other user

runas /user:MYDOMAIN\myuser /savecred  "cmd /K cd c:\mydir && my_programm.exe"

/K to keep window open when finished
/C to close window when finished