Discovering DOS : DOS commands and batch file ideas.

A collection of DOS commands and batch file ideas to automate tasks on Windows.

Table of Contents

Deleting large folder structures & files

Consider a complex folder structure with nested sub-folders and many files holding many GBs of data, sometimes trying to delete this from the Windows Explorer UI can cause it to crash.

1\---PDF
2    +---0004318H
3    |       100608788.pdf
4    |       100964520.pdf
5    +---0004411E
6    |       100131585.pdf
7    +---0005042K
8    |       52437480.pdf
9    |       54289867.pdf

The following commands will first delete all the PDF files from all the folders, and then remove the all the folders.

1D:
2CD \FlatIronExtracts
3del /Q /S .\PDF\*
4rmdir /S /Q .\PDF

Using DOS batch file(s) to build an SQL change script

Using my SQL Schema Extraction Tool I downloaded all the stored procedures for a database as hard coded linked server names needed to be removed from the files. After each file was modified, I needed a batch file that would combine all the scripts into an individual sql script that could be applied to the server.

This is what I came up with:

 1@echo off
 2set basepath=C:\Code\db_schema_eRecordSilo
 3
 4set output=fix-uat-remove-linked-servers.sql
 5del %output%
 6
 7call :append %%basepath%%\sp_dbo.EncounterPregnancyUpdate.sql
 8call :append %%basepath%%\sp_dbo.PatientStatusUpdateAdmissionDischarge.sql
 9call :append %%basepath%%\sp_dbo.PatientStatusUpdateBedStatus.sql
10
11exit
12
13:append
14echo Appending: %~1
15
16echo -- %~1 >> %output%
17type %~1 >> %output%
18
19echo.>> %output%
20echo GO>> %output%
21echo.>> %output%
22echo.>> %output%
23
24endlocal
25exit /b

Using ERRORLEVEL in a batch file to report errors stopping & starting a service

The following batch file is run via a scheduled task every hour, and I needed to add alerts if the process failed in either stopping or starting the service. It uses the ERRORLEVEL returned by the sc command.

 1echo "Attempting to restart DataWarehouseConverter"
 2
 3sc stop DataWarehouseConverter
 4sc start DataWarehouseConverter
 5
 6if %ERRORLEVEL% NEQ 0 (
 7    echo "ERRORS detected"
 8
 9    :: email the whole team an error was detected
10    incident-emailer.exe
11        -subject="VAS104A - FAILED SERVICE RESTART"
12        -body="\n
13        The DataWarehouseConverter FAILED to restart\n\n.
14        Manual intervention is required!\n\n"
15)