Batch file to Stop/Start Service

I would like to restart a service by using a service account in batch. The batch file will need to read over 300 file services from a text file and stop the service. A second file will start the service in the same manner.

You can do this using a combination of for /f and “net start” and “net stop” commands.

for /f %%A in (text.file) do net start %%A
for /f %%A in (text.file) do net stop %%A

If you have quotes in filename or so use the backquote option for for command. type for /? for help on for.

Create Batch File to Start or End Window Services

We all want to tweak or windows systems to the extreme to get the quickest, most powerful system possible. Many people will disable multiple window services manually before game playing. What a pain!

Many times people forget what the services do or forget to restart the important ones. Services can be easily changed by creating batch files.

The important commands are the following:
NET START - starts the service
NET STOP - ends the service

For example:
NET STOP “Error Reporting Service”

Output: The Error Reporting Service service was stopped successfully.

Knowing the commands, one can now easily create batch files called something like beforegame.bat and aftergame.bat.

Before.bat would contain all the NET STOP commands to end the nonessential services.
After.bat would be exactly the same except all the NET STOP commands would be replaced with NET START commands to restart all the common services.

A sample of the before.bat file might look something like this:

NET STOP “Error Reporting Service”
NET STOP “FTP Publishing Service”
SET STOP “IIS Admin”
NET STOP “Messenger”

Likewise, the after.bat file might look something like this:

NET START “Error Reporting Service”
NET START “FTP Publishing Service”
SET START “IIS Admin”
NET START “Messenger”

Creating Batch File Processes in Photoshop

To begin this process you need to create an action. If you don’t know how to do this or never used Photoshop’s actions before, I’ll explain it. First you must create a new action from the actions menu, give it a name and hit the record button. Photoshop will now memorize everything you do in between pressing the record button on and off. Just like a tape player (am I old?). In my case, I would load my image, press record, then reduce the resolution and change CMYK to RGB. After I’m finished with all my actions I would hit the record button again to stop recording. Photoshop now knows that every time that action is played it will recreate everything you’ve done in the recording mode. Remember to give your action a name.

Now, on to automating the actions via the batch command. From the actions menu select the batch command. It will then show the batch dialogue box. You have little variety here to select from, which is good because it makes things pretty easy. In my case, I just wanted to modify each file then load a new one and continue in a loop. So select a destination folder where all your graphic files are, then select one of the actions to be performed on each file. Select the option (Save and Close). Photoshop will now be automated. You can watch as Photoshop mechanically and quickly goes through all your files while you can sit back and relax. Your boss might be impressed as he wonders how you completed the task so efficiently, while you didn’t even break a sweat.

DOS Batch FTP - Simple - FTP script and batch in a single file

Embed FTP script into a batch script. Add this line at the beginning of the FTP script:

@ftp -i -s:”%~f0″&GOTO:EOF

