You must have same rights on the machine you are running this from
shutdown /r /m \\severname
Showing posts with label Batch File. Show all posts
Showing posts with label Batch File. Show all posts
Tuesday, November 29, 2011
Tuesday, March 1, 2011
Get IP Addresses from a list of Servers
two files:
server_list.txt - this is your list of SERVERS
SERVER_IP.txt - Outputfile
@echo off
FOR /F %%G IN (server_list.txt) DO CALL :setvars %%G %%h
:setvars
SET COMPUTER=%1
FOR /F "tokens=2 delims=[]" %%A IN ('PING %Computer% -n 1') DO (
SET IP=%%A
)
echo. %COMPUTER% %IP% >> "SERVER_IP.txt"
goto:eof
server_list.txt - this is your list of SERVERS
SERVER_IP.txt - Outputfile
@echo off
FOR /F %%G IN (server_list.txt) DO CALL :setvars %%G %%h
:setvars
SET COMPUTER=%1
FOR /F "tokens=2 delims=[]" %%A IN ('PING %Computer% -n 1') DO (
SET IP=%%A
)
echo. %COMPUTER% %IP% >> "SERVER_IP.txt"
goto:eof
Get File Size of any file
@echo off
FOR %%A IN (C:\APP\log.txt) DO SET FileSize=%%~zA
echo %filesize%
pause
FOR %%A IN (C:\APP\log.txt) DO SET FileSize=%%~zA
echo %filesize%
pause
Is someone's account locked?
With the native NET command:
NET USER loginname/DOMAIN | FIND /I "Account active"
The account is either locked ("Locked") or active ("Yes").
With the native NET command:
NET USER loginname /DOMAIN /ACTIVE:YES
or, if the password needs to be reset as well:
NET USER loginname newpassword /DOMAIN /ACTIVE:YES
NET USER loginname/DOMAIN | FIND /I "Account active"
The account is either locked ("Locked") or active ("Yes").
With the native NET command:
NET USER loginname /DOMAIN /ACTIVE:YES
or, if the password needs to be reset as well:
NET USER loginname newpassword /DOMAIN /ACTIVE:YES
Wednesday, February 2, 2011
Rename Log files with unique name when greater than a certin size
@echo off
::Set vars
SET LOGFILE=\\\SUPPORT\LOGS\log.txt
SET LOGNAME=log
:CHECK_FILE
:: Create file if does not exist
IF EXIST %LOGFILE% (goto:CHECK_SIZE) ELSE (
echo Created %DATE% > %LOGFILE%
goto:CHECK_FILE
)
:CHECK_SIZE
FOR %%? IN (%LOGFILE%) DO (SET FILESIZE=%%~z?)
::Check if less than 10kb
If %FILESIZE% LSS 10000 (
GOTO:EOF
)
::Check if greater than 10kb, if so rename to unique name
If %FILESIZE% GTR 10000 (
ren %LOGFILE% "%LOGNAME%-%date:~4,2%-%date:~7,2%-%date:~10%-%time:~0,2%%time:~3,2%%time:~6,2%"
pause
echo Created %DATE% > %LOGFILE%
)
GOTO:EOF
::Set vars
SET LOGFILE=\\
SET LOGNAME=log
:CHECK_FILE
:: Create file if does not exist
IF EXIST %LOGFILE% (goto:CHECK_SIZE) ELSE (
echo Created %DATE% > %LOGFILE%
goto:CHECK_FILE
)
:CHECK_SIZE
FOR %%? IN (%LOGFILE%) DO (SET FILESIZE=%%~z?)
::Check if less than 10kb
If %FILESIZE% LSS 10000 (
GOTO:EOF
)
::Check if greater than 10kb, if so rename to unique name
If %FILESIZE% GTR 10000 (
ren %LOGFILE% "%LOGNAME%-%date:~4,2%-%date:~7,2%-%date:~10%-%time:~0,2%%time:~3,2%%time:~6,2%"
pause
echo Created %DATE% > %LOGFILE%
)
GOTO:EOF
Rename the file using the current system date
Here's how you'd rename the file using the current system date.
ren test.txt test%date:~4,2%-%date:~7,2%-%date:~10%.txt
or even better
ren test.txt test-%date:~4,2%-%date:~7,2%-%date:~10%-%time:~0,2%%time:~3,2%%time:~6,2%.txt
ren test.txt test%date:~4,2%-%date:~7,2%-%date:~10%.txt
or even better
ren test.txt test-%date:~4,2%-%date:~7,2%-%date:~10%-%time:~0,2%%time:~3,2%%time:~6,2%.txt
:Unique - returns a unique string based on a date-time-stamp, YYYYMMDDhhmmsscc
:Unique - returns a unique string based on a date-time-stamp, YYYYMMDDhhmmsscc
:Unique ret -- returns a unique string based on a date-time-stamp, YYYYMMDDhhmmsscc
:: -- ret [out,opt] - unique string
:$created 20060101 :$changed 20080219 :$categories StringOperation,DateAndTime
:$source http://www.dostips.com
SETLOCAL
for /f "skip=1 tokens=2-4 delims=(-)" %%a in ('"echo.|date"') do (
for /f "tokens=1-3 delims=/.- " %%A in ("%date:* =%") do (
set %%a=%%A&set %%b=%%B&set %%c=%%C))
set /a "yy=10000%yy% %%10000,mm=100%mm% %% 100,dd=100%dd% %% 100"
for /f "tokens=1-4 delims=:. " %%A in ("%time: =0%") do @set UNIQUE=%yy%%mm%%dd%%%A%%B%%C%%D
ENDLOCAL & IF "%~1" NEQ "" (SET %~1=%UNIQUE%) ELSE echo.%UNIQUE%
EXIT /b
:Unique ret -- returns a unique string based on a date-time-stamp, YYYYMMDDhhmmsscc
:: -- ret [out,opt] - unique string
:$created 20060101 :$changed 20080219 :$categories StringOperation,DateAndTime
:$source http://www.dostips.com
SETLOCAL
for /f "skip=1 tokens=2-4 delims=(-)" %%a in ('"echo.|date"') do (
for /f "tokens=1-3 delims=/.- " %%A in ("%date:* =%") do (
set %%a=%%A&set %%b=%%B&set %%c=%%C))
set /a "yy=10000%yy% %%10000,mm=100%mm% %% 100,dd=100%dd% %% 100"
for /f "tokens=1-4 delims=:. " %%A in ("%time: =0%") do @set UNIQUE=%yy%%mm%%dd%%%A%%B%%C%%D
ENDLOCAL & IF "%~1" NEQ "" (SET %~1=%UNIQUE%) ELSE echo.%UNIQUE%
EXIT /b
DOS BATCH - (Read File Properties)
http://www.robvanderwoude.com/battech_fileproperties.php
Many times we need to check a file's size, its last-modified date, its location, or we may require its fully qualified path in short (8.3) notation.
Arguably CMD's most versatile internal command to the rescue: FOR.
FOR %%? IN (file_to_be_queried) DO (
ECHO File Name Only : %%~n?
ECHO File Extension : %%~x?
ECHO Name in 8.3 notation : %%~sn?
ECHO File Attributes : %%~a?
ECHO Located on Drive : %%~d?
ECHO File Size : %%~z?
ECHO Last-Modified Date : %%~t?
ECHO Parent Folder : %%~dp?
ECHO Fully Qualified Path : %%~f?
ECHO FQP in 8.3 notation : %%~sf?
ECHO Location in the PATH : %%~dp$PATH:?
)
pause
Note: Not all of these properties can be read this way in every Windows version. With every new Windows version, more options became available.
Type FOR /? for more details.
Many of these properties can be combined, as is shown for the s option (short, or 8.3 notation).
Play with it, experiment, and learn. Have fun.
Many times we need to check a file's size, its last-modified date, its location, or we may require its fully qualified path in short (8.3) notation.
Arguably CMD's most versatile internal command to the rescue: FOR.
FOR %%? IN (file_to_be_queried) DO (
ECHO File Name Only : %%~n?
ECHO File Extension : %%~x?
ECHO Name in 8.3 notation : %%~sn?
ECHO File Attributes : %%~a?
ECHO Located on Drive : %%~d?
ECHO File Size : %%~z?
ECHO Last-Modified Date : %%~t?
ECHO Parent Folder : %%~dp?
ECHO Fully Qualified Path : %%~f?
ECHO FQP in 8.3 notation : %%~sf?
ECHO Location in the PATH : %%~dp$PATH:?
)
pause
Note: Not all of these properties can be read this way in every Windows version. With every new Windows version, more options became available.
Type FOR /? for more details.
Many of these properties can be combined, as is shown for the s option (short, or 8.3 notation).
Play with it, experiment, and learn. Have fun.
Wednesday, January 19, 2011
DOS BATCH - (FIND)
EXAMPLE:
@echo off
echo .. >> "USERS_DISC_%COMPUTER%.txt"
echo %DATE% %TIME% >> "USERS_DISC_%COMPUTER%.txt"
for /f "tokens=1,3" %%a in (qwinsta^|find /i "disc"') do CALL :process %%a %%b %%c
call USERS_DISC_%COMPUTER%.txt
goto:eof
:process
echo [%2] %1 >> "USERS_DISC_%COMPUTER%.txt"
goto:eof
Searches for a text string in a file or files.
FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ ...]]
/V Displays all lines NOT containing the specified string.
/C Displays only the count of lines containing the string.
/N Displays line numbers with the displayed lines.
/I Ignores the case of characters when searching for the string.
/OFF[LINE] Do not skip files with offline attribute set.
"string" Specifies the text string to find.
[drive:][path]filename
Specifies a file or files to search.
If a path is not specified, FIND searches the text typed at the prompt
or piped from another command.
@echo off
echo .. >> "USERS_DISC_%COMPUTER%.txt"
echo %DATE% %TIME% >> "USERS_DISC_%COMPUTER%.txt"
for /f "tokens=1,3" %%a in (qwinsta^|find /i "disc"') do CALL :process %%a %%b %%c
call USERS_DISC_%COMPUTER%.txt
goto:eof
:process
echo [%2] %1 >> "USERS_DISC_%COMPUTER%.txt"
goto:eof
Searches for a text string in a file or files.
FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ ...]]
/V Displays all lines NOT containing the specified string.
/C Displays only the count of lines containing the string.
/N Displays line numbers with the displayed lines.
/I Ignores the case of characters when searching for the string.
/OFF[LINE] Do not skip files with offline attribute set.
"string" Specifies the text string to find.
[drive:][path]filename
Specifies a file or files to search.
If a path is not specified, FIND searches the text typed at the prompt
or piped from another command.
Tuesday, January 18, 2011
DOS BATCH - (FOR IN DO)
echo off
FOR %%b in (A, B, C) DO IF %%b == B echo B is in the set!
pause
FOR %%a in (C:\windows\*.*) DO echo %%a
pause
EXAMPLE
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
http://www.dostips.com/DosCommandIndex.htm#FOR
Runs a specified command for each file in a set of files.
FOR %variable IN (set) DO command [command-parameters]
%variable Specifies a single letter replaceable parameter.
(set) Specifies a set of one or more files. Wildcards may be used.
command Specifies the command to carry out for each file.
command-parameters
Specifies parameters or switches for the specified command.
To use the FOR command in a batch program, specify %%variable instead
of %variable. Variable names are case sensitive, so %i is different
from %I.
If Command Extensions are enabled, the following additional
forms of the FOR command are supported:
FOR /D %variable IN (set) DO command [command-parameters]
If set contains wildcards, then specifies to match against directory
names instead of file names.
FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters]
Walks the directory tree rooted at [drive:]path, executing the FOR
statement in each directory of the tree. If no directory
specification is specified after /R then the current directory is
assumed. If set is just a single period (.) character then it
will just enumerate the directory tree.
FOR /L %variable IN (start,step,end) DO command [command-parameters]
The set is a sequence of numbers from start to end, by step amount.
So (1,1,5) would generate the sequence 1 2 3 4 5 and (5,-1,1) would
generate the sequence (5 4 3 2 1)
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]
or, if usebackq option present:
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ('string') DO command [command-parameters]
FOR /F ["options"] %variable IN (`command`) DO command [command-parameters]
filenameset is one or more file names. Each file is opened, read
and processed before going on to the next file in filenameset.
Processing consists of reading in the file, breaking it up into
individual lines of text and then parsing each line into zero or
more tokens. The body of the for loop is then called with the
variable value(s) set to the found token string(s). By default, /F
passes the first blank separated token from each line of each file.
Blank lines are skipped. You can override the default parsing
behavior by specifying the optional "options" parameter. This
is a quoted string which contains one or more keywords to specify
different parsing options. The keywords are:
eol=c - specifies an end of line comment character
(just one)
skip=n - specifies the number of lines to skip at the
beginning of the file.
delims=xxx - specifies a delimiter set. This replaces the
default delimiter set of space and tab.
tokens=x,y,m-n - specifies which tokens from each line are to
be passed to the for body for each iteration.
This will cause additional variable names to
be allocated. The m-n form is a range,
specifying the mth through the nth tokens. If
the last character in the tokens= string is an
asterisk, then an additional variable is
allocated and receives the remaining text on
the line after the last token parsed.
usebackq - specifies that the new semantics are in force,
where a back quoted string is executed as a
command and a single quoted string is a
literal string command and allows the use of
double quotes to quote file names in
filenameset.
Some examples might help:
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
would parse each line in myfile.txt, ignoring lines that begin with
a semicolon, passing the 2nd and 3rd token from each line to the for
body, with tokens delimited by commas and/or spaces. Notice the for
body statements reference %i to get the 2nd token, %j to get the
3rd token, and %k to get all remaining tokens after the 3rd. For
file names that contain spaces, you need to quote the filenames with
double quotes. In order to use double quotes in this manner, you also
need to use the usebackq option, otherwise the double quotes will be
interpreted as defining a literal string to parse.
%i is explicitly declared in the for statement and the %j and %k
are implicitly declared via the tokens= option. You can specify up
to 26 tokens via the tokens= line, provided it does not cause an
attempt to declare a variable higher than the letter 'z' or 'Z'.
Remember, FOR variables are single-letter, case sensitive, global,
and you can't have more than 52 total active at any one time.
You can also use the FOR /F parsing logic on an immediate string, by
making the filenameset between the parenthesis a quoted string,
using single quote characters. It will be treated as a single line
of input from a file and parsed.
Finally, you can use the FOR /F command to parse the output of a
command. You do this by making the filenameset between the
parenthesis a back quoted string. It will be treated as a command
line, which is passed to a child CMD.EXE and the output is captured
into memory and parsed as if it was a file. So the following
example:
FOR /F "usebackq delims==" %i IN (`set`) DO @echo %i
would enumerate the environment variable names in the current
environment.
In addition, substitution of FOR variable references has been enhanced.
You can now use the following optional syntax:
%~I - expands %I removing any surrounding quotes (")
%~fI - expands %I to a fully qualified path name
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only
%~nI - expands %I to a file name only
%~xI - expands %I to a file extension only
%~sI - expanded path contains short names only
%~aI - expands %I to file attributes of file
%~tI - expands %I to date/time of file
%~zI - expands %I to size of file
%~$PATH:I - searches the directories listed in the PATH
environment variable and expands %I to the
fully qualified name of the first one found.
If the environment variable name is not
defined or the file is not found by the
search, then this modifier expands to the
empty string
The modifiers can be combined to get compound results:
%~dpI - expands %I to a drive letter and path only
%~nxI - expands %I to a file name and extension only
%~fsI - expands %I to a full path name with short names only
%~dp$PATH:I - searches the directories listed in the PATH
environment variable for %I and expands to the
drive letter and path of the first one found.
%~ftzaI - expands %I to a DIR like output line
In the above examples %I and PATH can be replaced by other valid
values. The %~ syntax is terminated by a valid FOR variable name.
Picking upper case variable names like %I makes it more readable and
avoids confusion with the modifiers, which are not case sensitive.
FOR %%b in (A, B, C) DO IF %%b == B echo B is in the set!
pause
FOR %%a in (C:\windows\*.*) DO echo %%a
pause
EXAMPLE
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
http://www.dostips.com/DosCommandIndex.htm#FOR
Runs a specified command for each file in a set of files.
FOR %variable IN (set) DO command [command-parameters]
%variable Specifies a single letter replaceable parameter.
(set) Specifies a set of one or more files. Wildcards may be used.
command Specifies the command to carry out for each file.
command-parameters
Specifies parameters or switches for the specified command.
To use the FOR command in a batch program, specify %%variable instead
of %variable. Variable names are case sensitive, so %i is different
from %I.
If Command Extensions are enabled, the following additional
forms of the FOR command are supported:
FOR /D %variable IN (set) DO command [command-parameters]
If set contains wildcards, then specifies to match against directory
names instead of file names.
FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters]
Walks the directory tree rooted at [drive:]path, executing the FOR
statement in each directory of the tree. If no directory
specification is specified after /R then the current directory is
assumed. If set is just a single period (.) character then it
will just enumerate the directory tree.
FOR /L %variable IN (start,step,end) DO command [command-parameters]
The set is a sequence of numbers from start to end, by step amount.
So (1,1,5) would generate the sequence 1 2 3 4 5 and (5,-1,1) would
generate the sequence (5 4 3 2 1)
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]
or, if usebackq option present:
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ('string') DO command [command-parameters]
FOR /F ["options"] %variable IN (`command`) DO command [command-parameters]
filenameset is one or more file names. Each file is opened, read
and processed before going on to the next file in filenameset.
Processing consists of reading in the file, breaking it up into
individual lines of text and then parsing each line into zero or
more tokens. The body of the for loop is then called with the
variable value(s) set to the found token string(s). By default, /F
passes the first blank separated token from each line of each file.
Blank lines are skipped. You can override the default parsing
behavior by specifying the optional "options" parameter. This
is a quoted string which contains one or more keywords to specify
different parsing options. The keywords are:
eol=c - specifies an end of line comment character
(just one)
skip=n - specifies the number of lines to skip at the
beginning of the file.
delims=xxx - specifies a delimiter set. This replaces the
default delimiter set of space and tab.
tokens=x,y,m-n - specifies which tokens from each line are to
be passed to the for body for each iteration.
This will cause additional variable names to
be allocated. The m-n form is a range,
specifying the mth through the nth tokens. If
the last character in the tokens= string is an
asterisk, then an additional variable is
allocated and receives the remaining text on
the line after the last token parsed.
usebackq - specifies that the new semantics are in force,
where a back quoted string is executed as a
command and a single quoted string is a
literal string command and allows the use of
double quotes to quote file names in
filenameset.
Some examples might help:
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
would parse each line in myfile.txt, ignoring lines that begin with
a semicolon, passing the 2nd and 3rd token from each line to the for
body, with tokens delimited by commas and/or spaces. Notice the for
body statements reference %i to get the 2nd token, %j to get the
3rd token, and %k to get all remaining tokens after the 3rd. For
file names that contain spaces, you need to quote the filenames with
double quotes. In order to use double quotes in this manner, you also
need to use the usebackq option, otherwise the double quotes will be
interpreted as defining a literal string to parse.
%i is explicitly declared in the for statement and the %j and %k
are implicitly declared via the tokens= option. You can specify up
to 26 tokens via the tokens= line, provided it does not cause an
attempt to declare a variable higher than the letter 'z' or 'Z'.
Remember, FOR variables are single-letter, case sensitive, global,
and you can't have more than 52 total active at any one time.
You can also use the FOR /F parsing logic on an immediate string, by
making the filenameset between the parenthesis a quoted string,
using single quote characters. It will be treated as a single line
of input from a file and parsed.
Finally, you can use the FOR /F command to parse the output of a
command. You do this by making the filenameset between the
parenthesis a back quoted string. It will be treated as a command
line, which is passed to a child CMD.EXE and the output is captured
into memory and parsed as if it was a file. So the following
example:
FOR /F "usebackq delims==" %i IN (`set`) DO @echo %i
would enumerate the environment variable names in the current
environment.
In addition, substitution of FOR variable references has been enhanced.
You can now use the following optional syntax:
%~I - expands %I removing any surrounding quotes (")
%~fI - expands %I to a fully qualified path name
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only
%~nI - expands %I to a file name only
%~xI - expands %I to a file extension only
%~sI - expanded path contains short names only
%~aI - expands %I to file attributes of file
%~tI - expands %I to date/time of file
%~zI - expands %I to size of file
%~$PATH:I - searches the directories listed in the PATH
environment variable and expands %I to the
fully qualified name of the first one found.
If the environment variable name is not
defined or the file is not found by the
search, then this modifier expands to the
empty string
The modifiers can be combined to get compound results:
%~dpI - expands %I to a drive letter and path only
%~nxI - expands %I to a file name and extension only
%~fsI - expands %I to a full path name with short names only
%~dp$PATH:I - searches the directories listed in the PATH
environment variable for %I and expands to the
drive letter and path of the first one found.
%~ftzaI - expands %I to a DIR like output line
In the above examples %I and PATH can be replaced by other valid
values. The %~ syntax is terminated by a valid FOR variable name.
Picking upper case variable names like %I makes it more readable and
avoids confusion with the modifiers, which are not case sensitive.
Friday, January 14, 2011
Creating and using a variable array in DOS
http://www.sprint.net.au/~terbut/usefulbox/msdoscmds.htm
I searched everywhere without success for a method to produce an array in DOS.
This solution has proven to be very successful.
The basics is to use a variable name that has some type of separator, like a period ".", the second half of the variable name can then be substituted with the contents of another variable, following is very a simple example.
:: set the segment variables
set agbtp.1=A
set agbtp.2=B
Notice the period between the 'agbtp' and '1' ?
Next setup or supply a third variable that will be substituted into the array.
:: set the segid
set segid=1
Now put the whole lot in to a FOR-DO to obtain the new variable from the array based on the supplied segid. Note the '^=' in the delims, this allows the search to use the '=' as a separator. The 'find' with the ".variable=" is also necessary to do the correct filtering.
:: calculate the Segment printed variable
for /F "tokens=2 delims=^=" %%i in ('set agbtp.%segid% ^| find ".%segid%=" ') do set psegid=%%i
This resulted in the variable 'psegid' now containing 'A'.
If the variable 'segid' had been loaded with the value '2', then the 'psegid' would then contain 'B'.
This may all appear very simplistic, but if there was a problem where you wanted to count from 0 to 255, and on each count, produce the output in HEX (00-FF). Setup an array of:
set myhex.0=00
set myhex.1=01
set myhex.2=02
" " " - (repeat from 3 to 252 / 03 to FC)
set myhex.253=FD
set myhex.254=FE
set myhex.255=FF
Set up a counting loop.
set /A cntr=0
set /A scntr=256
:loop
Then substitute in the variable and output the results.
for /F "tokens=2 delims=^=" %%i in ('set myhex.%cntr% ^| find ".%cntr%=" ') do echo %%i
And loop until finished.
set /A cntr=%cntr%+1
if NOT [%scntr%]==[%cntr%] goto loop
This technique can be used to read data or configuration from a text file, into an array.
I searched everywhere without success for a method to produce an array in DOS.
This solution has proven to be very successful.
The basics is to use a variable name that has some type of separator, like a period ".", the second half of the variable name can then be substituted with the contents of another variable, following is very a simple example.
:: set the segment variables
set agbtp.1=A
set agbtp.2=B
Notice the period between the 'agbtp' and '1' ?
Next setup or supply a third variable that will be substituted into the array.
:: set the segid
set segid=1
Now put the whole lot in to a FOR-DO to obtain the new variable from the array based on the supplied segid. Note the '^=' in the delims, this allows the search to use the '=' as a separator. The 'find' with the ".variable=" is also necessary to do the correct filtering.
:: calculate the Segment printed variable
for /F "tokens=2 delims=^=" %%i in ('set agbtp.%segid% ^| find ".%segid%=" ') do set psegid=%%i
This resulted in the variable 'psegid' now containing 'A'.
If the variable 'segid' had been loaded with the value '2', then the 'psegid' would then contain 'B'.
This may all appear very simplistic, but if there was a problem where you wanted to count from 0 to 255, and on each count, produce the output in HEX (00-FF). Setup an array of:
set myhex.0=00
set myhex.1=01
set myhex.2=02
" " " - (repeat from 3 to 252 / 03 to FC)
set myhex.253=FD
set myhex.254=FE
set myhex.255=FF
Set up a counting loop.
set /A cntr=0
set /A scntr=256
:loop
Then substitute in the variable and output the results.
for /F "tokens=2 delims=^=" %%i in ('set myhex.%cntr% ^| find ".%cntr%=" ') do echo %%i
And loop until finished.
set /A cntr=%cntr%+1
if NOT [%scntr%]==[%cntr%] goto loop
This technique can be used to read data or configuration from a text file, into an array.
Thursday, January 13, 2011
Logoff Disconnected users dos batch help
@echo off
for /f "tokens=1,2,3" %%a in ('qwinsta^|find /i "disc"') do call :process %%a %%b %%c
goto :eof
:process
echo. %1
echo. %2
echo. %3
logoff %2
pause
---------------------------
@echo off
for /f "tokens=2,3" %%a in ('qwinsta^|find /i "Active"') do call :process %%a %%b
goto :eof
:process
set username=%1
set sessionID=%2
echo. Found user: %username% under session ID %sessionID%
pause
if [%username%]=[Administrator] goto :eof
if [%username%] NEQ [] logoff %sessionID%
for /f "tokens=1,2,3" %%a in ('qwinsta^|find /i "disc"') do call :process %%a %%b %%c
goto :eof
:process
echo. %1
echo. %2
echo. %3
logoff %2
pause
---------------------------
@echo off
for /f "tokens=2,3" %%a in ('qwinsta^|find /i "Active"') do call :process %%a %%b
goto :eof
:process
set username=%1
set sessionID=%2
echo. Found user: %username% under session ID %sessionID%
pause
if [%username%]=[Administrator] goto :eof
if [%username%] NEQ [] logoff %sessionID%
Trim Quotes - Remove surrounding quotes via FOR command
Description:
The FOR command can be used to safely remove quotes surrounding a string. If the string does not have quotes then it will remain unchanged.
Script:
set str="cmd politic"
echo.%str%
for /f "useback tokens=*" %%a in ('%str%') do set str=%%~a
echo.%str%
http://www.dostips.com/DtTipsStringManipulation.php
The FOR command can be used to safely remove quotes surrounding a string. If the string does not have quotes then it will remain unchanged.
Script:
set str="cmd politic"
echo.%str%
for /f "useback tokens=*" %%a in ('%str%') do set str=%%~a
echo.%str%
http://www.dostips.com/DtTipsStringManipulation.php
Remove - Remove a substring using string substitution
Description:
The string substitution feature can also be used to remove a substring from another string. The example shown here removes all occurrences of "the " from the string variable str.
Script:
set str=the cat in the hat
echo.%str%
set str=%str:the =%
echo.%str%
http://www.dostips.com/DtTipsStringManipulation.php
The string substitution feature can also be used to remove a substring from another string. The example shown here removes all occurrences of "the " from the string variable str.
Script:
set str=the cat in the hat
echo.%str%
set str=%str:the =%
echo.%str%
http://www.dostips.com/DtTipsStringManipulation.php
Left String - Extract characters from the beginning of a string
Description:
Similar to the Left function in VB a batch script can return a specified number of characters from the left side of a string by specifying a substring for an expansion given a position of 0 and a length using :~ while expanding a variable content. The example shows how to return the first 4 characters of a string.
Script:
set str=politic
echo.%str%
set str=%str:~0,4%
echo.%str%
also
@echo off
echo. %0
set str=%0
echo.%str%
set str=%str:~0,-10%
set str=%str:~1,-1%
echo.%str%
pause
Similar to the Left function in VB a batch script can return a specified number of characters from the left side of a string by specifying a substring for an expansion given a position of 0 and a length using :~ while expanding a variable content. The example shows how to return the first 4 characters of a string.
Script:
set str=politic
echo.%str%
set str=%str:~0,4%
echo.%str%
also
@echo off
echo. %0
set str=%0
echo.%str%
set str=%str:~0,-10%
set str=%str:~1,-1%
echo.%str%
pause
Wednesday, January 12, 2011
SET Curent path in a DOS BATCH file
If you want to know where the batch file lives: %~dp0
%0 is the name of the batch file. ~dp gives you the drive and path of the specified argument.
or
@echo off
SET currentpath = %~d0%~p0
echo %currentpath%
pause
%0 is the name of the batch file. ~dp gives you the drive and path of the specified argument.
or
@echo off
SET currentpath = %~d0%~p0
echo %currentpath%
pause
Tuesday, January 4, 2011
Loop a Bacth file to run every minute
@echo off
:loop
task here
ping -n 61 127.0.0.1 >nul
goto :loop
:loop
task here
ping -n 61 127.0.0.1 >nul
goto :loop
Wednesday, December 22, 2010
Create Batch File to Start or End Window Services
www.tech-recipes.com
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"
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"
STOP SERVICES and FOR LOOPS in Batch files
www.tech-recipes.com
The key is to use delimaters...well, sorta. You want to trick the FOR loop into looking for delimiters.
~~ SERVICES.TXT ~~
; be sure to surround your values by QUOTES (")
"Apache Tomcat 4.1.31"
"Apache Tomcat 5.0.27"
"MySQL41"
; and with the EOL switch, lines beginning in ";" are ignored
~~ START.EM.UP.BAT ~~
FOR /F "eol=; tokens=1,2,3,4,5,6,7* delims= " %%a IN (SERVICES.TXT) DO NET STOP %%a %%b %%c %%d %%e %%f %%g
also notice a few things
lastly, the resulting output:NET STOP "Apache Tomcat 4.1.31"
NET STOP "Apache Tomcat 5.0.27"
NET STOP "MySQL41"
The key is to use delimaters...well, sorta. You want to trick the FOR loop into looking for delimiters.
~~ SERVICES.TXT ~~
; be sure to surround your values by QUOTES (")
"Apache Tomcat 4.1.31"
"Apache Tomcat 5.0.27"
"MySQL41"
; and with the EOL switch, lines beginning in ";" are ignored
~~ START.EM.UP.BAT ~~
FOR /F "eol=; tokens=1,2,3,4,5,6,7* delims= " %%a IN (SERVICES.TXT) DO NET STOP %%a %%b %%c %%d %%e %%f %%g
also notice a few things
- 1. no quotes around filename
- 2. the "%%x" variables have two % symbols (this is because i'm running inside of a BAT already.
- 3. there are just as many "tokens" as there are "%%x" variables
- 4. there is only a space after the delims= declaration
lastly, the resulting output:NET STOP "Apache Tomcat 4.1.31"
NET STOP "Apache Tomcat 5.0.27"
NET STOP "MySQL41"
Subscribe to:
Posts (Atom)