Δ
Your First Script
![Description: bar1](http://eddiejackson.net/web_images/lightgraybar.bmp)
start - run - cmd.exe {enter} * you
should now be at the black console (used to be called DOS) * * you can now
just call it the console or command prompt *
* let's begin your first
script *
type edit {enter} * you should now be at a blue screen *
type the following:
rem --------------------------------
@echo off
TITLE My First Script
COLOR 0A
CLS
ECHO This is my first script.
PAUSE CLS
ECHO This will create a text file list of all the files
on your computer's c:\ drive REM This is the command dir
c:\ /s >"%userprofile%\desktop\list.txt" cls
echo LIST IS COMPLETE!
PAUSE
notepad.exe "%userprofile%\desktop\list.txt"
rem
----------------------------------
now go to file and save like this
myscript.bat - select [OK] then
back to File and Exit
type myscript.bat
watch your program run
when the script is done, type "%userprofile%\desktop\list.txt"
(or just view the open notepad doc)
you see should all the files on C:\ drive
Once you
have done that, let's copy and paste or open your script with Notepad++.
Notepad++ is good because it has syntax highlighting, which makes editing much
easier.
![Description: bar1](http://eddiejackson.net/web_images/lightgraybar.bmp)
Δ
How-To Quick Reference
![Description: bar1](http://eddiejackson.net/web_images/lightgraybar.bmp)
A B
C
∆ Copy
∆
copy (basic)
Copy a file
C:\
Command Prompt |
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>copy "file1.txt"
"c:\NewFolder\"
1 file(s) copied.
C:\>_
Syntax
command COPY [/A | /B]
source [/A | /B] [+ source [/A | /B] [+ ...]] [destination] [/A | /B]] [/V] [/Y
| /-Y]
source Specifies the file or files to be copied. /A Indicates
an ASCII text file.
/B Indicates a binary file. destination
Specifies the directory or filename for the new file(s).
/V Verifies
that new files are written correctly.
/Y Suppresses prompting to confirm
you want to overwrite an existing destination file.
/-Y Causes prompting
to confirm you want to overwrite an existing destination file.
|
∆
copy with prompt override
C:\
Command Prompt |
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>copy /y "file1.txt"
"c:\NewFolder\"
1 file(s) copied.
C:\>_ |
∆
copy with verify and prompt override
C:\
Command Prompt
|
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>copy /y /v "file1.txt"
"c:\NewFolder\"
1 file(s) copied.
C:\>_
|
∆
copy using input as a variable
(it would look like this when you launch file: YourFile.bat
FileToCopy.txt)
C:\
Command Prompt
|
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>YourFile.bat
file1.txt
code (YourFile.bat):
copy
/y /v %1 "C:\NewFolder\"
Output:
copy /y "file1.txt"
"c:\NewFolder\"
1 file(s) copied.
C:\>_
|
D
∆ Delete
∆
delete (basic) Deletes a file
C:\
Command Prompt
|
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>del "file1.txt"
C:\>_
Syntax
command DEL [/P] [/F] [/S]
[/Q] [/A[[:]attributes]] names ERASE [/P] [/F] [/S] [/Q] [/A[[:]attributes]]
names
names Specifies a list of one or more files or directories.
Wildcards may be used to delete multiple files. If a directory is specified, all
files within the directory will be deleted.
/P Prompts for confirmation
before deleting each file.
/F Force deleting of read-only files.
/S Delete specified files from all subdirectories.
/Q Quiet mode, do
not ask if ok to delete on global wildcard
/A Selects files to delete
based on attributes
attributes R
Read-only files S System files
H Hidden files A Files ready for archiving - Prefix meaning not
If Command Extensions are enabled DEL and ERASE change as follows:
The display
semantics of the /S switch are reversed in that it shows you only
|
∆
delete with prompt override
(useful if deleting many files)
C:\
Command Prompt
|
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>del /q "file*.txt"
C:\>_
|
∆
delete with prompt override and delete file from all
subdirectories
C:\
Command Prompt
|
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>del /q /s "file1.txt"
C:\>_ |
∆
delete using input as a variable
(it would look like this when you launch file: YourFile.bat
FileToDel.txt) YourFile.bat FileToDel.txt
del /q "%1"
∆
dir
List directories
C:\
Command Prompt
|
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>dir
03/29/2012
02:03 PM 671
document1.log
03/29/2012 02:04 PM 671
document2.log 03/29/2012 02:05 PM 671
document3.log
3 File(s)
2,013 bytes
4 Dir(s) 6,542,013 bytes free
C:\>_
Syntax
command DIR
[drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
[/O[[:]sortorder]] [/P] [/Q] [/S] [/T[[:]timefield]] [/W] [/X] [/4]
[drive:][path][filename] Specifies drive, directory, or files to list.
attributes D Directories R Read-only files H Hidden files A Files ready for
archiving S System files - Prefix meaning not
/B Uses bare format (no
heading information or summary). /C Display the thousand separator in file
sizes. This is the default. Use /-C to disable display of separator.
/D Same
as wide but files are list sorted by column.
/L Uses lowercase.
/N New
long list format where filenames are on the far right.
/O List by files in
sorted order. sortorder N By name (alphabetic) S By size (smallest first) E
By extension (alphabetic) D By date/time (oldest first) G Group directories
first - Prefix to reverse order
/P Pauses after each screenful of
information.
/Q Display the owner of the file.
/S Displays files in
specified directory and all subdirectories.
/T Control what time field
displayed or used for sorting
timefield
C Creation A Last Access W
Last Written
/W Uses wide list format.
/X This displays the short names
generated for non-8dot3 file names. The format is that of /N with the short name
inserted before the long name. If no short name is present, blanks are displayed
in its place.
/4 Displays four-digit years
|
F ∆
Find Use the FIND command to search for a specific string in
a file or files and send the specified lines to your output device.
C:\
Command Prompt
|
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>find
/c /i "test" test.txt
----------- TEST.TXT: 1
C:\>_
Syntax
command FIND [/V] [/C] [/N]
[/I] "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.
"string" Specifies the text string to find. [drive:][path]filename
|
∆
For Loop
Use the FOR command to cycle through a list.
C:\
Command Prompt
|
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>myfile.cmd
[contents of myfile.cmd]
for /f "tokens=* delims= " %%a in
(C:\workstations.txt) do ( ping -a -n 2 -w 750 %%a | find "Reply" > nul if
errorlevel 1 (echo %%a, OFFLINE >> "%OutputFile2%" & echo %%a OFFLINE & echo %%a
>> "C:\newlist.txt" ) else ( echo %%a, ONLINE >> "%OutputFile%" & echo %%a
ONLINE )
)
Syntax
command 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.
|
I ∆
If Do
M ∆
Make directory
Creates a directory.
C:\
Command Prompt
|
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>md
c:\temp
C:\>cd temp
C:\temp>
Syntax
MKDIR [drive:]path MD [drive:]path
|
∆
Move
Moves files and renames files and directories.
C:\
Command Prompt
|
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>move "file1.txt"
"c:\temp"
1 file(s) moved.
C:\>_
Syntax
command
To move one or more files: MOVE [/Y | /-Y]
[drive:][path]filename1[,...] destination
To rename a directory: MOVE [/Y
| /-Y] [drive:][path]dirname1 dirname2
[drive:][path]filename1 Specifies
the location and name of the file or files you want to move.
destination
Specifies the new location of the file. Destination can consist of a drive
letter and colon, a directory name, or a combination. If you are moving only one
file, you can also include a filename if you want to rename the file when you
move it.
[drive:][path]dirname1 Specifies the directory you want to rename.
dirname2 Specifies the new name of the directory.
/Y Suppresses
prompting to confirm you want to overwrite an existing destination file.
/-Y
Causes prompting to confirm you want to overwrite an existing destination file.
|
R
∆
Remove directory
Removes (deletes) a directory.
C:\
Command Prompt
|
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>rd
"c:\tempo"
C:\>_
Syntax
command RMDIR [/S] [/Q]
[drive:]path RD [/S] [/Q] [drive:]path
/S Removes all directories and
files in the specified directory in addition to the directory itself. Used to
remove a directory tree.
/Q Quiet mode, do not ask if ok to remove a
directory tree with /S.
|
R
∆
Rename
Renames a file or files.
C:\
Command Prompt
|
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>ren "file1.txt"
"file4.txt"
C:\>_
Syntax
command RENAME
[drive:][path][directoryname1 | filename1] [directoryname2 | filename2]
REN [drive:][path][directoryname1 | filename1] [directoryname2 | filename2]
Note that you cannot specify a new drive or path for your destination.
|
∆
Taskkill
Kill a running process
C:\
Command Prompt
|
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>taskkill /f
/im notepad.exe
SUCCESS: The process "notepad.exe" with PID 2588 has been terminated.
C:\>_
Syntax
command taskkill [/s
Computer] [/u Domain\User [/p Password]]] [/fi FilterName] [/pid ProcessID]|[/im
ImageName] [/f][/t]
/s computer Specifies the name or IP address of a
remote computer (do not use backslashes). The default is the local computer.
/u domain\user Runs the command with the account permissions of the user
specified by User or Domain\User. The default is the permissions of the current
logged on user on the computer issuing the command.
/p password
Specifies the password of the user account that is specified in the /u
parameter.
/fi FilterName Specifies the types of process(es) to include
in or exclude from termination. The following are valid filter names, operators,
and values.
Hostname eq, ne Any
valid string. Status
eq, ne RUNNING|NOT RESPONDING Imagename eq, ne Any valid
string. PID
eq, ne, gt, lt, ge, le Any valid positive integer. Session
eq, ne, gt, lt, ge, le Any valid session number. CPUTime
eq, ne, gt, lt, ge, le Valid time in the format of hh:mm:ss. The mm
and ss parameters should be between 0 and 59 and hh can be any
valid unsigned numeric value. Memusage eq, ne, gt,
lt, ge, le Any valid integer. Username eq, ne
Any valid user name ([Domain\]User). Services
eq, ne Any valid string. Windowtitle eq, ne Any valid
string.
/pid processID Specifies the process ID of the process to be
terminated.
/im ImageName Specifies the image name of the process to be
terminated. Use the wildcard (*) to specify all image names.
/f
Specifies that process(es) be forcefully terminated. This parameter is ignored
for remote processes; all remote processes are forcefully terminated.
/t
Specifies to terminate all child processes along with the parent process,
commonly known as a tree kill.
|
∆
Tasklist
List running processes
C:\
Command Prompt
|
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>tasklist
Image Name
PID Session
Name Session#
Mem Usage ==================== ======== ================ ==========
========== System Idle Process
0
Services
0
24 K
C:\>_
Syntax
command TASKLIST [/S system
[/U username [/P [password]]]] [/M [module] | /SVC | /V] [/FI filter] [/FO
format] [/NH]
/S system Specifies the remote system to connect to.
/U [domain\]user Specifies the user context under which the command should
execute.
/P [password] Specifies the password for the given user
context. Prompts for input if omitted.
/M [module] Lists all tasks
currently using the given exe/dll name. If the module name is not specified all
loaded modules are displayed.
/SVC Displays services hosted in each
process.
/V Displays verbose task information.
/FI filter
Displays a set of tasks that match a given criteria specified by the filter.
/FO format Specifies the output format. Valid values: "TABLE", "LIST",
"CSV".
/NH Specifies that the "Column Header" should not be displayed in
the output. Valid only for "TABLE" and "CSV" formats. Filters
STATUS
eq, ne RUNNING | NOT RESPONDING | UNKNOWN IMAGENAME
eq, ne Image name PID
eq, ne, gt, lt, ge, le PID value SESSION
eq, ne, gt, lt, ge, le Session number SESSIONNAME
eq, ne Session name CPUTIME
eq, ne, gt, lt, ge, le CPU time in the format of hh:mm:ss.
hh - hours,
mm - minutes
ss - seconds MEMUSAGE
eq, ne, gt, lt, ge, le Memory usage in KB USERNAME
eq, ne User name in [domain\]user format SERVICES
eq, ne Service name WINDOWTITLE eq, ne
Window title MODULES
eq, ne DLL name
|
X
∆
XCopy
Copy files and folders
C:\
Command Prompt
|
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>xcopy
ping_sort.cmd c:\temp /y
C:pingsort.cmd 1 File(s) copied
C:\>_
Syntax
command XCOPY source [destination] [/A |
/M] [/D[:date]] [/P] [/S [/E]] [/V] [/W] [/C] [/I] [/Q] [/F] [/L] [/H] [/R] [/T]
[/U] [/K] [/N] [/O] [/X] [/Y] [/-Y] [/Z]
[/EXCLUDE:file1[+file2][+file3]...]
source Specifies the file(s) to copy.
destination Specifies the location or name of new files.
/A Copies
only files with the archive attribute set, doesn't change the attribute.
/M Copies only files with the archive attribute set, turns off the archive
attribute.
/D:m-d-y Copies files changed on or after the specified date.
If no date is given, copies only those files whose source time is newer than the
destination time.
/EXCLUDE:file1 [+file2][+file3]... Specifies a list of
files containing strings. When any of the strings match any part of the absolute
path of the file to be copied, that file will be excluded from being copied. For
example, specifying a string like \obj\ or .obj will exclude all files
underneath the directory obj or all files with the .obj extension respectively.
/P Prompts you before creating each destination file.
/S Copies
directories and subdirectories except empty ones.
/E Copies directories
and subdirectories, including empty ones. Same as /S /E. May be used to modify
/T.
/V Verifies each new file.
/W Prompts you to press a key
before copying.
/C Continues copying even if errors occur.
/I If
destination does not exist and copying more than one file, assumes that
destination must be a directory.
/Q Does not display file names while
copying.
/F Displays full source and destination file names while
copying.
/L Displays files that would be copied.
/H Copies
hidden and system files also.
/R Overwrites read-only files.
/T
Creates directory structure, but does not copy files. Does not include empty
directories or subdirectories. /T /E includes empty directories and
subdirectories.
/U Copies only files that already exist in destination.
/K Copies attributes. Normal Xcopy will reset read-only attributes.
/N Copies using the generated short names.
/O Copies file ownership
and ACL information.
/X Copies file audit settings (implies /O).
/Y Suppresses prompting to confirm you want to overwrite an existing
destination file.
/-Y Causes prompting to confirm you want to overwrite
an existing destination file.
/Z Copies networked files in restartable
mode.
|
∆
∆
Using Environment Variables
These are some of the common environmental
variables
type set at the command prompt to see these available environmental
variables:
ALLUSERSPROFILE=C:\Documents and Settings\All Users APPDATA=C:\Documents and
Settings\username\Application Data CLIENTNAME=Console
CommonProgramFiles=C:\Program Files\Common Files
COMPUTERNAME=YourComputerName ComSpec=C:\WINDOWS\system32\cmd.exe
FP_NO_HOST_CHECK=NO HOMEDRIVE=H: HOMEPATH=\
HOMESHARE=\\servername\sharename LDMS_LOCAL_DIR=C:\Program
Files\LANDesk\LDClient\Data LOGONSERVER=\\YourLogonServerName
NUMBER_OF_PROCESSORS=2 OS=Windows_NT Path=%CommonProgramFiles%\Microsoft
Shared\Windows Live;C:\WINDOWS\system32;C:\W
INDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\ATI Technologies\ATI.ACE\Core-S
tatic PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
PROCESSOR_ARCHITECTURE=x86 PROCESSOR_IDENTIFIER=x86 Family 6 Model 23
Stepping 10, GenuineIntel PROCESSOR_LEVEL=6 PROCESSOR_REVISION=170a
ProgramFiles=C:\Program Files PROMPT=$P$G SESSIONNAME=Console
SystemDrive=C: SystemRoot=C:\WINDOWS
TEMP=C:\DOCUME~1\username\LOCALS~1\Temp
TMP=C:\DOCUME~1\username\LOCALS~1\Temp USERDNSDOMAIN=YourFQDNDomainName
USERDOMAIN=YourDomainName USERNAME=username USERPROFILE=C:\Documents and
Settings\username
WINDIR=C:\WINDOWS
This is how you would use one of these variables in a
script
Example:
∆
Copy yourfile.dll to the system32 folder
C:\
Command Prompt |
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>copy /v /y yourfile.dll %windir%\system32
1 file(s) copied.
C:\>_ |
or
∆
Display on screen the current username
C:\
Command Prompt |
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>echo
%username%
eddiejackson
C:\>_ |
or
∆
Delete all .old files from the temp folder
C:\
Command Prompt
|
Microsoft Windows XP
[Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.
C:\>del
%temp%\*.old
C:\>_ |
![bar1](http://eddiejackson.net/web_images/lightgraybar.bmp)
Δ
Short Commands
![bar1](http://eddiejackson.net/web_images/lightgraybar.bmp)
FUNCTION |
BATCH CODE |
REMARKS |
Batch file's directory |
ECHO "%~dp0" |
Shows the batch file's
directory with trailing backslash (credits: Sean Brannery) |
Batch file's directory (SFN) |
ECHO "%~dps0" |
Shows the batch file's directory as Short File
Name (8.3 notation) |
Battery icon in notification area |
POWERCFG /GlobalPowerFlag
ON /Option: BatteryIcon |
Will even work on desktops and servers |
Beep |
@ECHO ^G |
^G is Ctrl+G (ASCII character 7) |
Count files |
DIR /A | FIND "File(s)" |
Counts the number of files in the current directory. Will show
its result like this: 47 File(s) .
Language dependent, FIND
filter shown is for English Windows versions only. |
Count files |
DIR /A-D /B | FIND /C /V "" |
Counts the number of files in the current directory. Will show
its result like this: 47 .
Language independent. |
Count files (1) |
XCOPY *
"%TEMP%" /H /L /Q /S /Y |
Counts the number of files in the current
directory. Will show its result like this:
47 File(s) . Language
independent. Credits: Andrew J. Macbeth |
Count files in subfolders |
FOR /D %%A IN (*) DO (
ECHO.%%A DIR "%%~A" /A-D /B /S | FIND /C /V "" ) |
Counts the number of files in each subdirectory. Will show its
result like this: My Pictures
47
Language independent. |
Count files in subfolders (1) |
FOR /D %%F IN (*) DO (
ECHO "%%F" XCOPY "%%F\*" "%TEMP%" /H /L /Q /S /Y ) |
Counts the number of files in each subdirectory. Will show its
result like this: "My Pictures"
47 File(s) Language independent. Credits: Andrew J.
Macbeth |
Count files in subfolders (1) |
FOR /D %%F IN (*) DO (
FOR /F %%C IN ('XCOPY "%%F\*" " %TEMP%" /H /L /Q /S /Y') DO (
ECHO.%%C File(s) %%F ) ) |
Counts the number of files in each subdirectory. Will show its
result like this:
47 File(s) My
Pictures . Language independent. Credits: Andrew J.
Macbeth |
Count files in subfolders |
FOR /D %%A IN (*) DO (
FOR /F %%B IN ('DIR "%%~A" /A-D /B /S ˆ| FIND /C /V ""') DO (
ECHO.%%B File(s) %%A ) |
Counts the number of files in each subdirectory. Will show its
result like this:
47 File(s) My
Pictures Language independent. |
Count files modified since ... (1) |
XCOPY * "%TEMP%" /H /L /S
/Q /Y /D:12-29-2005 |
Counts all files modified since December 29, 2005, in the current
directory and subdirectories. Will show its result like this:
13 File(s) Regardless of
language or international settings, the date format for
XCOPY 's
/D switch is always M-D-Y. |
Count files modified before ... (1) |
FOR /F %%A IN ('XCOPY *
"%TEMP%" /H /L /S /Q /Y /D:12-29-2005') DO ( FOR /F %%B IN
('XCOPY * "%TEMP%" /H /L /S /Q /Y') DO ( SET /A OldFiles =
%%B - %%A ) ) ECHO.%OldFiles% File(s) |
Counts all files modified before December 29, 2005, in the
current directory and subdirectories. Will show its result like this:
34 File(s) Regardless
of language or international settings, the date format for
XCOPY 's
/D switch is always M-D-Y. |
Counter |
SET /A Counter += 1 |
Increments the variable %Counter%
by 1; if %Counter% is
not defined, its starting value is 0 |
Current Directory |
CD |
Displays the current directory (without trailing backslash,
unless it is the root directory) |
Current Directory |
ECHO.%CD% |
Displays the current directory (without trailing backslash,
unless it is the root directory) |
Current Directory |
ECHO.%__CD__% |
Displays the current directory with trailing backslash
(note the double undescores before and after
CD ) |
Current Directory |
ECHO.%__CD__:~0,-1% |
Displays the current directory without trailing backslash
(note the double undescores before and after
CD ) |
Current Directory (SFN) |
FOR %%A IN ("%CD%") DO
ECHO.%%~sfA |
Displays the current directory as Short File Name (8.3 notation,
without trailing backslash, unless it is the root directory) |
Current Drive |
FOR %%A IN ("%CD%") DO
ECHO.%%~dA |
Displays the current drive letter (or
\\ for UNC paths) (Thanks
Rob Huston for pointing out the required doublequotes) |
Date |
DATE /T |
|
Date |
ECHO.%Date% |
|
Date |
FOR %%A IN (%Date:/=%) DO
SET Today=%%A |
Removes forward slashes and day of week, so the result can be used
in a file name |
Date (YYYYMMDD format) |
FOR %%A IN (%Date%) DO (
FOR /F "tokens=1-3 delims=/-" %%B in
("%%~A") DO ( SET
Today=%%D%%B%%C ) ) |
Stores current date in YYYYMMDD
format variable %Today% .
Code shown is for (US) systems with date in
MM/DD/YYYY format. Use
%%D%% C%%B for systems with
date in DD- MM-YYYY
format. (Credits: Matthew C. Miller) |
Date |
VER | DATE | FIND /V "(" |
Will also show the text "The current date is" and, depending on OS
version and regional settings, the day of the week |
Date and Time in file name |
REN *.LOG "* %Date:/= %
%Time::=.%.*" |
Will append the current date and time to all log file names,
replacing forward slashes by spaces and colons by dots |
Date and Time in file name |
SET Today=%Date: =0% SET
Today=%Today:~-4%%Date:~-7,2%%Date: ~-10,2% SET Now=%Time: =0% FOR
/F "tokens=1,2 delims=:.," %%A IN ("%Now%")
DO SET Now=%%A%%B REN
*.LOG "*_%Today%_%Now%.*" |
Will append the current date and time to all log file names, with
the date in YYYYMMDD
format and the time in HHmm
format. The code shown is for systems with the date in
DD*MM*YYYY format, change the
order of the Date substrings for other date settings. (Credits:
Ildar Shaimordanov)
|
Drive letters in use |
FSUTIL FSINFO DRIVES |
Lists all drive letters in a single line on screen; however, to
parse that line with
FOR /F you'll need
MORE /E /T0 to remove
vertical tabs or orphaned line feeds, as demonstrated in my own
DrivUsed.bat |
File size |
FOR %%A IN (filename.ext)
DO SET FileSize=%%~zA |
Will store the size of
filename.ext into variable
%FileSize% |
Hexadecimal to Decimal |
SET /A DecValue =
0x%HexString% |
Maximum value 65536 (216) |
IP Address |
FOR /F "tokens=2
delims=[]" %%A IN ('PING
%ComputerName% -n 1') DO ( SET IP=%%A ) |
Subtitute %ComputerName%
with a remote computer name to get that computer's IP address |
Jump to batch file's directory |
PUSHD "%~dp0" |
Will map a network drive if the batch file was started from a UNC
path, and then make the batch file's location the current (or working)
directory. Use POPD before closing the batch file, otherwise the
mapping will persist. (Credits: Reinhard Irnberger) |
Linefeed |
ECHO. |
Actually a carriage return/linefeed combination; displays an empty
line |
Linefeeds CR/LF |
TYPE input_filename
| MORE /E /P > output_filename |
Converts "isolated" linefeeds to carriage return/linefeed pairs |
List directories in PATH |
FOR %%A IN (%PATH%) DO
ECHO.%%A |
Will fail if directory entries contain spaces |
List files modified since ... (1) |
XCOPY * "%TEMP%" /H /L /S
/Y /D:12-29-2005 |
Will lists all files modified since December 29, 2005, in the
current directory and subdirectories. Regardless of language or
international settings, the date format for
XCOPY 's
/D switch is always M-D-Y. |
Math |
SET /A |
Integers only |
Check if a value is numeric |
FOR /F
"tokens=1
delims=0123456789" %%A IN
("%Value%") DO ( ECHO.%Value% is NOT a valid decimal,
octal or
binary number ) |
Positive numbers only, no hexadecimal. If the value is
numeric the FOR loop won't iterate, because %VALUE% will contain nothing
but delimiters. Use constructs like
SET Invalid=1 inside the loop
if you want to use the result outside the loop. |
Check if a value is numeric |
FOR /F
"tokens=1
delims= -0123456789abcdefABCDEF" %%A
IN ("%Value%") DO ( ECHO.%Value% is NOT a number ) |
All numbers, positive or negative, including hexadecimal without "x"
or "0x" prefix. "False positive" on strings like
"0FA7-A33E-7049-E444-1DEA". |
Octal to Decimal |
SET /A DecValue =
0%OctalString% |
Maximum value 65536 (216) |
Script's own startup drive |
SET MyStartupDrive=%~d0 |
|
Script's own startup folder (without drive) |
SET MyStartupFolder=%~p0 |
Double quotes may be necessary for long folder names with spaces:
"%~p0" |
Script's own startup path |
SET MyStartupPath=%~dp0 |
Double quotes may be necessary for long folder names with spaces:
"%~dp0" |
Short File Name |
FOR %%A IN ("filename.ext")
DO ECHO.%%~snxA |
Shows filename.ext 's
Short File Name (8.3 notation) |
Short File Name |
FOR %%A IN ("filename.ext")
DO ECHO.%%~sfA |
Shows filename.ext 's
fully qualified path as Short File Name (8.3 notation) |
String Substitution |
SET
NewString=%OldString:old=new% |
Substitutes "old" with "new" everywhere in the string
%OldString% ; case sensitive! |
Time |
ECHO.%Time% |
Hours, minutes, seconds and hundredths of seconds |
Time |
FOR /F "tokens=1-3
delims=:.," %%A IN ("%Time%") DO (
SET Time=%%A:%%B:%%C ) |
Hours, minutes and seconds |
Time |
TIME /T |
Hours and minutes only |
Time |
VER | TIME | FINDSTR /R
/C:"[0-9]" |
Hours, minutes, seconds and hundredths of seconds, prefixed by "The
current time is" |
Open Windows Update in Internet Explorer |
WUPDMGR |
|
Wipe an empty partition or the empty space on a partition |
> wipe.txt ECHO
AAAAAA FOR /L %%A IN (1,1,1000) DO (TYPE wipe.txt
>> wipe.txt) DEL wipe.txt |
This may take some time... |
Open .ZIP file in Explorer |
RUNDLL32.EXE
ZIPFLDR.DLL,RouteTheCall zipfile.ZIP |
Unfortunately, there seems to be no (native) command to copy files
into the .ZIP file |
![bar1](http://eddiejackson.net/web_images/lightgraybar.bmp)
∆
Control Characters
dec hex
char mnemonic
00 00
NUL ^@
01
01 SOH
^A
02
02 STX
^B
03
03 ETX
^C
04
04 EOT
^D
05
05 ENQ
^E
06 06
ACK ^F
07
07 BEL
^G
08
08 BS
^H
09
09 HT
^I
10
0A LF
^J
11
0B VT
^K
12
0C FF
^L
13
0D CR
^M
14
0E SO
^N
15
0F SI
^O
16
10 DLE
^P
17
11 DC1
^Q
18
12 DC2
^R
19
13 DC3 ^S
20
14 DC4
^T
21
15 NAK
^U
22
16 ETB
^W
23
17 SYN
^V
24
18 CAN
^X
25
19 EM
^Y
26
1A SUB
^Z
27
1B ESC
^[
28
1C FS
^\
29
1D GS
^]
30
1E RS
^^
31
1F US
^_
![bar1](http://eddiejackson.net/web_images/lightgraybar.bmp)
Scripts In Action
∆
Random Number
How to use a random number in a script
Example:
set ran=%random:~-2% if
"%ran:~1%"=="" set ran=0%ran% set /a ran=1%ran%-99 ping -n %ran% 127.0.0.1
![bar1](http://eddiejackson.net/web_images/lightgraybar.bmp)
∆
Computer Model
How to return computer model and use logic
for processing
Example:
:POLICY @REM VALIDATE MODEL
@echo off for /f "delims==" %%a in ('wmic csproduct get name ^| find /c
/i "6930"') do set /a machine=%%a if %machine% geq 1 ( GOTO POLICYA )
else ( GOTO ERROR ) Goto :POLICYF
:POLICYA echo Running on a
6930 machine Goto POLICYB
:POLICYB @REM VALIDATE WORKSTATION
BELONGS TO OWNER IF EXIST "C:\Program Files\Credant" GOTO MAINROUTE IF NOT
EXIST "C:\Program Files\Credant" GOTO POLICYF
:MAINROUTE @rem Your
code goes here EXIT /b 0
:POLICYF echo Workstation does not minimum
requirements for installation PAUSE
∆
Message Popup
Description
How to create a message popup in Shell
Example:
echo msgbox "Test message">%temp%\popup.vbs %windir%\system32\wscript.exe
%temp%\popup.vbs
![bar1](http://eddiejackson.net/web_images/lightgraybar.bmp)
∆
Cycling Through List
![bar1](http://eddiejackson.net/web_images/lightgraybar.bmp)
Description
How to cycle through a text file computer list
Example:
for /f "tokens=* delims= " %%a in
(C:\workstations.txt) do ( ping -a -n 2 -w 750 %%a | find "Reply" > nul if
errorlevel 1 (echo %%a, OFFLINE >> "%OutputFile2%" & echo %%a OFFLINE & echo %%a
>> "C:\newlist.txt" ) else ( echo %%a, ONLINE >> "%OutputFile%" & echo %%a
ONLINE ) )
Δ
Command Reference
A
|
ADDUSERS
|
ARP
|
ASSOC
|
ASSOCIAT
|
AT
|
ATTRIB
|
B
|
BOOTCFG
|
BROWSTAT
|
C
|
CACLS
|
CALL
|
CD
|
CHANGE
|
CHKDSK
|
CHKNTFS
|
CHOICE
|
CIPHER
|
CleanMgr
|
CLEARMEM
|
CLIP
|
CLS
|
CLUSTER
|
CMD
|
COMP
|
COMPACT
|
COMPRESS
|
CON2PRT
|
CONVERT
|
COPY
|
CSCcmd
|
CSVDE
|
D
|
DATE
|
DEFRAG
|
DEL
|
DELPROF
|
DELTREE
|
DevCon
|
DIR
|
DIRUSE
|
DISKCOMP
|
DISKCOPY
|
DISKPART
|
DNSSTAT
|
DOSKEY
|
DSADD
|
DSMOD
|
DSRM
|
E
|
ECHO
|
ENDLOCAL
|
ERASE
|
EXIT
|
EXPAND
|
EXTRACT
|
F
|
FC
|
FIND
|
FINDSTR
|
FOR
|
FOR
|
FORFILES
|
FORMAT
|
FREEDISK
|
FSUTIL
|
FTP
|
FTYPE
|
G
|
GLOBAL
|
GOTO
|
H
|
HELP
|
I
|
IF
|
IFMEMBER
|
IPCONFIG
|
K
|
KILL
|
L
|
LABEL
|
LOCAL
|
LOGEVENT
|
LOGOFF
|
LOGTIME
|
M
|
MAPISEND
|
MBSAcli
|
MEM
|
MD
|
MKLINK
|
MODE
|
MORE
|
MOUNTVOL
|
MOVE
|
MOVEUSER
|
MSG
|
MSIEXEC
|
MSINFO
|
MSTSC
|
MUNGE
|
MV
|
N
|
NET
|
NETDOM
|
NETSH
|
NETSVC
|
NBTSTAT
|
NETSTAT
|
NOW
|
NSLOOKUP
|
NTBACKUP
|
NTRIGHTS
|
P
|
PATH
|
PATHPING
|
PAUSE
|
PERMS
|
PERFMON
|
PING
|
POPD
|
PORTQRY
|
POWERCFG
|
PRINT
|
PRNCNFG
|
PRNMNGR
|
PROMPT
|
PsExec
|
PsFile
|
PsGetSid
|
PsInfo
|
PsKill
|
PsList
|
PsLoggedOn
|
PsLogList
|
PsPasswd
|
PsService
|
PsShutdown
|
PsSuspend
|
PUSHD
|
Q
|
QGREP
|
R
|
RASDIAL
|
RASPHONE
|
RECOVER
|
REG
|
REGEDIT
|
REGSVR32
|
REGINI
|
REM
|
REN
|
REPLACE
|
RD
|
RMTSHARE
|
ROBOCOPY
|
ROUTE
|
RUNAS
|
RUNDLL32
|
S
|
SC
|
SCHTASKS
|
SCLIST
|
SET
|
SETLOCAL
|
SETX
|
SHARE
|
SHIFT
|
SHORTCUT
|
SHOWGRPS
|
SHOWMBRS
|
SHUTDOWN
|
SLEEP
|
SLMGR
|
SOON
|
SORT
|
START
|
SU
|
SUBINACL
|
SUBST
|
SYSTEMINFO
|
T
|
TASKLIST
|
TASKKILL
|
TIME
|
TIMEOUT
|
TITLE
|
TLIST
|
TOUCH
|
TRACERT
|
TREE
|
TYPE
|
U
|
USRSTAT
|
V
|
VER
|
VERIFY
|
VOL
|
W
|
WHERE
|
WHOAMI
|
WINDIFF
|
WINMSD
|
WINMSDP
|
WMIC
|
X
|
XCACLS
|
XCOPY
|
|
∆
|
ADD OR
LIST USERS TO/FROM A CSV FILE
|
ADDRESS
RESOLUTION PROTOCOL
|
CHANGE
FILE EXTENSION ASSOCIATIONS
|
ONE STEP
FILE ASSOCIATION
|
SCHEDULE
A COMMAND TO RUN AT A LATER TIME
|
CHANGE
FILE ATTRIBUTES
|
∆
|
EDIT
WINDOWS BOOT SETTINGS
|
GET
DOMAIN, BROWSER AND PDC INFO
|
∆
|
CHANGE
FILE PERMISSIONS
|
CALL ONE
BATCH PROGRAM FROM ANOTHER
|
CHANGE
DIRECTORY - MOVE TO A SPECIFIC FOLDER
|
CHANGE
TERMINAL SERVER SESSION PROPERTIES
|
CHECK
DISK - CHECK AND REPAIR DISK PROBLEMS
|
CHECK THE
NTFS FILE SYSTEM
|
ACCEPT
KEYBOARD INPUT TO A BATCH FILE
|
ENCRYPT
OR DECRYPT FILES/FOLDERS
|
AUTOMATED
CLEANUP OF TEMP FILES, RECYCLE BIN
|
CLEAR
MEMORY LEAKS
|
COPY
STDIN TO THE WINDOWS CLIPBOARD
|
CLEAR THE
SCREEN
|
WINDOWS
CLUSTERING
|
START A
NEW CMD SHELL
|
COMPARE
THE CONTENTS OF TWO FILES OR SETS OF FILES
|
COMPRESS
FILES OR FOLDERS ON AN NTFS PARTITION
|
COMPRESS
INDIVIDUAL FILES ON AN NTFS PARTITION
|
CONNECT
OR DISCONNECT A PRINTER
|
CONVERT A
FAT DRIVE TO NTFS.
|
COPY ONE
OR MORE FILES TO ANOTHER LOCATION
|
CLIENT-SIDE CACHING (OFFLINE FILES)
|
IMPORT OR
EXPORT ACTIVE DIRECTORY DATA
|
∆
|
DISPLAY
OR SET THE DATE
|
DEFRAGMENT HARD DRIVE
|
DELETE
ONE OR MORE FILES
|
DELETE NT
USER PROFILES
|
DELETE A
FOLDER AND ALL SUBFOLDERS
|
DEVICE
MANAGER COMMAND LINE UTILITY
|
DISPLAY A
LIST OF FILES AND FOLDERS
|
DISPLAY
DISK USAGE
|
COMPARE
THE CONTENTS OF TWO FLOPPY DISKS
|
COPY THE
CONTENTS OF ONE FLOPPY DISK TO ANOTHER
|
DISK
ADMINISTRATION
|
DNS
STATISTICS
|
EDIT
COMMAND "LINE," RECALL "COMMANDS," AND CREATE MACROS
|
ADD USER
"(COMPUTER," GROUP..) TO AD DSQUERY LIST ITEMS IN AD
|
MODIFY
USER "(COMPUTER," GROUP..) IN ACTIVE DIRECTORY
|
REMOVE
ITEMS FROM ACTIVE DIRECTORY
|
∆
|
DISPLAY
MESSAGE ON SCREEN
|
END
LOCALISATION OF ENVIRONMENT CHANGES IN A BATCH FILE
|
DELETE
ONE OR MORE FILES
|
QUIT THE
CURRENT SCRIPT/ROUTINE AND SET AN ERRORLEVEL
|
UNCOMPRESS FILES
|
UNCOMPRESS CAB FILES
|
∆
|
COMPARE
TWO FILES
|
SEARCH
FOR A TEXT STRING IN A FILE
|
SEARCH
FOR STRINGS IN FILES
|
/F LOOP
COMMAND: AGAINST A SET OF FILES
|
/F LOOP
COMMAND: AGAINST THE RESULTS OF ANOTHER LOOP COMMAND:
|
BATCH
PROCESS MULTIPLE FILES
|
FORMAT A
DISK
|
CHECK
FREE DISK SPACE (IN BYTES)
|
FILE AND
VOLUME UTILITIES
|
FILE
TRANSFER PROTOCOL
|
DISPLAY
OR MODIFY FILE TYPES USED IN FILE EXTENSION ASSOCIATIONS
|
∆
|
DISPLAY
MEMBERSHIP OF GLOBAL GROUPS
|
DIRECT A
BATCH PROGRAM TO JUMP TO A LABELLED LINE
|
∆
|
ONLINE
HELP
|
∆
|
CONDITIONALLY PERFORM A COMMAND
|
IS THE
CURRENT USER IN AN NT WORKGROUP
|
CONFIGURE
IP
|
∆
|
REMOVE A
PROGRAM FROM MEMORY
|
∆
|
EDIT A
DISK LABEL
|
DISPLAY
MEMBERSHIP OF LOCAL GROUPS
|
WRITE
TEXT TO THE NT EVENT VIEWER.
|
LOG A
USER OFF
|
LOG THE
DATE AND TIME IN A FILE
|
∆
|
SEND
EMAIL FROM THE COMMAND LINE
|
BASELINE
SECURITY ANALYZER.
|
DISPLAY
MEMORY USAGE
|
CREATE
NEW FOLDERS
|
CREATE A
SYMBOLIC LINK (LINKD)
|
CONFIGURE
A SYSTEM DEVICE
|
DISPLAY
"OUTPUT," ONE SCREEN AT A TIME
|
MANAGE A
VOLUME MOUNT POINT
|
MOVE
FILES FROM ONE FOLDER TO ANOTHER
|
MOVE A
USER FROM ONE DOMAIN TO ANOTHER
|
SEND A
MESSAGE
|
MICROSOFT
WINDOWS INSTALLER
|
WINDOWS
NT DIAGNOSTICS
|
TERMINAL
SERVER CONNECTION (REMOTE DESKTOP PROTOCOL)
|
FIND AND
REPLACE TEXT WITHIN FILE(S)
|
COPY
IN-USE FILES
|
∆
|
MANAGE
NETWORK RESOURCES
|
DOMAIN
MANAGER
|
CONFIGURE
NETWORK PROTOCOLS
|
COMMAND-LINE SERVICE CONTROLLER
|
DISPLAY
NETWORKING STATISTICS (NETBIOS OVER TCP/IP)
|
DISPLAY
NETWORKING STATISTICS (TCP/IP)
|
DISPLAY
THE CURRENT DATE AND TIME
|
NAME
SERVER LOOKUP
|
BACKUP
FOLDERS TO TAPE
|
EDIT USER
ACCOUNT RIGHTS
|
∆
|
DISPLAY
OR SET A SEARCH PATH FOR EXECUTABLE FILES
|
TRACE
ROUTE PLUS NETWORK LATENCY AND PACKET LOSS
|
SUSPEND
PROCESSING OF A BATCH FILE AND DISPLAY A MESSAGE
|
SHOW
PERMISSIONS FOR A USER
|
PERFORMANCE MONITOR
|
TEST A
NETWORK CONNECTION
|
RESTORE
THE PREVIOUS VALUE OF THE CURRENT DIR SAVED BY PUSHD
|
DISPLAY
THE STATUS OF PORTS AND SERVICES
|
CONFIGURE
POWER SETTINGS
|
PRINT A
TEXT FILE
|
"DISPLAY," CONFIGURE OR RENAME A PRINTER
|
"ADD,"
"DELETE," LIST PRINTERS SET THE DEFAULT PRINTER
|
CHANGE
THE COMMAND PROMPT
|
EXECUTE
PROCESS REMOTELY
|
SHOW
FILES OPENED REMOTELY
|
DISPLAY
THE SID OF A COMPUTER OR A USER
|
LIST
INFORMATION ABOUT A SYSTEM
|
KILL
PROCESSES BY NAME OR PROCESS ID
|
LIST
DETAILED INFORMATION ABOUT PROCESSES
|
WHO'S
LOGGED ON (LOCALLY OR VIA RESOURCE SHARING)
|
EVENT LOG
RECORDS
|
CHANGE
ACCOUNT PASSWORD
|
VIEW AND
CONTROL SERVICES
|
SHUTDOWN
OR REBOOT A COMPUTER
|
SUSPEND
PROCESSES
|
SAVE AND
THEN CHANGE THE CURRENT DIRECTORY
|
∆
|
SEARCH
FILE(S) FOR LINES THAT MATCH A GIVEN PATTERN.
|
∆
|
MANAGE
RAS CONNECTIONS
|
MANAGE
RAS CONNECTIONS
|
RECOVER A
DAMAGED FILE FROM A DEFECTIVE DISK.
|
REGISTRY:
"READ," "SET," "EXPORT," DELETE KEYS AND VALUES
|
IMPORT OR
EXPORT REGISTRY SETTINGS
|
REGISTER
OR UNREGISTER A DLL
|
CHANGE
REGISTRY PERMISSIONS
|
RECORD
COMMENTS (REMARKS) IN A BATCH FILE
|
RENAME A
FILE OR FILES
|
REPLACE
OR UPDATE ONE FILE WITH ANOTHER
|
DELETE
FOLDER(S)
|
SHARE A
FOLDER OR A PRINTER
|
ROBUST
FILE AND FOLDER COPY
|
MANIPULATE NETWORK ROUTING TABLES
|
EXECUTE A
PROGRAM UNDER A DIFFERENT USER ACCOUNT
|
RUN A DLL
COMMAND (ADD/REMOVE PRINT CONNECTIONS)
|
∆
|
SERVICE
CONTROL
|
CREATE OR
EDIT SCHEDULED TASKS
|
DISPLAY
NT SERVICES
|
"DISPLAY," "SET," OR REMOVE ENVIRONMENT VARIABLES
|
CONTROL
THE VISIBILITY OF ENVIRONMENT VARIABLES
|
SET
ENVIRONMENT VARIABLES PERMANENTLY
|
LIST OR
EDIT A FILE SHARE OR PRINT SHARE
|
SHIFT THE
POSITION OF REPLACEABLE PARAMETERS IN A BATCH FILE
|
CREATE A
WINDOWS SHORTCUT (.LNK FILE)
|
LIST THE
NT WORKGROUPS A USER HAS JOINED
|
LIST THE
USERS WHO ARE MEMBERS OF A WORKGROUP
|
SHUTDOWN
THE COMPUTER
|
WAIT FOR
X SECONDS
|
SOFTWARE
LICENSING MANAGEMENT (VISTA/2008)
|
SCHEDULE
A COMMAND TO RUN IN THE NEAR FUTURE
|
SORT
INPUT
|
START A
PROGRAM OR COMMAND IN A SEPARATE WINDOW
|
SWITCH
USER
|
EDIT FILE
AND FOLDER "PERMISSIONS," OWNERSHIP AND DOMAIN
|
ASSOCIATE
A PATH WITH A DRIVE LETTER
|
LIST
SYSTEM CONFIGURATION
|
|
LIST
RUNNING APPLICATIONS AND SERVICES
|
REMOVE A
RUNNING PROCESS FROM MEMORY
|
DISPLAY
OR SET THE SYSTEM TIME
|
DELAY
PROCESSING OF A BATCH FILE
|
SET THE
WINDOW TITLE FOR A CMD.EXE SESSION
|
TASK LIST
WITH FULL PATH
|
CHANGE
FILE TIMESTAMPS
|
TRACE
ROUTE TO A REMOTE HOST
|
GRAPHICAL
DISPLAY OF FOLDER STRUCTURE
|
DISPLAY
THE CONTENTS OF A TEXT FILE
|
∆
|
LIST
DOMAIN USERNAMES AND LAST LOGIN
|
∆
|
DISPLAY
VERSION INFORMATION
|
VERIFY
THAT FILES HAVE BEEN SAVED
|
DISPLAY A
DISK LABEL
|
∆
|
LOCATE
AND DISPLAY FILES IN A DIRECTORY TREE
|
OUTPUT
THE CURRENT USERNAME AND DOMAIN
|
COMPARE
THE CONTENTS OF TWO FILES OR SETS OF FILES
|
WINDOWS
SYSTEM DIAGNOSTICS
|
WINDOWS
SYSTEM DIAGNOSTICS II
|
WMI
COMMANDS
|
∆
|
CHANGE
FILE AND FOLDER PERMISSIONS
|
COPY
FILES AND FOLDERS
|
|
Y Z
![Description: bar1](http://eddiejackson.net/web_images/lightgraybar.bmp)
∆
Script in Action
How to return
basic inventory information on a workstation
A header is used at the top of your script defining basic script info
@rem ********************************************************************
@rem Language: Shell @rem Script: client services--AUDIT_PC_EXE.CMD
@rem Purpose: To audit customer PC and upload audit to network share
@rem Created in-house to save money; savings $4000.00+
@rem Creation Date: 04/15/07
@rem Last Modified: 04/15/07
@rem Author: Eddie S. Jackson
@rem E-Mail:
MrNetTek2000@yahoo.com
@rem Usage Just execute program from customer workstation
@rem *******************************************************************
@echo off
clears screen cls
sets color bright green on black
@color 0a
sets the title in the title bar
@title=SEND AUDIT TO
\\NETWORK_UNC_HERE\_CUSTOMER_BACKUPS
defines variables
@REM **************** SET VARIABLES ************** SET PC=%computername% SET /P PC=Enter PC NAME to AUDIT (press enter for %PC%): IF EXIST "\\%PC%\C$\BOOT.INI" GOTO NEXT1 ;ERRORTRAPPING IF NOT EXIST "\\%PC%\C$\BOOT.INI" GOTO ERR ;ERRORTRAPPING
Sets default username to current unless otherwise specified using the [SET] statement
@REM GET VARIABLE FOR USERNAME :NEXT1 SET UN=%username% SET /P UN=Enter NAME of PROFILE to AUDIT (press enter for %UN%):
This copies over necessary files using [XCOPY] command
@REM **************** COPY OVER NEEDED FILES ***************
xcopy "\\NETWORK_UNC_HERE\AppData\ScriptDepo\BackupScript\Master-X-I\psgetsid.exe" "c:\windows\system32" /y xcopy "\\NETWORK_UNC_HERE\AppData\ScriptDepo\BackupScript\Master-X-I\remote.exe" "c:\windows\system32" /y xcopy "\\NETWORK_UNC_HERE\AppData\ScriptDepo\BackupScript\Master-X-I\sleep.exe" "c:\windows\system32" /y xcopy "\\NETWORK_UNC_HERE\AppData\ScriptDepo\BackupScript\Master-X-I\winaudit.exe" "c:\windows\system32" /y xcopy "\\NETWORK_UNC_HERE\AppData\ScriptDepo\BackupScript\Master-X-I\cap.exe" "c:\windows\system32" /y xcopy "\\NETWORK_UNC_HERE\AppData\ScriptDepo\BackupScript\Master-X-I\nircmd.exe" "c:\windows\system32" /y xcopy "\\NETWORK_UNC_HERE\AppData\ScriptDepo\BackupScript\Master-X-I\msg01.*" "c:\windows\system32" /y md "\\%PC%\C$\TEMP" psgetsid -accepteula
This parses the user SID and sets output to a variable using [FOR /F] and [SET]
@REM ************* GET SID : USED FOR GETTING REGISTRY SETTINGS***** :NEXT2 for /F "usebackq delims== skip=1" %%i in (`psgetsid.exe %UN%`) do set uSID=%%i rem set uSID=%uSID% IF errorlevel 1 GOTO ERR ;ERRORTRAPPING @REM *************************************************************
@REM *************** MISC TASK : MAKE DIR AND KILL TWO TASKS ******* net localgroup administrators %UN% /ADD md "\\NETWORK_UNC_HERE\_Customer_Backups\%PC%\%UN%\_AUDIT" md "\\NETWORK_UNC_HERE\_Customer_Backups\%PC%\%UN%\_AUDIT\Desktop_Icons" md "\\NETWORK_UNC_HERE\_Customer_Backups\%PC%\%UN%\_AUDIT\AU_Desktop_Icons" md "\\NETWORK_UNC_HERE\_Customer_Backups\%PC%\%UN%\_AUDIT\Start Menu" net use x: /delete /y net use x: \\NETWORK_UNC_HERE\_Customer_Backups\%PC%\%UN%\_AUDIT" taskkill /S %PC% /f /im outlook.exe taskkill /S %PC% /f /im winpage.exe @REM *************************************************************
:AUDIT
@REM ******************* AUDIT COMPUTER **************************
@REM ***** TAKES A SNAPSHOT OF "C:\" & "PROGRAM FILES" & "DESKTOP" ****** "C:\Documents and Settings\%UN%\Application Data\Microsoft\Internet Explorer\Quick Launch\Show Desktop.scf" start /MAX cap.exe /full /cursor /file="C:\temp\desktop_snapshot.jpg"; in testing sleep 1 xcopy "\\NETWORK_UNC_HERE\AppData\ScriptDepo\BackupScript\Master-X-I\open2.bat" "c:\temp" /y sleep 2 remote \\%PC% -i -s "c:\temp\open2.bat"
@REM *** RUNS WINAUDIT - YOU CAN CONFIGURE WINAUDIT TO GATHER THE INVENTORY YOU WANT ***
echo start explorer.exe "\\NETWORK_UNC_HERE\_Customer_Backups\%PC%\%UN%\_AUDIT" > c:\temp\open.bat c:\windows\system32\WinAudit.exe -i /r=soPpmidc /f=c:\temp
@REM *** GETS DIRECTORY TEXT LISTING AND PUTS IT INTO A LOG FILE ***
dir "c:\" > "c:\temp\root_directory_snapshot.log" dir "c:\program files" > "c:\temp\program_files_snapshot.log"
@REM ******** export network, printers, odbc registry settings *********
remote \\%PC% -i -s "c:\temp\open.bat" start /MIN msg01.bat remote.exe \\%PC% -i -u
DomainName\Username -p password Regedit /e "\\%PC%\C$\TEMP\printers.reg" "HKEY_USERS\%uSID%\Printers" remote.exe \\%PC% -i -u
DomainName\Username -p password Regedit /e "\\%PC%\C$\TEMP\network.reg" "HKEY_USERS\%uSID%\Network" remote.exe \\%PC% -i -u
DomainName\Username -p password Regedit /e "\\%PC%\C$\TEMP\default_printer.reg" "HKEY_USERS\%uSID%\Software\Microsoft\Windows NT\CurrentVersion\Windows" remote.exe \\%PC% -i -u
DomainName\Username -p password Regedit /e "\\%PC%\C$\TEMP\odbc.reg" "HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI"
IF EXIST "\\%PC%\C$\temp\printers.reg" GOTO EXPORT ;ERRORTRAPPING IF NOT EXIST "\\%PC%\C$\temp\printers.reg" GOTO RUNAS ;ERRORTRAPPING
:RUNAS echo. echo. ########## ########## ########## ########## echo THIS WILL WILL GET REGISTRY SETTINGS THROUGH THE RUNAS COMMAND. echo PLEASE HAVE CUSTOMER ENTER THEIR PASSWORD TO CONTINUE. echo. runas /u:DomainName\%UN% "\\NETWORK_UNC_HERE\AppData\ScriptDepo\BackupScript\Master-X-I\registry.bat"
:EXPORT
@REM ******* MOVES DATA FROM LOCAL PC TO NETWORK LOCATION ********* xcopy "\\%PC%\c$\temp\*.log" "\\NETWORK_UNC_HERE\_Customer_Backups\%PC%\%UN%\_AUDIT" /y xcopy "\\%PC%\c$\temp\%PC%.txt" "\\NETWORK_UNC_HERE\_Customer_Backups\%PC%\%UN%\_AUDIT" /y xcopy "\\%PC%\c$\temp\*.reg" "\\NETWORK_UNC_HERE\_Customer_Backups\%PC%\%UN%\_AUDIT" /y xcopy "\\%PC%\c$\temp\*.jpg" "\\NETWORK_UNC_HERE\_Customer_Backups\%PC%\%UN%\_AUDIT" /y xcopy "\\%PC%\c$\Documents and Settings\%UN%\Desktop\*.*" "\\NETWORK_UNC_HERE\_Customer_Backups\%PC%\%UN%\_AUDIT\Desktop_Icons" /s /y xcopy "\\%PC%\c$\Documents and Settings\All Users\Desktop\*.*" "\\NETWORK_UNC_HERE\_Customer_Backups\%PC%\%UN%\_AUDIT\AU_Desktop_Icons" /s /y xcopy "\\%PC%\c$\Documents and Settings\%UN%\Start Menu\*.*" "\\NETWORK_UNC_HERE\_Customer_Backups\%PC%\%UN%\_AUDIT\Start Menu" /s /y xcopy "\\%PC%\c$\Documents and Settings\All Users\Start Menu\*.*" "\\NETWORK_UNC_HERE\_Customer_Backups\%PC%\%UN%\_AUDIT\Start Menu" /s /y xcopy "\\%PC%\c$\Program Files\Belarc\Advisor\System\tmp\(%PC%).html" "\\NETWORK_UNC_HERE\_Customer_Backups\%PC%\%UN%\_AUDIT" /s /y taskkill /im nircmd.exe
:POOF taskkill /im wscript.exe net localgroup administrators %UN% /DELETE net sessions \\%PC% /delete net sessions \\NETWORK_UNC_HERE /delete net use x: /delete /y cls echo. echo Successfully Audited PC!!! nircmd infobox "Successfully Audited PC!!! " "AUDIT SUCCESS" sleep 3 goto END
:ERR net localgroup administrators %UN% /DELETE net sessions \\%PC% /delete net sessions \\NETWORK_UNC_HERE /delete net use x: /delete /y cls echo. echo PC or USER is unavailable!!!! nircmd infobox "PC or USER is unavailable!!!! " goto END
:END
|