The “FTP -s:ftpscript.txt” option executes a FTP script wheres “%~f0″ resolved to the name of the running batch file. “GOTO:EOF” ends the batch script and makes sure the FTP script doesn`t run as part of the batch.
Good: You end up with only one file that contains the batch script and the FTP script combined.
Minor flaw: The batch command in the first line causes an “Invalid command.” error when executed in FTP context, however the FTP execution will continue.

@ftp -i -s:”%~f0″&GOTO:EOF
open example.com
username
password
!:— FTP commands below here —
lcd c:\MyLocalDirectory
cd  public_html/MyRemoteDirectory
binary
mput “*.*”
disconnect
bye

Wait, Sleep, Hold - :sleep

The :sleep function puts the batch execution on hold for a certain amount of second.

:sleep -– waits some seconds before returning

::     — %~1 – in, number of seconds to wait

FOR /l %%a in (%~1,-1,1) do (ping -n 2 -w 1 127.0.0.1>NUL)

goto :eof

Get THIS computers IP address - :getIP

The getIP function filters the IP address from the ipconfig command output and returns it to the caller.

Code

:getIP — return THIS computers IP address

::     — %~1 - out, IP

SETLOCAL

set ip=

for /f “tokens=2,* delims=:. ” %%a in (’”ipconfig|find “IP Address”"‘) do set ip=%%b

( ENDLOCAL & REM RETURN VALUES

IF “%~1″ NEQ “” (SET %~1=%ip%) ELSE (echo.%ip%)

)

goto :eof

Test Code

rem.show this computers IP address

call:getIP ip

echo This computers IP is: %ip%

Test Code Output

This computers IP is: 4.239.36.199

OSQL.EXE - Run SQL script from DOS Batch - SQL script and dos batch script in one file, the One-File Solution

Embedding SQL script within a batch script is just as easy. The following batch script executes itself in SQL context. The trick is the GOTO command in the first line of the script. When executing GOTO START in batch context than the command processor will jump to the label “:START” and execute the batch script. The batch script will then run the OSQL.EXE using the batch file itself as SQL file argument to be executed. When subsequently executing the GOTO START line in SQL context, the query language processor will jump to the label “START:” and execute the SQL queries. In fact the file can be opened and executed in Query Analyzer as is, since the batch script in the file looks like a comment to the query language processor.

GOTO START
– DOS jumps to the ‘:START’ label
– SQL jumps to the ‘START:’ label

/* Begin of SQL comment, this makes the BATCH script invisible for SQL
:: BATCH starts below here
:START
@echo off
CLS

OSQL.EXE -n -E -w 65536 -d NORTHWIND -i “%~f0″

PAUSE&GOTO:EOF
*/

– SQL starts below here
START:
GO
SELECT * FROM AUTHOR
GO

DOS Command Index

ASSOC    Displays or modifies file extension associations.
AT    Schedules commands and programs to run on a computer.
ATTRIB    Displays or changes file attributes.
BREAK    Sets or clears extended CTRL+C checking.
CACLS    Displays or modifies access control lists (ACLs) of files.
CALL    Calls one batch program from another.
CD    Displays the name of or changes the current directory.
CHCP    Displays or sets the active code page number.
CHDIR    Displays the name of or changes the current directory.
CHKDSK    Checks a disk and displays a status report.
CHKNTFS    Displays or modifies the checking of disk at boot time.
CLS    Clears the screen.
CMD    Starts a new instance of the Windows command interpreter.
COLOR    Sets the default console foreground and background colors.
COMP    Compares the contents of two files or sets of files.
COMPACT    Displays or alters the compression of files on NTFS partitions.
CONVERT    Converts FAT volumes to NTFS. You cannot convert the
COPY    Copies one or more files to another location.
DATE    Displays or sets the date.
DEL    Deletes one or more files.
DIR    Displays a list of files and subdirectories in a directory.
DISKCOMP    Compares the contents of two floppy disks.
DISKCOPY    Copies the contents of one floppy disk to another.
DOSKEY    Edits command lines, recalls Windows commands, and creates macros.
ECHO    Displays messages, or turns command echoing on or off.
ENDLOCAL    Ends localization of environment changes in a batch file.
ERASE    Deletes one or more files.
EXIT    Quits the CMD.EXE program (command interpreter).
FC    Compares two files or sets of files, and displays the differences
FIND    Searches for a text string in a file or files.
FINDSTR    Searches for strings in files.
FOR    Runs a specified command for each file in a set of files.
FORMAT    Formats a disk for use with Windows.
FTYPE    Displays or modifies file types used in file extension associations.
GOTO    Directs the Windows command interpreter to a labeled line in a
GRAFTABL    Enables Windows to display an extended character set in graphics
HELP    Provides Help information for Windows commands.
IF    Performs conditional processing in batch programs.
LABEL    Creates, changes, or deletes the volume label of a disk.
MD    Creates a directory.
MKDIR    Creates a directory.
MODE    Configures a system device.
MORE    Displays output one screen at a time.
MOVE    Moves one or more files from one directory to another directory.
PATH    Displays or sets a search path for executable files.
PAUSE    Suspends processing of a batch file and displays a message.
POPD    Restores the previous value of the current directory saved by PUSHD.
PRINT    Prints a text file.
PROMPT    Changes the Windows command prompt.
PUSHD    Saves the current directory then changes it.
RD    Removes a directory.
RECOVER    Recovers readable information from a bad or defective disk.
REM    Records comments (remarks) in batch files or CONFIG.SYS.
REN    Renames a file or files.
RENAME    Renames a file or files.
REPLACE    Replaces files.
RMDIR    Removes a directory.
SET    Displays, sets, or removes Windows environment variables.
SETLOCAL    Begins localization of environment changes in a batch file.
SHIFT    Shifts the position of replaceable parameters in batch files.
SORT    Sorts input.
START    Starts a separate window to run a specified program or command.
SUBST    Associates a path with a drive letter.
TIME    Displays or sets the system time.
TITLE    Sets the window title for a CMD.EXE session.
TREE    Graphically displays the directory structure of a drive or path.
TYPE    Displays the contents of a text file.
VER    Displays the Windows version.
VERIFY    Tells Windows whether to verify that your files are written
VOL    Displays a disk volume label and serial number.
XCOPY    Copies files and directory trees.

DOS Batch - Find and Replace - Search a file and replace all occurrences of a string with another string

This batch allows string substitution in a text file. It parses each line of a text file for a particular string and replaces it with another string.
I.e. To replace all occurrences of “Yellow Submarine” in “color.txt” with “uboot” and put the output on the screen run:
BatchSubstitute.bat “Yellow Submarine” uboot color.txt
Or
type color.txt|BatchSubstitute.bat “Yellow Submarine” uboot

Optionally pipe the output into a new file, i.e.
BatchSubstitute.bat “Yellow Submarine” uboot color.txt>newfile.txt
Or
type color.txt|BatchSubstitute.bat “Yellow Submarine” uboot>newfile.txt
Note: Due to the nature of the FOR command and string substitution, the following known restrictions apply:

* Lines starting with “]” character will end up empty
* OldStr must not start with “*”

@echo off
REM — Prepare the Command Processor –
SETLOCAL ENABLEEXTENSIONS
SETLOCAL DISABLEDELAYEDEXPANSION

::BatchSubstitude - parses a File line by line and replaces a substring”
::syntax: BatchSubstitude.bat OldStr NewStr File
::          OldStr [in] - string to be replaced
::          NewStr [in] - string to replace with
::          File   [in] - file to be parsed
if “%*”==”" findstr “^::” “%~f0″&GOTO:EOF
for /f “tokens=1,* delims=]” %%A in (’”type %3|find /n /v “”"‘) do (
set “line=%%B”
if defined line (
call set “line=echo.%%line:%~1=%~2%%”
for /f “delims=” %%X in (’”echo.”%%line%%”"‘) do %%~X
) ELSE echo.
)

DOS Batch File - Progress - Show progress in batch using the title bar

Showing progress in the output window seems impractical in DOS batch, since there is no way to overwrite a previews output for an updated progress status during each progress tick. Using the ECHO command is not nice, screen content quickly scrolls out of sight. A practicable alternative may be to use the window TITLE for the progress message. A nice side effect is that you can minimize the batch window and still observe the progress output in the task bar, since the task bar text will always reflect the window title text.

@ECHO OFF
set "max=11"
call :initProgress %max% "Window Title: [PPP]”
for /l %%N in (1,1,%max%) do (
ping -n 2 -w 1 127.0.0.1>NUL
call:doProgress
)
GOTO:EOF

:initProgress max format — initialize an internal progress counter and display the progress in percent
::                       — max    [in]     - progress counter maximum, equal to 100 percent
::                       — format [in,opt] - title string formatter, default is ‘[P] completed.’
:$created 20060101 :$changed 20080327
set /a “ProgressCnt=-1″
set /a “ProgressMax=%~1″
set “ProgressFormat=%~2″
if not defined ProgressFormat set “ProgressFormat=[PPPP]”
set “ProgressFormat=%ProgressFormat:[PPPP]=[P] completed.%”
call:doProgress
EXIT /b

:doProgress — display the next progress tick
:$created 20060101 :$changed 20080327
set /a “ProgressCnt+=1″
SETLOCAL ENABLEDELAYEDEXPANSION
set /a “per100=100*ProgressCnt/ProgressMax”
set /a “per10=per100/10″
set /a “per10m=10-per100/10-1″
set “P=%per100%%%”
set “PP=”
for /l %%N in (0,1,%per10%) do call set “PP=%%PP%%*”
for /l %%N in (%per10%,1,9) do call set “PP=%%PP%% ”
set “PPP=”
for /l %%N in (0,1,%per10m%) do call set “PPP=%%PPP%%*”
set “ProgressFormat=%ProgressFormat:[P]=!P!%”
set “ProgressFormat=%ProgressFormat:[PP]=!PP!%”
set “ProgressFormat=%ProgressFormat:[PPP]=!PPP!%”
title %ProgressFormat%
EXIT /b