Professional Documents
Culture Documents
Cac Lenh Trong RUN
Cac Lenh Trong RUN
Cac Lenh Trong RUN
SC Service Control
SCHTASKS Create or Edit Scheduled Tasks
SCLIST Display NT Services
ScriptIt Control GUI applications
SET Display, set, or remove environment variables
SETLOCAL Control the visibility of environment variables
SETX Set environment variables permanently
SHARE List or edit a file share or print share
SHIFT Shift the position of replaceable parameters in a
batch file
SHORTCUT Create a windows shortcut (.LNK file)
SHOWGRPS List the NT Workgroups a user has joined
SHOWMBRS List the Users who are members of a Workgroup
SHUTDOWN Shutdown the computer
SLEEP Wait for x seconds
SOON Schedule a command to run in the near future
SORT Sort input
START Start a separate window to run a specified program or
command
SU Switch User
SUBINACL Edit file and folder Permissions, Ownership and
Domain
SUBST Associate a path with a drive letter
SYSTEMINFO List system configuration
ADDUSERS.exe (Resource Kit)
ADDUSERS Automate the creation of a large number of users
Syntax
Create Users:
AddUsers /c filename [/s:x] [/?] Domain
Password_options
Dump to file:
AddUsers /d{:u} filename [/s:x] [/?] Domain
Password_options
Erase Users:
AddUsers /e filename [/s:x] [/?] Domain
Password_options
key
The (:u) is an optional switch that causes current
accounts to be written to the specified file in Unicode text
format. Choosing to dump current user accounts does not
save the account's passwords or any security information
for the accounts.
Note: Password information is not saved in a user
account dump and if you use the same file to create
accounts, all passwords of newly created accounts will be
empty. To back up security information for accounts, use
a Tape Backup.
Password_options
/p: - Set account creation options, used along with
any combination of the following:
* l - Users do not have to change passwords at next
logon.
* c - Users cannot change passwords.
* e - Passwords never expire. (implies l option)
* d - Accounts disabled.
By default, all created users are required to
change their password at logon.
Example
Create a commadelimited text file, which contains the new users to be created.
Following the Syntax as follows:
[Users]
User Name,Full name, Password, Description, HomeDrive, Homepath, Profile, Script
e.g.
[User]
jimmye,James Edward Phillip II,,,,,,
alexd,Alex Denuur,,,E:\,E:\users\alexd,,
ronj,Ron Jarook,ChangeThis,,E:\,E:\users\ronj,,
sarahs,Sarah Smith,,,,,,
u0123,Mike Olarte,,,,,,
Save the file as C:\Users.txt and execute the command
AddUsers MyDomain /c c:\Users.txt /p:e
Related Commands:
Q199878 further examples of ADDUSERS
DSADD Add user (computer, group..) in active directory
CSVDE Import and export from Active Directory.
Equivalent Linux BASH commands:
useradd Create new user accounts
ARP.exe
ARP Address Resolution Protocol
Display and modify the IPtoPhysical address translation tables used by address
resolution protocol.
Syntax
View the contents of the local ARP cache table
ARP -a [ip_addr] [-N if_addr]
Delete an entry
ARP -d ip_addr [if_addr]
Key
-a Display current ARP entries.
May include more than one network interface.
If ip_addr is specified, the IP and Physical
addresses for only the specified computer are
displayed.
-g Same as -a.
Related Commands:
ROUTE Manipulate network routing tables
Q199773 Behaviour of Gratuitous ARP
Q140859 Win NT TCP/IP Routing Basics
ASSOC
Display or change the association between a file extension and a fileType
Syntax
ASSOC .ext = [fileType]
ASSOC
ASSOC .ext
ASSOC .ext =
Key
.ext : The file extension
fileType : The type of file
A file extension is the last few characters in a FileName after the period.
So a file called JANUARY.HTML has the file extension .HTML
The File extension is used by Windows NT to determine the type of information
stored in the file and therefore which application(s) will be able to display the
information in the file. File extensions are not case sensitive and are not limited to 3
characters.
More than one file extension may be associated with the same File Type.
e.g. both the extension .JPG and the extension .JPEG may be associated with the
File Type "jpegfile"
At any one time a given file extension may only be associated with one File Type.
e.g. If you change the extension .JPG so it is associated with the File Type "txtfile"
then it's normal association with "jpegfile" will disappear. Removing the association to
"txtfile" does not restore the association to "jpegfile"
File Types can be displayed in the Windows Explorer GUI: [View, Options, File
Types] however the spelling is usually different to that expected by the ASSOC
command e.g. the File Type "txtfile" is displayed in the GUI as "Text Document"and
"jpegfile" is displayed as "image/jpeg"
The command ASSOC followed by just a file extension will display the current File
Type for that extension.
ASSOC without any parameters will display all the current file associations.
ASSOC with ".ext=" will delete the association for that file extension.
Did you leave the Always Use This Program To Open This File option turned on?
To change it back so it prompts you to specify a program each time, just delete the
association for that file type
ASSOC .ext=
[where .ext is the file extension].
Now when you doubleclick on a file of that type, the system will ask you what
program you want to use.
Using the ASSOC command will edit values stored in the registry at
HKey_Classes_Root\.<file extension>
Therefore it's possible to use registry permissions to protect a file extension and
prevent any file association changes.
Examples:
Viewing file associations:
ASSOC .txt
ASSOC .doc
ASSOC >backup.txt
Editing file associations:
ASSOC .txt=txtfile
ASSOC .DIC=txtfile
ASSOC .html=Htmlfile
Deleting a file association:
ASSOC .html=
Repair .REG and .EXE file associations:
ASSOC .EXE=exefile
ASSOC .REG=regfile
Digging through CLASSES_ROOT entries often reveals more than one shell for the
same application, for example the Apple Quick Time player has two entries, one to
"open" (which gives an annoying nag screen) and one to just "play" the QT file:
[HKEY_CLASSES_ROOT\MOVFile\shell\open] and [play]
In cases like this you can change the default action e.g.
[HKEY_CLASSES_ROOT\MOVFile\shell]
@="play"
"Of all forms of caution, caution in love is perhaps the most fatal to true happiness"
Bertrand Russell
Related:
FTYPE Edit file types (used in file extension associations)
Batch file to list the application associated with a file extension
ASSOCIAT One step file association (Resource Kit)
Q162059 Associate Internet Explorer with MS Office files
JSIFAQ Tip 9715 List File Types with executable path
ASSOCIATE.exe (Resource Kit)
One step file association.
This utility does the job of both ASSOC and FTYPE, in one step. ASSOCIATE
assigns an extension directly with an executable application. This is done by
automatically adding a new FileType to the system registry.
Syntax
ASSOCIATE .ext filename [/q /d /f]
Key
.ext : Extension to be associated.
filename : Executable program to associate .ext with.
/q : Quiet - Suppress interactive prompts.
/f : Force - Force overwrite or delete without
questions.
/d : Delete - Delete the association.
A file extension is the last few characters in a FileName after the period.
So a file called JANUARY.HTML has the file extension .HTML
The File extension is used by Windows NT to determine the type of information
stored in the file and therefore which application(s) will be able to display the
information in the file. File extensions are not case sensitive and are not limited to 3
characters.
Example: adding a File Association
To add the File Type "SQLfile"=Notepad.exe and also set the File Association of
.SQL="SQLfile" run this command:
ASSOCIATE .SQL Notepad.exe
Example: Removing a File Association
ASSOCIATE .SQL /d
Note that /d will delete the File Association but will NOT delete the File Type.
File types created by Associate.exe are always given a name in the form xxxfile,
where xxx is the file extension.
"There are three roads to ruin; women, gambling and technicians. The most pleasant
is with women, the quickest is with gambling, but the surest is with technicians"
Georges Pompidou
Related Commands:
ASSOC Change file extension associations
FTYPE Display or modify file types used in file extension associations
Equivalent Linux BASH commands:
export Set an environment variable
AT.exe
Schedule a batch file to run on a computer at a specific date and time. This
command is available for backwards compatibility with NT 4 but has been
superseded by SCHTASKS.
Syntax
Create an AT job:
AT [\\computername] hh:mm [/INTERACTIVE] [ /EVERY:day(s)
| /NEXT:day(s) ] "command"
Delete an AT job:
AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]]
Key
\\computername : Execute the AT command on a remote
computer.
Monday = m
Tuesday = t
Wednesday = w
Thursday = th
Friday = f
Saturday = s
Sunday = su
or a specific day of the month:
e.g. 5th of every month = 5
Examples:
Running a command every day
AT_DAILY.cmd
::::::::::::
AT 23:30 /EVERY:m,t,w,th,f,s,su c:\backups\every_day.cmd
::::::::::::
Running a command every Friday
AT_WEEKLY.cmd
::::::::::::
AT 23:30 /EVERY:f c:\backups\weekly.cmd
::::::::::::
Resetting the above AT commands
RESET_AT_JOBS.cmd
::::::::::::
AT /delete /yes
CALL AT_DAILY
CALL AT_WEEKLY
::::::::::::
Running a command this evening (once only)
AT_TODAY.cmd
::::::::::::
AT 23:30 /NEXT: c:\backups\today.cmd
::::::::::::
Rights needed to issue an AT command
By default only a Local Administrator can issue an AT command, a Domain Admin
can direct the command at any machine.
To configure an AT job as part of a users login script the user must be a member of
the local Administrators group.
Schedule vs Task Sheduler
The "Schedule" service must be running to use the AT command. If you have
Internet Explorer 5.0 or greater this is renamed as the "Task Scheduler" service. Task
Scheduler initially had a bad reputation due to a security vulnerability it introduced
however this was fixed with IE 5.01
The "Schedule" service (ATSVC) rather than the "Task Scheduler" service must be
running to use SOON with a delay of less than 60 seconds. see Q237840
You can use the Scheduled Tasks folder to view or modify the settings of a task that
was created by using the AT command. When you schedule a task using the at
command, the task is listed in the Scheduled Tasks folder, with a name such
as:At3478. However, if you modify an AT task through the Scheduled Tasks folder, it
is upgraded to a normal scheduled task. The task is no longer visible to the at
command, and the at account setting no longer applies to it. You must explicitly enter
a user account and password for the task.
Commands to Process
At does not automatically load Cmd.exe, the command interpreter. If you are not
running an executable (.exe) file, you must explicitly load Cmd.exe at the beginning
of the command e.g. cmd /c dir
Don't try to pass more than one command into AT, put everything you want to
achieve in one batch file and then call the batch file from AT.
User Rights needed for the AT command to perform it's task
The User Account under which the Schedule service runs may require specific file
access permissions, user permissions and drive mappings.
The User Account is selected under MyComputer, ScheduledTasks, Advanced
(Menu), AT Service Account. You also need to stop and restart the service before the
change in UserAccount will take effect.
Here's how to check if a user account has sufficent rights for a particular task:
AT hh:mm /interactive %comspec% /k
Setting hh:mm for one minute from now will open a cmd window at the specified
time. In this window you can check the following settings:
• The PATH
• Environment variables (particularly TEMP).
• Drive mappings you can add these by putting appropriate NET USE...
commands at the beginning of your batch file.
Next, go ahead and run your batch file in this console window, note the errors, and
fix them. Once the errors have been fixed, you can remove the /interactive switch
and schedule the batch file with some confidence that it will work as intended.
Bugs
If you change the system time after scheduling a command with AT, synchronize the
scheduler with the revised system time by typing AT without any commandline
options.
By default, AT jobs will stop running after 72 hours.
You can modify this in the registry.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Schedule
Add Value:
AtTaskMaxHours Data type: REG_DWORD
Decimal Value Data: 0.
A value of 0 indicates no limit, does not stop.
Values from 1 through 99 indicate the number of hours.
See Q226370 for bugs related to the Task Scheduler under NT4.
Other Task Scheduler options are stored in the registry
HKLM\SOFTWARE\Microsoft\SchedulingAgent\
"We don't wake up for less than $10,000 a day" Linda Evangelista
Related commands:
SOON Schedule a command to run in the near future
CALL Call one batch program from another.
JT Win 2000 Task Scheduler Command Line Utility
SchTasks Task Scheduler
WMIC JOB WMI access to scheduled tasks.
Scheduling Windows 2000’s Disk Defragmenter
Equivalent Linux BASH commands:
cron Daemon to execute scheduled commands
crontab Schedule a command to run at a later time
watch Execute/display a program periodically
ATTRIB.exe
Display or change file attributes. Find Filenames.
Syntax
ATTRIB [ + attribute | - attribute ] [pathname] [/S]
Key
+ : Turn an attribute ON
- : Clear an attribute OFF
attributes:
H Hidden
S System
R Read-only
A Archive
If no attributes are specified attrib will return the current attribute settings. Used with
just the /S option ATTRIB will quickly search for a particular filename.
Combining the Hidden and System attributes.
If a file has both the Hidden and System attributes set, you can clear both attributes
only with a single ATTRIB command.
For example, to clear the Hidden and System attributes for the RECORD.TXT file,
you would type:
ATTRIB S H RECORD.TXT
Using ATTRIB with groups of files
You can use wildcards (? and *) with the filename parameter to display or change the
attributes for a group of files.
Remember that, if a file has the System or Hidden attribute set, you must clear that
attribute before you can change any other attributes.
Changing the attributes for a directory
You can display or change the attributes for a directory. To use ATTRIB with a
directory, you must explicitly specify the directory name; you cannot use wildcards to
work with directories.
For example, to hide the directory C:\SECRET, you would type the following:
ATTRIB +H C:\SECRET
The following command would affect only files, not directories: ATTRIB +H C:*.*
Viewing archive attributes
The Archive attribute (A) is used to mark files that have changed since they were
previously backed up. The (A) flag is automatically updated by Windows as the file is
saved.
If the (A) flag is present the file is new or has been changed since the last backup.
The MSBACKUP, RESTORE, and XCOPY commands use these Archive attributes,
as do many (but not all) 3rd party backup solutions.
New attributes in Windows XP
In addition to A,H,R,S, the latest version of NTFS includes the following new
attributes
E = Encrypted, C = Compressed, T = Temporary, O = Offline
"The moral sense of conscience is by far the most important..
it is the most noble of all the attributes of man" Charles Darwin
Related Commands:
CACLS Change file permissions
Equivalent Linux BASH commands:
chflags Change a file or folder's flags.
chmod Change access permissions
chown Change file owner and group
BOOTCFG.exe
Edit the Windows boot settings stored in Boot.ini
Syntax
BOOTCFG /addsw Add OS load options for an OS entry in
boot.ini
Fixboot Write a new partition boot sector
Q291980 The XP Bootcfg command
Q317521 The 2003 Bootcfg command
Recovery console
BROWSTAT.exe (Resource Kit)
Get domain, browser and PDC info.
Syntax
BROWSTAT sta : Status Displays
Transport,Primary DNS
and Backup DNS servers.
The VIEW options below can enumerate all the server services
running across a server or domain:
BROWSTAT vw Transport
BROWSTAT vw Transport ‹domain›
BROWSTAT vw Transport \\Server
BROWSTAT vw Transport \\‹Server› /DOMAIN ‹DomainToQuery›
TS=TimeSource
MBC=MemberServer
PQ=PrintServer
DL=DialinServer
AFP=AFPServer
OSF=OSFServer
VMS=VMSServer
PBR=PotentialBrowser
BBR=BackupBrowser,
MBR=MasterBrowser
DMB=DomainMasterBrowser
DFS=DistributedFileSystem
A mission statement is defined as "a long awkward sentence that demonstrates
management's inability to think clearly." All good companies have one. Scott Adams
The Dilbert Principle, 1996
Related Commands:
Q188305 Troubleshooting the Browser Service
DNSSTAT DNS Statistics
NETSTAT Display networking statistics (TCP/IP)
SETPRFDC Set preferred Domain Controller
CACLS.exe
Display or modify Access Control Lists (ACLs) for files and folders.
Access Control Lists apply only to files stored on an NTFS formatted drive, each ACL
determines which users (or groups of users) can read or edit the file. When a new file
is created it normally inherits ACL's from the folder where it was created.
Syntax
CACLS pathname [options]
Key
options can be any combination of:
/G user:permission
Grant access rights, permision can be:
R Read
W Write
C Change (read/write)
F Full control
/R user
Revoke specified user's access rights (only valid with
/E).
/P user:permission
Replace access rights, permission can be:
N None
R Read
W Write
C Change (read/write)
F Full control
/D user
Deny access to user.
Wildcards can be used to specify multiple files.
You can specify more than one user:permission in a single command.
The /D option will deny access to a user even if they belong to a group that does
have access.
Using CACLS
• The CACLS command does not provide a /Y switch to automatically answer
'Y' to the Y/N prompt. However, you can pipe the 'Y' character into the CACLS
command using ECHO, use the following syntax:
• To edit a file you must have the "Change" ACL (or be the file's owner)
• To use the CACLS command and change an ACL requires "FULL Control"
• File "Ownership" will always override all ACL's you always have Full Control
over files that you create.
• If CACLS is used without the /E switch all existing rights on [pathname] will be
replaced, any attempt to use the /E switch to change a [user:permission] that
already exists will raise an error. To be sure the CALCS command will work
without errors use /E /R to remove ACL rights for the user concerned, then
use /E to add the desired rights.
• The /T option will only traverse subfolders below the current directory.
• Windows NT 4.0 does not support the Grant Write option (CACLS <Folder> /G
<UserName>:W) grant the Change permission instead.
If no options are specified CACLS will display the current ACLs
e.g. To display the current folder
CACLS .
Display permissions for one file
CACLS MyFile.txt
Display permissions for multiple files
CACLS *.txt
Inherited folder permissions are displayed as follows:
OI This folder and files. (nO Inheritance to
subfolders)
CI This folder and subfolders. (Cascade
Inherititance)
IO Inherit Only (Do not apply this ACE to the
current folder)
No output This folder only.
(OI)(CI) This folder, subfolders, and files.
(OI)(CI)(IO) Subfolders and files only.
(CI)(IO) Subfolders only.
(OI) (IO) Files only.
Errors when changing permissions
If a user or group has a permission on a file or folder and you grant a second
permission to the same user/group on the same folder, NTFS will sometimes
produce the error message "The parameter is incorrect" To fix this (or prevent it
happening) revoke the permission first (/e /r) and then reapply (/e /g)
Examples:
Add ReadOnly permission to a single file
CACLS myfile.txt /E /G "Power Users":R
Add Full Control permission to a second group of users
CACLS myfile.txt /E /G "FinanceUsers":F
Now revoke the Read permissions from the first group
CACLS myfile.txt /E /R "Power Users"
Now give the first group Fullcontrol:
CACLS myfile.txt /E /G "Power Users":F
Give the Finance group Full Control of a folder and all sub folders
CACLS c:\docs\work /E /T /C /G "FinanceUsers":F
"Whether a pretty woman grants or withholds her favours, she always likes to be
asked for them" Ovid (Ars Amatoria)
Related:
ATTRIB Display or change file attributes
AccessEnum GUI to browse a tree view of user privs
DIR /Q Display the owner for a list of files (try it for Program files)
PERMS Show permissions for a user
FIXACLS Restore default privs (Resource Kit supplement 2)
FSUTIL File System Options
NTRIGHTS Edit user account rights
SHOWACL Show file Access Control Lists (Windows 2000)
TAKEOWN Take ownership of shares
XCACLS Display or modify Access Control Lists (ACLs) for files and folders
Q237701 Cacls cannot apply security to root
Q834721 Permissions on Folder are incorrectly ordered
Q135268 How to use CACLS.EXE in a Batch File
Q245031 Error when using the | pipe symbol
NT Permissions explained
ACL utils: SuperCACLS (costs) or FileACL (free)
Equivalent Linux BASH commands:
chmod Change access permissions
chown Change file owner and group
CALL
Call one batch program from another.
Syntax
CALL [drive:][path]filename [parameters]
CALL internal_cmd
Key:
pathname The batch program to run
this can be a network (UNC) pathname
When calling a secondary batch file or subroutine, you will often want the routine to
manipulate some data, the data (usually a variable) should be passed as a
parameter
CALL OtherScript.cmd "1234"
or
CALL OtherScript.cmd %_MyVariable%
Use a label to CALL a subroutine
A label is defined by a single colon followed by a name.
CALL :s_display_result 123
ECHO Done
GOTO :eof
:s_display_result
ECHO The result is %1
GOTO :eof
When you jump to a subroutine with CALL, all statements after the label are
executed until either the end of the script is reached, or a GOTO :eof command.
At the end of the subroutine, GOTO :eof will return to the position where you used
CALL.
Example
@ECHO OFF
SETLOCAL
CALL :s_staff SMITH 100
GOTO s_last_bit
:s_staff
ECHO Name is %1
ECHO Rate is %2
GOTO :eof
:s_last_bit
ECHO The end of the script
Returning Parameters
When a subroutine contains local variables (SETLOCAL) you will need a method of
returning values, i.e. setting a variable that is passed back to the calling routine.
This is done by executing the ENDLOCAL command on the same line as a SET
statement(s)
For example
@ECHO OFF
SETLOCAL
CALL :s_calc 200 100
ECHO %_return%
GOTO :eof
:s_calc
SETLOCAL
SET _sum=0
IF %1 GTR %2 SET _sum=5
ENDLOCAL & SET _return=%_sum%
GOTO :eof
The use of SETLOCAL and ENDLOCAL is roughly equivalent to option explicit in
Visual Basic, it's use is strongly recommended.
You should also use SETLOCAL and ENDLOCAL when passing values from one
batch file to another.
Advanced usage : CALLing internal commands
As well as running a subroutine, CALL can also be used to run any internal
command (SET, ECHO etc) and cruicially will evaluate any environment variables
passed on the same line.
Each CALL does one substitution of the variables. (You can also do CALL CALL... for
multiple substitutions)
For example
@ECHO off
SETLOCAL
set pc1=frodo3
set pc2=gandalf4
set pc3=ascom5
set pc4=qwerty2
set pc5=last1
:loop
set _pc_name=pc%1
:: Evaluate the PC's name
CALL SET _pc_name=%%%_pc_name%%%
echo The pc is %_pc_name%
goto :eof
:s_next_bit
:: continue below
"My mother never saw the irony in calling me a sonofabitch." Jack Nicholson
Related commands:
CMD can be used to call a subsequent batch and ALWAYS return even if errors
occur.
GOTO jump to a label or GOTO :eof
START Start a separate window to run a specified program or command
Equivalent Linux BASH commands:
. (dot operator) Include (run) commands from another file
builtin Run a shell builtin
chroot Run a command with a different root directory
CD
Change Directory Select a Folder (and drive)
Syntax
CD [/D] [drive:][path]
CD [..]
Key
/D : change the current DRIVE in addition to changing
folder.
Examples
To change to the parent directory.
CD ..
To change to the grant-parent directory.
CD ..\..
If Command Extensions are enabled the CD command is enhanced as follows:
1)
The current directory string is converted to use the correct CASE.
So CD C:\wiNnt would actually set the current directory to C:\Winnt
2)
CD does not treat spaces as delimiters, so it is possible to CD into a subfolder name
that contains a space without surrounding the name with quotes.
For example:
cd \My folder
is the same as:
cd "\My folder"
3)
An asterisk can be used to complete a folder name
e.g. from C:\
CD pro*
will move to
C:\Program Files
CHDIR is a synonym for CD
Tab Completion
This allows changing current folder by entering part of the path and pressing TAB
C:> CD Prog [PRESS TAB]
Will go to C:\Program Files\
Tab Completion is disabled by default, it has been known to create difficulty when
using a batch script to process text files that contain TAB characters.
Tab Completion is turned on by setting the registry value shown below
REGEDIT4
[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"CompletionChar"=dword:00000009
Changing the Current drive
simply enter the drive letter followed by a colon
C:> E:
E:>
To change drive and directory at the same time, use CD with the /D switch
C:> cd /D E:\utils
E:\utils\>
"Change is the law of life. And those who look only to the past or the present are
certain to miss the future" John F. Kennedy
Related commands:
You can also change directory using the pushd command
Q156276 Cmd does not support UNC names as the current directory
JSIFaq Tip 4757 cd Folder navigation
Equivalent Linux BASH commands:
cd Change Directory
pwd Print Working Directory
CHANGE
Change Terminal Server Session properties.
Syntax
CHANGE USER /options
CHANGE LOGON /options
CHANGE PORT /options
Options:
To change .INI file mapping: (administrator rights required)
How .ini files work:
Installing an application will create a .ini file in the TS system directory.
The first time a user runs the application, the application looks in the home directory
for its .ini file. If none is found then Terminal Server will copy the .ini file from the
system directory to the users home directory.
Each user will have a unique copy of the application's .ini file in their home directory.
To learn more about what happens when the system is put into install mode run
CHANGE USER /?
The CHANGE command replaces CHGLOGON, CHGUSER, and CHGPORT from
Citrix Winframe.
"There are two ways to slide easily through life; to believe everything or to doubt
everything. Both ways save us from thinking" Alfred Korzybski
Related Commands:
Other Terminal Server commands
INSTSRV Install an NT Service
LOGOFF Log a user off
MSIEXEC Microsoft Windows Installer
Q243202 TS Session Management Tools
The Microsoft NT4 'Automated Installation Framework' (MSIF) also included a grep
like command called CHANGE.
Equivalent Linux BASH commands:
who Print all usernames currently logged in
chkdsk.exe
Check Disk check and repair disk problems
Syntax
CHKDSK [drive:][[path]filename] [/F] [/V] [/R]
[/L[:size]]
Key
[drive:] Specify the drive to check.
CHKDSK c: /F
Fixing Errors /F
If the drive is the boot partition, you will be prompted to run the check during the next
boot
To issue chkdsk on a hard drive you must be a member of the Administrators group.
If you specify the /f switch, chkdsk will show an error if open files are found on the
disk.
Chkdsk /f will lock the volume, making data unavailable until chkdsk is finished.
If you use chkdsk /f on a very large disk or a disk with a very large number of files
(millions), chkdsk may take a long time to complete. The computer will not be
available during this time, as chkdsk does not relinquish control until it is done.
Scan only (without /f switch)
If a file needs to be fixed chkdsk will alert you with a message but will not fix the
error(s).
chkdsk may report lost allocation units on the disk it will produce this report even if
the files are inuse (open). If corruption is found, consider closing all files and
repairing the disk with /F.
Running chkdsk on a data volume that is in use by another program or process may
incorrectly report errors when none are present. To avoid this, close all programs or
processes that have open handles to the volume.
As a rule, run chkdsk only on volumes that are known to be corrupt.
On computers running Windows 2003 SP1, chkdsk automatically creates a shadow
copy, so you can check volumes that are 'in use' by another program or process.
This enables an accurate report against a live file server. On earlier versions of
Windows, chkdsk would always lock the volume, making data unavailable.
Run at Bootup
Use the chkntfs or the FSUTIL dirty commands to set or query the volume's dirty bit
(indicating corruption) so that Windows runs chkdsk when the computer is restarted.
On volumes marked as "dirty," Windows automatically runs chkdsk when the
computer is restarted. Prior to Win2003 SP1, running at bootup is often the easiest
way to close all open file handles.
Event Logs
Chkdsk will log error messages in the Event Viewer System Log.
Chkdsk /f removes ACLs that are no longer used and reports this in the Event Viewer
Application Log.
Cluster (or block) Size
CHKDSK produces a report that shows the the block /cluster size
typically: "4096 bytes in each allocation unit."
When the cluster size is greater than 4 KB on an NTFS volume, none of the NTFS
compression functions are available.
Exit codes
0 No errors were found
1 Errors were found and fixed.
2 Could not check the disk, did not or could not fix errors.
Notes:
Consider the time required to run Chkdsk to repair any errors that occur. Chkdsk
times are determined by the number of files on the volume and by the number of files
in the largest folder. Chkdsk performance under Windows 2003 is around 30% faster
than previous versions.
When CHKDSK is set to run at bootup there is a delay to allow the check to be
cancelled this can be configured in the registry:
HKLM\System\CurrentControlSet\Control\Session Manager
REG_DWORD:AutoChkTimeOutData
The value is the time in seconds that you want CHKDSK to wait (0 = no delay)
default is 10 seconds.
The file system structure on the disk is corrupt and unusable.
If you have disk corruption, run the drive manufacturers diagnostics:
fujitsu | ibm | maxtor | seagate | western digital
Also: memtest.org and ubcd.sourceforge.net
Chkdsk is also available from the Recovery Console (with different parameters.)
"I either want less corruption, or more chance to participate in it" Ashleigh Brilliant
Related commands:
CHKNTFS schedule CHKDSK to run at boot time.
FSUTIL dirty query C: Is the drive dirty
Cleanmgr.exe Windows 2000 disk cleanup
Q187941 New /C and /I Switches
Q283340 Windows XP does not detect corruption
Q303079 Locate and correct NTFS problems.
Q310747 System File Checker (Sfc.exe)
Q327009 Chkdsk Finds Incorrect Security IDs
Q329394 Long Delays Occur When You Run Chkdsk.exe
Q873437 Windows 2000 incorrectly identifies security descriptors
JSIFAQ Cleaning unused security descriptors
Equivalent Linux BASH commands:
cksum Print CRC checksum and byte counts
fsck filesystem consistency check and interactive repair
CHKNTFS.exe
Check the NTFS file system with CHKDSK
Syntax
CHKNTFS drive: [...]
CHKNTFS /C drive: [...]
CHKNTFS /X drive: [...]
CHKNTFS /t[:Time]
CHKNTFS /D
Key
drive : Specifies a drive letter.
Related:
CHKDSK Check Disk check and repair disk problems
FSUTIL File and Volume utilities
BOOTCFG Edit the Boot.ini file
Q160963 ChkNTFS What you can use it for
Scheduling Windows 2000’s Disk Defragmenter
CHOICE.exe (Resource Kit)
Accept user input to a batch file.
Choice allows single keypresses to be captured from the keyboard.
Syntax
CHOICE [/C[:]choiceKeys] [/N] [/S] [/T[:]k,nn] [text]
Key
/C[:]choiceKeys : One or more keys the user can press.
Default is YN
/N : Do not display choiceKeys at end of
prompt string.
/S : case Sensitive.
/T[:]k,dd : Default the choice to k after dd seconds
text : Message string to display the choices
available
key
/C[:]choiceKeys : One or more keys the user can press.
Default is YN
/N : Do not display choiceKeys at end of
prompt string.
/CS : Case Sensitive.
/T dd : Timeout in dd seconds
/d choiceKey : Choice made on Timeout
/m text : Message string to describe the choices
available
CHOICE /C:FH /N select [F] Floppy or [H] Hard drive
IF errorlevel 2 goto s_hard
IF errorlevel 1 goto s_floppy
Note the order of the IF statements above, IF errorlevel 1 will return TRUE for an
errorlevel of 2
CHOICE can be used to set a specific %errorlevel%
for example to set the %errorlevel% to 6 :
ECHO 6| CHOICE /C:123456 /N >NUL
I saw a woman wearing a sweatshirt with "Guess" on it. I said, "Thyroid problem?"
Arnold Schwarzenegger
Related Commands:
IF Conditionally perform a command
Equivalent Linux BASH commands:
case Conditionally perform a command
select Accept keyboard input
CIPHER
Encrypt or Decrypt files and folders.
Without parameters cipher will display the encryption state of the current folder and
files.
NTFS volumes only.
Syntax:
Encrypt/Decrypt:
CIPHER [{/e | /d}] [/s:Folder] [options] [/u[/n]]
[{PathName [...]]
Remove data:
CIPHER /w:PathName
Backup Keys:
CIPHER /x[:PathName]
options:
/s:Folder
Performs the operation in the folder and all
subfolders.
PathName
A pattern, file, or folder.
/r:PathNameWithoutExtension
Generate a new recovery agent certificate and private
key, and
then write them to files with the filename
PathNameWithoutExtension.
/w:PathName
Remove data from unused portions of a volume.
PathName can indicate any directory on the desired
volume.
Cipher does not obtain an exclusive lock on the
drive.
This option can take a long time to complete and
should only be used when necessary.
/x[:PathName] PathNameWithoutExtension
Identifies the certificates and private keys used by
EFS for the
currently logged on user and backs them up to a file.
If PathName is provided, the certificate used to
encrypt the files
is backed up. Otherwise, the user's current EFS
certificate and keys
will be backed up.
The certificates and private keys are written to a
file name
PathNameWithoutExtension plus the file extension
.pfx.
Notes
It is recommended that you always encrypt both the file and the folder in which it
resides, this prevents an encrypted file from becoming decrypted when it is modified.
Cipher cannot encrypt files that are marked as readonly.
Cipher will accept multiple folder names and wildcard characters. You must separate
multiple parameters with at least one space.
Examples
List encrypted files in the reports folder are:
CIPHER c:\reports\*
Encrypt the Reports folder and all subfolders:
CIPHER /e /s:C:\reports
To back up the certificate and private key currently used to encrypt and decrypt EFS
files to a file named c:\myefsbackup.pfx, type:
CIPHER /x c:\myefsbackup
"He that would make his own liberty secure must guard even his enemy from
oppression; for if he violates this duty he establishes a precedent that will reach to
himself" Thomas Paine
Related Commands:
FSUTIL File and Volume utilities
CLEANMGR.exe
Automated cleanup of Temp files, Internet files, downloaded files, recycle bin (XP).
Syntax
CLEANMGR option
Options
/d driveletter: - Select the drive that you want Disk
Cleanup to clean.
Examples
CLEANMGR /sageset:64
CLEANMGR /sagerun:64
Options that can be chosen for cleanup:
Temporary Internet Files
Temporary Setup Files
Downloaded Program Files
Old Chkdsk Files
Recycle Bin
Temporary Files
Temporary Offline Files
Offline Files
Compress Old Files
Catalog Files for the Content Indexer
Items in bold may appear in more than one drive i.e not just in %SystemRoot%
If you want to choose the options automatically, without any user interaction then run
a registry script like this
e.g.
REGEDIT /S cleanmgr.reg
CLEANMGR /sagerun:64
Other items you may want to clear out...
Application Data
Most files in Application Data are things like browser bookmark files
best left alone.
However some applications (e.g. MS Access) leave large files in
application data which you probably don't need in a roaming profile,
these can be selectively deleted with a batch script like this.
Recent files
To clear the shortcuts for Start, Documents
cd %userprofile%\Recent
echo y| del *.*
Notice that the 'Recent' folder may contain many more shortcuts than are set to
display under Start, Documents.
Locked files (Typically IE temp files or the Offline cache)
This works on any version of NT, 2000 or XP
Close all applications
Open a command prompt
Click Start, and then Shut Down
Simultaneously press CTRL+SHIFT+ALT.
While you keep these keys pressed, click Cancel in the Shut Down
Windows dialog box.
In the command prompt window, navigate to the cache location, and
delete all files from the folder (DEL /s)
At the command prompt, type explorer, and then press ENTER.
"Then will I sprinkle clean water upon you, and ye shall be clean: from all your
filthiness, and from all your idols, will I cleanse you." Ezekiel 36:25
Related commands:
DELPROF Delete NT user profiles and/or User Profile cache
DEFRAG Defragment hard drive (XP)
Q253597 Automating Disk Cleanup in Windows
Q315246 Automating Disk Cleanup in Windows XP
Q812248 Disk Cleanup stops responding while compressing old files
Equivalent Linux BASH commands:
watch Execute/display a program periodically
CLIP.exe (Resource Kit)
Copy the result of any command to the Windows clipboard.
Syntax
command | CLIP
For Example:
DIR | CLIP
DATE /t | CLIP
"The stupid neither forgive nor forget, the naive forgive and forget, the wise forgive
but do not forget" Thomas Szasz (The second sin)
Related Commands:
cmdtools.com clip.zip copy clipboard to a file
ScriptIt Control GUI applications
SET Display, set, or remove Windows NT environment variables
Equivalent Linux BASH commands:
export Set an environment variable
xsel get and set the contents of an Xwindow selection
CMD.exe
Start a new CMD shell
Syntax
CMD [charset] [options] [My_Command]
Options
/C Carries out My_Command and then terminates
/K Carries out My_Command but remains
more below
Win2K / XP switches
The CMD switches below were first introduced with Windows 2000
/D Ignore registry AutoRun commands
HKLM | HKCU \Software\Microsoft\Command
Processor\AutoRun
/F:ON Enable auto-completion of pathnames entered at the
CMD prompt
/knetdiag /debug
/knetdiag /fix
- no /S switch
- exactly two quote characters
- no special characters between the two quote
characters,
where special is one of: &<>()@^|
- there are one or more whitespace characters between
the
the two quote characters
- the string between the two quote characters is the
name
of an executable file.
All the commands on these pages assume you are running the 32 bit command line
(cmd.exe)
CMD.exe is the NT/XP equivalent of Command.com in previous operating systems.
The older 16 bit command processor command.com is supplied to provide backward
compatibility for 16 bit DOS applications. e.g. command.com will fail to set
%errorlevel% after certain commands.
To ensure that a batch file will not run if accidentally copied to a Windows 95/98
machine you should use the extension .CMD rather than .BAT
The COMSPEC environment variable will show if you are running CMD.EXE or
command.com
Subject to licensing issues, it is possible to run the Windows 2000 or Win XP version
of CMD.EXE under NT. This is not true of all commands, e.g. any command that
involves NTFS disk access (such as cacls) should not be moved between OS
versions.
Opening CMD from Windows Explorer
You can open a new CMD prompt by choosing START, RUN, cmd, OK
Related Registry Keys:
;Allow UNC paths at command prompt
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]
"DisableUNCCheck"=dword:00000001
Previous Commands
Pressing the UP arrow will list previous commands entered at the command prompt.
Other DOSKEY function keys are loaded by default (F7, F8, F9)
Copy and Paste
QuickEdit mode allows the use of cut and paste functions at the Command Prompt.
Open Control Panel, Console and check the QuickEdit Mode box.
COPY:
With your leftmouse button, select a line of text, now rightclick anywhere in the
window to COPY. (in NT 4 there is no popup menu)
This saves the selected text to the clipboard.
PASTE:
Now rightclick again anywhere in the CMD window to PASTE the text to the
command line.
Note: moving the cursor and toggling Insert/Overwrite is also possible.
Press ESC to cancel the selection and return to editing mode.
Using CMD in a batch script
In a batch script CMD will start a new instance of CMD.exe which will appear in the
same window. The EXIT command will close the second CMD instance and return to
the previous shell.
A method of calling one Batch script from another is to run a command like
CMD /c C:\docs\myscript.cmd
The output of CMD can be redirected into a text file. Notice that where CMD /c is
used, the EXIT command is not required.
The environment Variable %CMDCMDLINE% will expand into the original command
line passed to CMD.EXE
Pausing a batch script
Execution of any batch script can be paused by pressing CTRLS
This also works for pausing a single command such as a DIR listing
Pressing any key will resume the operation.
Stopping a batch script from running
Execution of any batch script can be stopped by pressing CTRLC
If one batch file CALLs another batch file CTRLC will exit both batch scripts.
If CMD /c is used to call one batch file from another then CTRLC will cause only one
of the batch scripts to terminate. (see also EXIT)
Long Commands
Under Windows NT, the command line is limited to 256 characters.
Under Windows 2000, the command line is limited to 2046 characters.
Under Windows XP, the command line is limited to 8190 characters.
For all OS's NTFS and FAT allows pathnames of up to 260 characters.
A workaround for the limited pathname length is to prefix \\?\
for example:
\\?\C:\TEMP\Long_Directory\Long_Filename.txt
The above limits are often encountered when using long share names or drag and
dropping files onto a batch script.
Full Screen
The key combination ALT and ENTER will switch a CMD window to full screen mode.
press ALT and ENTER again to return to a normal Window.
Command Extensions
Much of the functionality of CMD.exe can be disabled this will affect all the internal
commands, Command Extensions are enabled by default. This is controlled by
setting a value in the registry: HKCU\Software\Microsoft\Command
Processor\EnableExtensions Alternatively under Win XP you can run CMD /e:on or
CMD /e:off
"Those who can command themselves, command others" Hazlitt
Related commands:
EXIT Use this to close a CMD shell and return.
CALL Call one batch program from another
START Start a separate window to run a specified program or command
DOSKEY Edit command line, recall commands
Q156276 Cmd does not support UNC names as the current directory
Equivalent Linux BASH commands:
builtin Run a shell builtin
bash run the bash shell
csh run the C shell
ksh run the Korn shell
sh run the Bourne shell
COLOR
Sets the default console foreground and background colours.
Syntax
COLOR [background][foreground]
Colour attributes are specified by 2 of the following hex digits. Each digit can be any
of the following values:
0 = Black
8 = Gray
1 = Blue
9 = Light Blue
2 = Green
A = Light Green
3 = Aqua
B = Light Aqua
4 = Red
C = Light Red
5 = Purple
D = Light Purple
6 = Yellow
E = Light Yellow
7 = White
F = Bright White
If no argument is given, COLOR restores the colour to what it was when CMD.EXE
started.
Colour values are assigned in the following order:
The DefaultColor registry value.
The CMD /T command line switch
The current colour settings when cmd was launched
The COLOR command sets ERRORLEVEL to 1 if an attempt is made to execute the
COLOR command with a foreground and background colour that are the same.
Examples:
COLOR 07, white on black is the default.
"COLOR 00" is an invalid option and will set %ERRORLEVEL% to 1 (this fails on
some early builds of NT 4 see verify for an alternative method of raising an error)
"How much more black could this be?" and the answer is "None...none more black."
Spinal Tap
Related commands:
CMD Start a new CMD shell
Equivalent Linux BASH commands:
dircolors Colour setup for `ls'
COMP.exe
Compare two files (or sets of files). Display items which do not match.
Syntax
COMP [pathname1] [pathname2] [/D] [/A] [/L] [/N=number]
[/C]
Key
pathname1 The path and filename of the first file(s)
When used with the /A option COMP is similar to the FC command but it displays the
individual characters that differ between the files rather than the whole line.
To compare files of different sizes, use /N= to compare only the first n lines (common
portion of each file.)
COMP will normally finish with a Compare more files (Y/N) prompt
to suppress this: ECHO n|COMP <options>
"Shall I compare thee to a summer's day" William Shakespeare
Related Commands:
FC Compare two files and display any LINES which do not match
Equivalent Linux BASH commands:
comm Compare two sorted files line by line
cmp Compare two files
diff Display the differences between two files
diff3 Show differences among three files
sdiff merge two files interactively
CON2PRT.exe (Zero Admin Kit)
Add a network printer to the Control Panel Printers folder, and/or Disconnect a
printer.
All commands issued using this utility will affect only the user currently logged in.
Con2prt is therefore ideal for managing NETWORK printer connections when used
in a login script.
Syntax
CON2PRT /f
CON2PRT /c \\PrintServer\PrintShare
CON2PRT /cd \\PrintServer\PrintShare
Key
/f - remove all network printer connections
/c - connect to \\PrintServer\PrintShare
/cd - connect to and set PrintShare as the default
printer
Several switches can be combined in one command line. So you can remove all
connections before adding new ones all in one command, you can only specify one
default printer.
Available for free download at:
http://www.microsoft.com/windows/zak/
Also the freeware utility AdPrintX is very similar to Con2Prt but has additional
functionality, including compatibility with Windows 9x systems. (it's also a smaller
download)
"I think you know as well as I do what the problem is, Dave. You and Dr. Poole were
planning to disconnect me. I cannot allow this to happen" HAL
Related:
PRINT Print a text file
NET VIEW to view a list of printers
NET PRINT View and Delete print jobs
PRNCNFG Display, configure or rename a printer
PRNDRVR Add, delete or list printer drivers.
PRNJOBS Pause, resume, cancel, or list print jobs
PRNMNGR Add, delete, or list printers / connections, set the default printer.
PRNPORT Create, delete, or list TCP/IP printer ports, change port configuration.
PRNQCTL Print a test page, pause or resume a printer, clear a printer queue.
RUNDLL32 Install/Remove Printers (plus advanced options)
WMIC PRINTER Set printing options through WMI
Network Printing Advice & Tips including printcon.vbs (Change print
connection)
Q189105 Add Printers with No User Interaction (Win 2000)
Q314486 Add Printers with No User Interaction (Win XP)
WSH Commands:
Add printer WshNetwork.AddPrinterConnection
Add Network printer WshNetwork.AddWindowsPrinterConnection
List printers WshNetwork.EnumPrinterConnections
Set default printer WshNetwork.SetDefaultPrinter
Equivalent Linux BASH commands:
lpc Line printer control program
lpr Off line print
lprint Print a file
lprintd Abort a print job
lprintq List the print queue
lprm Remove jobs from the print queue
COPY
Copy one or more files to another location
Syntax
COPY source destination [options]
Key
source : Pathname for the file or files to be copied.
To force the overwriting of destination files under both NT4 and Windows2000 use
the COPYCMD environment variable:
SET COPYCMD=/Y
This will turn off the prompt in Win2000 and will be ignored
by NT4 (which overwrites
by default)
Binary copies
"COPY /B ... " will copy all the files in binary mode , you can also put /B after any one
file to copy just that file in binary.
Combine files
To combine files, specify a single file for the destination, but multiple files as the
source. To specify more than one file use wildcards or list the files with a + in
between each (file1+file2+file3)
When copying multiple files in this way the first file must exist or else the copy will
fail, a workaround for this is COPY null + file1 + file2 dest1
COPY will accept UNC pathnames
Examples:
In the current folder
COPY oldfile.wp newfile.doc
Full path specified
COPY g:\department\oldfile.wp "c:\Files to Convert\newfile.doc"
Specify the drive and filename (assumes the current folder on both drives is correct)
COPY a:oldfile.wp c:newfile.doc
Specify source only (will copy the file to current folder, keeping the same filename)
COPY g:\department\oldfile.wp
Quiet copy (no feedback on screen)
COPY oldfile.wp newfile.doc >nul
"I've been going to Bible classes. They're teaching me to be more judgmental"
Flanders' wife
Related Commands:
ROBOCOPY Robust File and Folder Copy
SCOPY File Copy with Security
XCOPY Copy files and folders
MOVE Move a file from one folder to another
Mcopy Copy and create a log file (Win 2K ResKit)
Fcopy File Copy for MMQ (copy changed files & compress. (Win 2K ResKit)
Permcopy Copy share & file ACLs from one share to another. (Win 2K ResKit)
Equivalent Linux BASH commands:
cp Copy one or more files to another location
install Copy files and set attributes
CSVDE / LDIFDE (Directory Exchange)
Import or Export Active Directory data to a file. The syntax of these two commands is
identical, the difference being that one works with CSV files and one with LDIF files.
Syntax
Export to file:
CSVDE [-f FileName] [options]
LDIFDE [-f FileName] [options]
Export options
-d RootDN The root of the LDAP search (Default to
Naming Context)
-r Filter LDAP search filter (Default to
"(objectClass=*)")
-p SearchScope Search Scope (Base/OneLevel/Subtree)
-l list Attributes to look for in an LDAP search
(comma separated List)
-o list Attributes to omit from input
(comma separated list)
-g Disable Paged Search
-m Enable the SAM logic on export
-n Do not export binary values
Import options
-k Ignore 'Constraint Violation' and 'Object Already
Exists' errors.
Username/Password credentials
-a Sets the command to run using the supplied user
distinguished name
and password. For example:
"cn=yourname,dc=yourcompany,dc-com
password"
-b Sets the command to run as username domain
password. The default is
to run using the credentials of the currently
logged on user.
CSV (commaseparated value) format files can be read with MS Excel and are easily
modified with a batch script.
LDIF files (Ldap Data Interchange Format) are a crossplatform standard. This
provides a method to populate Active Directory with data from other directory
services. (e.g. Netscape NDS, Novell NDS/eDirectory, Oracle Internet Directory)
Passwords
For security reasons neither of these tools will export passwords. When you import
an account it is given a null password, if the domain has a password length policy,
then the account will be disabled (You can reenable accounts in bulk with a script)
Compatibility
CSVDE and LDIFDE are supplied with Windows 2000/2003 Server but can also be
run on Win2000 Professional and XP Professional (i.e run remotely against the
Active Directory Server.)
Examples
Export the whole domain
CSVDE f MyDomain.csv
Export all users with a particular surname:
CSVDE f MyUsers.csv r (and(objectClass=User)(sn=Surname))
Import the whole domain
CSVDE i f MyDomain.csv j C:\MyLogfile.txt
"Give me your tired, your poor,
Your huddled masses yearning to breathe free,
The wretched refuse of your teeming shore.
Send these, the homeless, tempesttossed to me,
I lift my lamp beside the golden door!"
Emma Lazarus
Related Commands:
Q271517 Ldifde fails if an attribute contains blank spaces.
Q327620 Import contacts and users with CSVDE
Q263991 How to set a user's password with Ldifde
Q276440 Backup and Restore Connection Agreements with CSVDE
Equivalent Linux BASH commands:
ldapadd Add LDAP information
DATE
Display or change the date
Syntax
In Control Panel Regional settings a short date STYLE can be set. This can be used
to change the date separator, the order (e.g. dd/mm/yyyy or mm/dd/yyyy) and the
number of characters used to display days and months.
Date Format information in the registry
The Country Code is a setting in the registry:
This can be read using REG.exe as follows
FOR /F "TOKENS=3 delims= " %%G IN ('REG QUERY
"HKEY_CURRENT_USER\Control Panel\International\iCountry"') DO
(SET _country=%%G)
The date separator is also a registry setting
This can be read using REG.exe as follows
FOR /F "TOKENS=3 delims= " %%G IN ('REG QUERY
"HKEY_CURRENT_USER\Control Panel\International\sDate"') DO SET
_date_sep=%%G
If Command Extensions are disabled DATE will not support the /T switch
"Carpe Diem Seize the day" Horace
Related Commands:
GetDate.cmd Get todays Date (any region, any OS)
datetime.vbs Get Date, Time and daylight savings
NOW Display Message with Current Date and Time
NET TIME Display the Date in US Format (mmddyy)
REG Read, Set or Delete registry keys and values
TIME Display or set the system time
TOUCH Change file timestamps
Equivalent Linux BASH commands:
cal Display a calendar
date Display or change the date
time Measure Program Resource Use
times User and system times
touch Change file timestamps
DEFRAG (Windows XP)
Defragment hard drive.
Syntax
DEFRAG <volume> [-a] [-f] [-v] [-?]
Options
volume drive letter or mount point (d: or
d:\vol\mountpoint)
-a Analyze only
-f Force defragmentation even if free space is low
-v Verbose output
Example:
DEFRAG c: f
"How can you expect to govern a country that has two hundred and fortysix kinds of
cheese?" Charles de Gaulle
Related Commands:
CleanMgr Automated cleanup of Temp files, Internet files, downloaded files, recycle
bin
DISKPART Partition manager
pagefileconfig.vbs PageFile Configuration
DEL
Delete one or more files.
Syntax
DEL [options] [/A:file_attributes] files_to_delete
Key
files_to_delete : This may be a filename, a list of files
or a Wildcard
options
/P Give a Yes/No Prompt before deleting.
/F Ignore read-only setting and delete anyway (FORCE)
/S Delete from all Subfolders (DELTREE)
/Q Quiet mode, do not give a Yes/No Prompt before
deleting.
file_attributes:
R Read-only -R NOT Read-only
S System -S NOT System
H Hidden -H NOT Hidden
A Archive -A NOT Archive
To delete HelloWorld.TXT
DEL HelloWorld.TXT
To delete "Hello Big World.TXT"
DEL "Hello Big World.TXT"
To delete all files that start with the letter A
DEL A*
To delete all files that end with the letter A
DEL *A.*
To delete all files with a .DOC extension
DEL *.DOC
To delete all read only files
DEL /a:R *
To delete all files including any that are read only
DEL /F *
Folders
If a folder name is given instead of a file, all files in the folder will be deleted, but the
folder itself will not be removed.
Temporary Files
You should clear out TEMP files on a regular basis this is best done at startup
when no applications are running. To delete all files in all subfolders of C:\temp\ but
leave the folder structure intact:
DEL /F /S /Q %TEMP%
When clearing out the TEMP directory it is not generally worthwhile removing the
subfolders too they don't use much space and constantly deleting and recreating
them can potentially increase fragmentation within the Master File Table.
Deleting a file will not prevent third party utilities from undeleting it again, however
you can turn any file into a zerobyte file to destroy the file allocation chain like this:
TYPE nul > C:\examples\MyFile.txt
DEL C:\examples\MyFile.txt
Undeletable Files
Files are sometimes created with the very long filenames or reserved names: CON,
AUX, COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, NUL
To delete these use the syntax: DEL \\.\C:\somedir\LPT1
Alternatively SUBST a drive letter to the folder containing the file.
If a file (or folder) still appears to be 'undeletable' this is often caused by the indexing
service.
Right click the file you need to delete, choose properties, advanced and untick "allow
indexing" you will then be able to delete the file.
To cure the problem permanently Control Panel, Add/Remove programs, Win
Accessories, indexing service.
Delete Locked files (Typically IE temp files or the Offline cache)
This works on any version of NT, 2000 or XP
Close all applications
Open a command prompt
Click Start, and then Shut Down
Simultaneously press CTRL+SHIFT+ALT.
While you keep these keys pressed, click Cancel in the Shut Down
Windows dialog box.
In the command prompt window, navigate to the cache location, and
delete all files from the folder (DEL /s)
At the command prompt, type explorer, and then press ENTER.
DELTREE
Previous versions of Windows had the DELTREE command that deletes all files and
sub folders.
DEL /s will delete all files
RD /s will remove all files and folders including the root folder.
:: Remove all files and subfolders but NOT the root folder
:: From tip 617 at JsiFAQ.com
@echo off
pushd %1
del /q *.*
for /f "Tokens=*" %%G in ('dir /B') do rd /s /q "%%G"
popd
Normally DEL will display a list of the files deleted, if Command Extensions are
disabled; it will instead display a list of any files it cannot find.
ERASE is a synonym for DEL
"It devoured my paper, it was a really good paper" Ellen Feiss
Related Commands:
DELPROF Delete NT user profiles
Delrp Delete a file/directory and NTFS reparse points.(Win 2K ResKit)
RD Delete folders or entire folder trees ()
CleanMgr Automated cleanup of Temp files, Internet files, downloaded files, recycle
bin
INUSE updated file replacement utility (may not preserve file permissions)
Q120716 Delete inuse files with rm
Q320081 Cannot delete a file or folder
Q159199 A file cannot be deleted (NTFS)
Delete files older than X days
How to change the Windows NT recycle bin
Equivalent Linux BASH commands:
rm Remove files
rmdir Remove folder(s)
DELPROF (Resource Kit)
Delete NT user profiles.
Syntax
DELPROF [options]
Key
/Q Quiet, no confirmation.
/C:\\computer_name
Delete profiles on a remote computer.
/D:Number_of_days
Only delete profiles that have been inactive for
'X' Number of days (or greater)
delprof /D:14
"The best way to destroy the capitalist system is to debauch the currency" John
Keynes
Related Commands:
DEL Delete one or more files
DELTREE Delete a folder and all subfolders
RD Delete folders or entire folder trees (DELTREE)
DEL
Delete one or more files.
Syntax
DEL [options] [/A:file_attributes] files_to_delete
Key
files_to_delete : This may be a filename, a list of files
or a Wildcard
options
/P Give a Yes/No Prompt before deleting.
/F Ignore read-only setting and delete anyway (FORCE)
/S Delete from all Subfolders (DELTREE)
/Q Quiet mode, do not give a Yes/No Prompt before
deleting.
file_attributes:
R Read-only -R NOT Read-only
S System -S NOT System
H Hidden -H NOT Hidden
A Archive -A NOT Archive
To delete HelloWorld.TXT
DEL HelloWorld.TXT
To delete "Hello Big World.TXT"
DEL "Hello Big World.TXT"
To delete all files that start with the letter A
DEL A*
To delete all files that end with the letter A
DEL *A.*
To delete all files with a .DOC extension
DEL *.DOC
To delete all read only files
DEL /a:R *
To delete all files including any that are read only
DEL /F *
Folders
If a folder name is given instead of a file, all files in the folder will be deleted, but the
folder itself will not be removed.
Temporary Files
You should clear out TEMP files on a regular basis this is best done at startup
when no applications are running. To delete all files in all subfolders of C:\temp\ but
leave the folder structure intact:
DEL /F /S /Q %TEMP%
When clearing out the TEMP directory it is not generally worthwhile removing the
subfolders too they don't use much space and constantly deleting and recreating
them can potentially increase fragmentation within the Master File Table.
Deleting a file will not prevent third party utilities from undeleting it again, however
you can turn any file into a zerobyte file to destroy the file allocation chain like this:
TYPE nul > C:\examples\MyFile.txt
DEL C:\examples\MyFile.txt
Undeletable Files
Files are sometimes created with the very long filenames or reserved names: CON,
AUX, COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, NUL
To delete these use the syntax: DEL \\.\C:\somedir\LPT1
Alternatively SUBST a drive letter to the folder containing the file.
If a file (or folder) still appears to be 'undeletable' this is often caused by the indexing
service.
Right click the file you need to delete, choose properties, advanced and untick "allow
indexing" you will then be able to delete the file.
To cure the problem permanently Control Panel, Add/Remove programs, Win
Accessories, indexing service.
Delete Locked files (Typically IE temp files or the Offline cache)
This works on any version of NT, 2000 or XP
Close all applications
Open a command prompt
Click Start, and then Shut Down
Simultaneously press CTRL+SHIFT+ALT.
While you keep these keys pressed, click Cancel in the Shut Down
Windows dialog box.
In the command prompt window, navigate to the cache location, and
delete all files from the folder (DEL /s)
At the command prompt, type explorer, and then press ENTER.
DELTREE
Previous versions of Windows had the DELTREE command that deletes all files and
sub folders.
DEL /s will delete all files
RD /s will remove all files and folders including the root folder.
:: Remove all files and subfolders but NOT the root folder
:: From tip 617 at JsiFAQ.com
@echo off
pushd %1
del /q *.*
for /f "Tokens=*" %%G in ('dir /B') do rd /s /q "%%G"
popd
Normally DEL will display a list of the files deleted, if Command Extensions are
disabled; it will instead display a list of any files it cannot find.
ERASE is a synonym for DEL
"It devoured my paper, it was a really good paper" Ellen Feiss
Related Commands:
DELPROF Delete NT user profiles
Delrp Delete a file/directory and NTFS reparse points.(Win 2K ResKit)
RD Delete folders or entire folder trees ()
CleanMgr Automated cleanup of Temp files, Internet files, downloaded files, recycle
bin
INUSE updated file replacement utility (may not preserve file permissions)
Q120716 Delete inuse files with rm
Q320081 Cannot delete a file or folder
Q159199 A file cannot be deleted (NTFS)
Delete files older than X days
How to change the Windows NT recycle bin
Equivalent Linux BASH commands:
rm Remove files
rmdir Remove folder(s)
On This Page
SUMMARY
MORE INFORMATION
Using DevCon
Example DevCon commands
Notes
SUMMARY
The DevCon utility is a command-line utility that acts as an alternative to Device Manager.
Using DevCon, you can enable, disable, restart, update, remove, and query individual devices or
groups of devices. DevCon also provides information that is relevant to the driver developer and
is not available in Device Manager.
You can use DevCon with Microsoft Windows 2000, Windows XP, and Windows Server 2003. You
cannot use DevCon with Windows 95, Windows 98, or Windows Millennium Edition.
Back to the top
MORE INFORMATION
DevCon is not redistributable. It is provided for use as a debugging and development tool. You
can freely modify DevCon for private use. The sample demonstrates how to use the SetupAPI and
CfgMgr32 functions together effectively to enumerate devices and perform device operations. The
following file is available for download from the Microsoft Download Center:
For more information about how to download Microsoft support files, click the following article
number to view the article in the Microsoft Knowledge Base:
119591 (http://support.microsoft.com/kb/119591/) How to obtain Microsoft support files from
online services
Microsoft scanned this file for viruses. Microsoft used the most current virus-detection software
that was available on the date that the file was posted. The file is stored on security-enhanced
servers that help prevent any unauthorized changes to the file.
Using DevCon
DevCon is a command-line utility with built-in documentation. If you run the devcon help
command, the following list of commands and descriptions appears. The devcon help command
will give more detailed help on any command. With some of these commands, you can specify a
remote target computer. These commands work if you are using the 32-bit version of DevCon on
WOW64.
Device Console Help:
devcon.exe [-r] [-m:\\<machine>] <command> [<arg>...]
-r if specified will reboot machine after command is
complete, if needed.
<machine> is name of target machine.
<command> is command to perform (see below).
<arg>... is one or more arguments if required by command.
For help on a specific command, type: devcon.exe help
<command>
classfilter Allows modification of class filters.
classes List all device setup classes.
disable Disable devices that match the
specific hardware or
instance ID.
driverfiles List driver files installed for
devices.
drivernodes Lists all the driver nodes of
devices.
enable Enable devices that match the
specific hardware or
instance ID.
find Find devices that match the specific
hardware or
instance ID.
findall Find devices including those that are
not present.
help Display this information.
hwids Lists hardware ID's of devices.
install Manually install a device.
listclass List all devices for a setup class.
reboot Reboot local machine.
remove Remove devices that match the
specific hardware or
instance ID.
rescan Scan for new hardware.
resources Lists hardware resources of devices.
restart Restart devices that match the
specific hardware or
instance ID.
stack Lists expected driver stack of
devices.
status List running status of devices.
update Manually update a device.
UpdateNI Manually update a device without user
prompt
SetHwID Adds, deletes, and changes the order
of hardware IDs of root-enumerated devices.
Lists all known PCI devices on the computer test. (By using-m, you can specify a target
computer. You must use Interprocess communication (IPC) to access the computer.)
Installs a new instance of the Microsoft loopback adaptor. This creates a new root-enumerated
device node with which you can install a "virtual device," such as the loopback adaptor. This
command also restarts the computer silently if a restart is required.
devcon classes
Lists all known setup classes. The output contains the short nonlocalized name (for example,
"USB") and the descriptive name (for example, "Universal Serial Bus controllers").
Lists files that are associated with each device in the ports setup class.
Disables all devices that have a hardware ID that ends in "MSLOOP" (including "*MSLOOP").
Lists all compatible drivers for the device ROOT\PCI_HAL\PNP0A03. This can be used to
determine why an integral device information (.inf) file was chosen, instead of a third-party .inf
file.
Enables all devices that have a hardware ID of "*MSLOOP". The single quotation mark indicates
that the hardware ID must be taken literally (in other words, the asterisk ["*"] actually is an
asterisk; it is not a wildcard character).
devcon find *
Lists device instances of all devices that are present on the local computer.
Lists all known peripheral component interconnect (PCI) devices that are on the local computer
(this command assumes that a device is PCI if it has a hardware ID that is prefixed by "PCI\").
Lists devices that are present that are a member of the ports setup class and that contain "PNP"
in their hardware ID.
Lists devices that are present that are a member of the ports setup class and that are in the
"root" branch of the enum tree (the instance ID is prefixed by "root\"). Note that you should not
make any programmatic assumption about how an instance ID is formatted. To determine root
devices, you can look at device status bits. This feature is included in DevCon to aid in
debugging.
Lists "nonpresent" devices and devices that are present for the ports class. This includes devices
that have been removed, devices that have been moved from one slot to another, and, in some
cases, devices that have been enumerated differently due to a BIOS change.
Removes all USB devices. Devices that are removed are listed with their removal status.
devcon rescan
Lists the resources that are used by all devices in the ports setup class.
Restarts the loopback adaptor ROOT\*MSLOOP\0000. The single quotation mark in the
command indicates that the instance ID must be taken literally.
devcon hwids=mouse
Lists the expected driver stack for the device. This includes device and class upper/lower filters,
and the controlling service.
Lists the status of each device present that has an instance ID that begins with "pci\".
Lists the status of a specific device instance, in this case an Advanced Configuration and Power
Interface (ACPI)-enumerated serial port.
Lists the status of the Microsoft Terminal Server or Terminal Services mouse driver.
Updates all devices that exactly match the hardware ID *pnp0501 to use the best driver in
Mydev.inf that is associated with the hardware ID *pnp0501.
Note This update forces all devices to use the driver in Mydev.inf, even if there is a better match
already on the system. This is useful when you want to install new versions of drivers during
development before you obtain a signature. The update affects only the devices that match the
specified hardware ID, and does not affect the child devices. If the specified .inf file is unsigned,
Windows may display a dialog box that prompts you to confirm whether the driver should be
installed. If a restart is required, this is reported and DevCon returns a level 1 error. If you
specify -r, this causes a restart to occur automatically if one is required.
Notes
DevCon will return an error level for use in scripts:
"0" indicates a success.
• "1" indicates that a restart is required.
"2" indicates a failure.
"3" indicates a syntax error.
If you specify -r and a restart is required, the restart occurs without
•
warning after all devices have been processed.
If you specify -m:\\computer and the command will not work for a
•
remote computer, an error is reported.
DevCon allows wildcards in instance IDs for interactive convenience.
Do not assume anything about the format of an instance ID from
•
computer to computer and from operating system version to
operating system version
DIR
Display a list of files and subfolders
Syntax
DIR [pathname(s)] [display_format] [file_attributes]
[sorted] [time] [options]
Key
[pathname] The drive, folder, and/or files to display,
this can include wildcards:
[display_format]
/P Pause after each screen of data.
/W Wide List format, sorted horizontally.
/D Wide List format, sorted by vertical
column.
[file_attributes] /A:
[time] /T: the time field to display & use for sorting
/T:C Creation
/T:A Last Access
/T:W Last Written (default)
[options]
/S include all subfolders.
/R Display alternate data streams. (Vista only)
/B Bare format (no heading information or summary).
/L use Lowercase.
/Q Display the owner of the file.
Override any preset DIRCMD switches by prefixing the switch with
For example:
DIR *.* /S
Upper and Lower Case filenames:
Filenames longer than 8 characters will always display the filename with mixed
case as entered.
Filenames shorter than 8 characters may display the filename in upper or lower
case this may vary from one client to another (registry setting)
To obtain a bare DIR format (no heading or footer info) but retain all the details, pipe
the output of DIR into FIND, this assumes that your date separator is /
DIR c:\temp\*.* | FIND "/"
FOR /f "tokens=*" %%G IN ('dir c:\temp\*.* ^| find "/"') DO
echo %%G
Normally DIR /b will return just the filename, however when displaying subfolders
with DIR /b /s the command will return a full pathname.
Checking filesize during a download (to monitor progress of a large download)
TYPE file_being_downloaded >NUL
DIR file_being_downloaded
Since TYPE won't lock the file_being_downloaded in any way, this doesn't pose a
threat to the download itself.
"There it was, hidden in alphabetical order" Rita Holt
Related commands
WHERE Locate and display files in a directory tree.
XCOPY /L List files without copying.
ROBOCOPY /L List files with specific properties
DIRUSE show size of multiple subfolders. (Resource Kit)
Freedisk.exe check free disk space. (Win 2K ResKit)
You can also get File Sizes and Date/Time from Windows 2000/XP Batch
Parameters
Use DIR to display drive status disk missing / ready / empty
Q226370 Browsing LAN directories is slow
Equivalent Linux BASH commands:
ls List information about file(s)
DIRUSE (2K Resource Kit / XP Support Tools)
Display disk usage
Syntax
DIRUSE [options] Folders...
Options
/M Display in Mb
/K Display in Kb
/B Display in bytes (default)
/, Use thousand separator when displaying sizes.
/Q:# Quota limit, mark folders that exceed the size (#) with
a "!".
set %errorlevel% to ONE if any folders are found that
exceed the specified size
Example
DIRUSE /M /q:1.5 /* e:\users
"Work is achieved by those employees who have not yet reached their level of
incompetence" Laurence J. Peter (The Peter Principle)
Related commands
DIR Display a list of files and folders
You can also list files with XCOPY /L
Freedisk.exe check free disk space. (Win 2K ResKit)
FSUTIL File and Volume utilities
Equivalent Linux BASH commands
du Disk Usage
quota Display disk usage and limits
quotacheck Scan a file system for disk usage
quotactl Set disk quotas
ulimit Limit user resources
DISKCOMP.com
Compare the content of two floppy disks.
Syntax
DISKCOMP floppy_drive1: floppy_drive2:
Key
floppy_drive is the drive letter
The two disks must be the same type,
e.g. both 1.44 Mb or both 720 K
If you specify the same drive letter for floppy_drive1 and floppy_drive2 you will be
prompted to enter each disk.
For Example:
DISKCOMP A: A:
"I don't want to sound like I'm bragging but I think I've finally managed to play the
record at the right speed John Peel
Related commands:
DISKCOPY Copy the contents of one floppy disk to another
FC Compare two files or sets of files, and display the differences between them
Equivalent Linux BASH commands:
cksum Print CRC checksum and byte counts
DISKCOPY.com
Copy the content of one floppy disk to another.
Syntax
DISKCOPY flopppy_drive1: floppy_drive2: [/V]
Key
/V Verify that the information was copied
correctly.
The two disks must be the same type,
e.g. both 1.44 Mb or both 720 K
If you specify the same drive letter for floppy_drive1 and floppy_drive2 you will be
prompted to enter each disk.
DISKCOMP A: A:
Related commands:
DISKCOMP Compare the contents of two floppy disks
FC Compare two files or sets of files, and display the differences between them
DOSKEY.exe
Recall and edit commands at the DOS prompt, and create macros. You cannot run a
Doskey macro from a batch file.
Syntax
DOSKEY [options] [macroname=[text]]
Key
macroname : A short name for the macro.
Examples:
A macro to open notepad
DOSKEY note=notepad.exe
The command
doskey /macros >macros.cmd
Will list all current macro definitions into macros.cmd, edit
this file
and place DOSKEY at the start of each line.
"No man steps in the same river twice, for it's not the same river, and he's not the
same man." Heraclitus
Related commands:
The ScriptIt Utility can supply keystrokes to control almost any Windows Application.
Equivalent Linux BASH commands:
m4 Macro processor
history Command history
DSADD.exe (Windows XP)
Add active directory object.
Syntax
DSADD computer Computer_DN options
DSADD contact ContactDN options
DSADD group GroupDN options
DSADD ou OU_DN organizational_unit_options
DSADD user User_DN user_options
Key
DN=Distinguished Name(s)
OU=Organisational Unit
Pretty much all the attributes can be modified (Name, display
name, tel number etc)
run the command with /? for a full list
e.g
DSADD USER /?
Commas
Commas must be escaped with the backslash \ character
(other than separators in distinguished names)
e.g.
"CN=Company\, Inc.,CN=Users,DC=ss64,DC=com"
Backslashes
Backslashes used in distinguished names must be escaped with a backslash
(for example,
"CN=Sales\\ Latin America,OU=Distribution Lists,DC=ss64,DC=com").
If any value contains spaces, use quotation marks:
"CN=John Smith,CN=Users,DC=SS64,DC=com"
Special Tokens
The token $username$ (case insensitive) may be used to place the SAM account
name.
Entering * as a password will cause DSADD to prompt for the new password.
Adding multiple Objects
For any DS command you can enter multiple values separated by spaces.
e.g. to add several user accounts at once just supply a list of the distinguished
names separated with spaces.
It is also possible to store multiple values in a text file and redirect into DSADD.
"For a list of all the ways technology has failed to improve the quality of life, press
three". Alice Kahn
Related commands:
dsmod modify object
dsget display object
dsmove move object
dsquery find object
dsrm delete object
CSVDE Import or export AD info in CSV format.
LDIFDE Edit AD Objects, extend schema, import or export AD information.
Equivalent Linux BASH commands:
ldapmodify Modify Lightweight Directory Access Protocol
DSMOD.exe (Windows XP)
Modify active directory object.
Syntax
DSMOD computer Computer_DN options
DSMOD contact ContactDN options
DSMOD group GroupDN options
DSMOD ou OU_DN Organizational_unit_options
DSMOD server ServerDN Domain_controller_options
DSMOD user User_DN User_options
DSMOD quota QuotaDN Quota_options
DSMOD partition PartitionDN Partition_options
Key
DN=Distinguished Name(s)
OU=Organisational Unit
Pretty much all the attributes can be modified (Name, display
name, tel number etc)
run the command with /? for a full list
e.g
DSMOD USER /?
Commas
Commas must be escaped with the backslash \ character
(other than separators in distinguished names)
e.g.
"CN=Company\, Inc.,CN=Users,DC=ss64,DC=com"
Backslashes
Backslashes used in distinguished names must be escaped with a backslash
(for example,
"CN=Sales\\ Latin America,OU=Distribution Lists,DC=ss64,DC=com").
Redirection
You can pipe results from DSQUERY into DSMOD in order to modify an object.
e.g. To find all users in the Marketing OU (organizational unit) and add them to the
Sales group:
DSQUERY user –startnode "ou=Marketing,dc=SS64,dc=com" | DSMOD
group "cn=Sales,ou=Marketing,dc=SS64,dc=com" -addmbr
Spaces
If any value contains spaces, use quotation marks:
"CN=John Smith,CN=Users,DC=SS64,DC=com"
Special Tokens
The token $username$ (case insensitive) may be used to place the SAM account
name.
Entering * as a password will cause DSMOD to prompt for the new password.
For any DS command you can enter multiple values separated by spaces.
e.g. to modify several user accounts at once just supply a list of the distinguished
names separated with spaces.
"For a list of all the ways technology has failed to improve the quality of life, press
three". Alice Kahn
Related commands:
dsadd add object
dsget display object
dsmove move object
dsquery find object
dsrm delete object
CSVDE Import or export AD info in CSV format.
LDIFDE Edit AD Objects, extend schema, import or export AD information.
Equivalent Linux BASH commands:
ldapmodify Modify Lightweight Directory Access Protocol
ECHO
Display messages on screen, turn commandechoing on or off.
Syntax
ECHO [ON | OFF]
ECHO [message]
Key
ON : Display each line of the batch on screen
(default)
OFF : Only display the command output on screen
message : a string of characters to display
Type ECHO without parameters to display the current echo setting (ON or OFF).
In most batch files you will want ECHO OFF, turning it ON can be useful when
debugging a problematic batch script.
In a batch file, the @ symbol is the same as ECHO OFF applied to the current line
only.
Normally a command is executed and takes effect from the next line onwards, @ is a
rare example of a command that takes effect immediately.
Command characters will normally take precedence over the ECHO statement
e.g. The redirection and pipe characters: & < > | ON OFF
To override this behaviour you can escape each command character with ^ as
follows:
ECHO Nice ^&Easy
ECHO Salary is ^> Commision
ECHO Name ^| Username ^| Expiry Date
ECHO:Off On Holiday
Echo a Variable
To display a department variable:
ECHO %_department%
If the variable does not exist ECHO will simply return the text "%_department%"
This can be extended to search and replace parts of a variable or display substrings
of a variable.
You can also redirect the echoed output from the screen into a file
Echo a file
see the TYPE command for this
Echo a sound
The following command in a batch file will trigger the default beep on most PC's
ECHO
Use CtrlG (or 'Alt' key, and 7 on the numeric keypad) to get this character (ascii 7)
Alternatively where a sound card is available:
START/min sndrec32 /play /close %windir%\media\ding.wav
or
START/min mplay32 /play /close %windir%\media\ding.wav
Echo a blank line
The following command in a batch file will produce an empty line
ECHO.
To ECHO text without including a CRLF see this discussion
Echo text into a stream
Streams allow one file to contain several separate forks of information (like the
macintosh resource fork)
The general syntax is
Echo Text_String > FileName:StreamName
Only the following commands support the File:Stream syntax ECHO, MORE, FOR
Creating streams:
Echo This is stream1 > myfile.dat:stream1
Echo This is stream2 > myfile.dat:stream2
Displaying streams:
More < myfile.dat:stream1
More < myfile.dat:stream2
SET Create and display environment variables
TYPE Display the contents of a text file
List Text Display and Search Tool (Win 2K ResKit)
Batch file to echo giant size characters BigText.cmd
NET SEND %COMPUTERNAME%
Q177795 Large vs Small fonts
Equivalent Linux BASH commands:
echo Display message on screen
ENDLOCAL
End localisation of environment changes in a batch file.
Syntax
ENDLOCAL
Any changes made to an Environment Variable after ENDLOCAL has been issued
will be persistent they will still remain in memory after the batch file has terminated
and any previous value stored in that Environment Variable will not be restored.
Ending the cmd.exe session will delete all Environment Variables created with the
SET command.
For example:
@ECHO off
SETLOCAL
SET _filename=c:\test.txt
SETLOCAL
SET _filename=H:\UserManual.doc
ENDLOCAL
ECHO %_filename% - this will ECHO the value "c:\test.txt"
If SETLOCAL is used without a corresponding ENDLOCAL then localisation of
environment changes will end when the batch file ends
Passing variables from one routine to another
When "&" is used to put several commands on one line, the command processor will
convert all the %variables% into their text values before executing any of the
commands.
By putting ENDLOCAL and SET commands on one line you are able to SET a
variable outside the SETLOCALENDLOCAL block that refers to a variable created
inside the block.
For Example:
@ECHO OFF
SETLOCAL
SET _file=%1
ENDLOCAL & SET _ret1=%_file%& SET _ret2=450
You can use several "&" characters in order to SET several variables
"A good place to visit, but a poor place to stay" Josh Billings
Related Commands:
SETLOCAL Begin localisation of environment variables in a batch file.
Equivalent Linux BASH commands:
readonly Mark variables/functions as readonly
EXIT
Quit CMD.EXE or the current batch script.
The options below are only available in Windows XP (or later).
Syntax
EXIT [/B] [exitCode]
Key
/B When used in a batch script it will exit the
current batch script instead of CMD.EXE.
If executed from outside a batch script, it
will still quit CMD.EXE
COLOR Set an errorlevel (without exiting)
KILL Remove a program from memory
Equivalent Linux BASH commands:
break Exit from a loop
EXPAND
Uncompress one or more compressed files.
Syntax
EXPAND Source Destination
EXPAND -r Source Destination
EXPAND -r Source
Options
ATTRIB Display or change file attributes
COPY Copy one or more files to another location
Equivalent Linux BASH commands:
gzip Compress or decompress named file(s)
EXPAND
Uncompress one or more compressed files.
Syntax
EXTRACT [options] CAB_file [filenames]
Key
CAB_file : Cabinet file
options
/A Process ALL cabinets. (where CABs are linked)
ATTRIB Display or change file attributes
COPY Copy one or more files to another location
Equivalent Linux BASH commands:
gzip Compress or decompress named file(s)
FC.exe
Compare the contents of two files or sets of files. Display any lines which do NOT
match.
Syntax
FC /B pathname1 pathname2
Key
/B : Perform a binary comparison.
options
/C : Do a case insensitive string comparison
/LBn: Limit the number of lines that will be read, "n" sets
a maximum number
of mismatches after which the File Comparison will
abort (resync failed)
When FC aborts (resync failed) then "n" number of
mismatches will be shown.
To identify 2 identical files use this syntax:
FC file1.txt file2.txt | FIND "FC: no dif" > nul
IF ERRORLEVEL 1 goto :s_files_are_different
Example:
If two files are compared and the four lines of text match as follows
1: different
2: same
3: same
4: different
Specifying /nnnn =2 the file compare will display the 4th line and continue
Specifying /nnnn =3 the file compare will halt at the 4th line (files too different)
Specifying /LB1 the file compare will halt after the first line
# Oh lord won't you buy me a Mercedes Benz, my friends all drive Porsches, I must
make amends # Janice Joplin
Related Commands:
COMP Compare two files and display any characters which do NOT match
FIND Search for a text string in a file
FINDSTR Search for strings in files
WinDiff GUI to compare files
Equivalent Linux BASH commands:
comm Compare two sorted files line by line
cmp Compare two files
diff Display the differences between two files
diff3 Show differences among three files
sdiff merge two files interactively
FDISK
The FDisk utility is no longer supplied with recent Windows operating systems.
To reset disk partition information boot using the install CD and choose the
install/repair option.
To do a Hard Disk reformat completely outside of Windows you can use FDISK from
Windows 95, 98 or ME see Q255867
Alternatively there are many third party formatting utils such as GDISK that will do
the same thing.
For more advice and other links look at FDISK.com
Related Commands:
MSINFO Windows NT diagnostics
FORMAT Format a disk
FSUTIL File and Volume utilities
Dmdiag Display disk properties: Size, Status, Type...(Win 2K ResKit)
DiskMap Document disk structures, such as the master boot record (Win 2K
ResKit)
Equivalent Linux BASH commands:
fdisk Partition table manipulator for Linux
FIND
Search for a text string in a file & display all the lines where it is found.
Syntax
FIND [/V] [/C] [/N] [/I] "string" [pathname(s)]
key
/V : Display all lines NOT containing the specified
string.
Examples:
If names.txt contains the following:
Joe Bloggs, 123 Main St, Dunoon
Arnold Jones, 127 Scotland Street, Edinburgh
To search for "Jones" in names.txt
FIND "Jones" names.txt
---------- NAMES.TXT
Arnold Jones, 127 Scotland Street, Edinburgh
If you want to pipe a command into FIND use this syntax
TYPE names.txt | FIND "Jones"
You can also redirect like this
FIND /i "Jones" < names.txt >logfile.txt
To search a folder for files that contain a given search string
FOR %G IN (*.txt) do (find /n /i "SearchWord" "%G")
Searching from Windows Explorer
Because the builtin Windows File Search is broken you may want to add a find script
to the Send To folder. Alternatively Agent Ransack or other search utilities will do the
job properly.
Bugs/Limitations
Although FIND can be used to scan large files, it will not detect any string that is
positioned more than 1070 characters along a single line (with no carriage return)
This makes it of limited use in searching binary or XML file types.
"Instead of getting married again, I'm going to find a woman I don't like and just give
her a house." Lewis Grizzard
Related Commands:
FC Compare files
FINDSTR Search for strings in files
MUNGE Find and Replace text within file(s)
ATTRIB Find filename (rather than searching the file contents)
Equivalent Linux BASH commands:
grep Search file(s) for lines that match a given pattern
gawk Find and Replace text within file(s)
tr Translate, squeeze, and/or delete characters
FINDSTR
Search for strings in files.
Syntax
FINDSTR [options] [/F:file] [/C:string] [/G:file]
[string(s)] [pathname(s)]
Key
string Text to search for.
pathname(s) The file(s) to search.
/C:string Use string as a literal search string.
/G:file Get search string from a file (/ stands for
console).
/F:file Get a list of pathname(s) from a file (/ stands
for console).
/d dirlist Search a comma-delimited list of directories.
/I Case-insensitive search.
/S Search subfolders.
/P Skip any file that contains non-printable characters
The FINDSTR syntax notation can use the following metacharacters which have
special meaning either as an operator or delimiter.
. Wildcard: any character
Examples:
FINDSTR "granny Smith" MyFile.txt
searches for "granny" OR "Smith" in MyFile.txt.
FINDSTR /C:"granny Smith" MyFile.txt
searches for "granny Smith" in MyFile.txt
This is effectively the same as the FIND command
To search every file in the current folder and all subfolders for the word "Smith",
regardless of upper/lower case use:
FINDSTR /s /i smith *.*
Note that /S will only search below the current directory
To find every line containing the word SMITH, preceeded by any number of spaces,
and to prefix each line found with a consecutive number:
FINDSTR /b /n /c:" *smith" MyFile.txt
Finding a string only if surrounded by the standard delimiters
To find the word "computer", but not the words "supercomputer" or "computerise":
FINDSTR "\<computer\>" MyFile.txt
Now assume you want to find not only the word "computer", but also any other words
that begin with the letters comp, such as "computerise" or "compete"
FINDSTR "\<comp.*" MyFile.txt
Example of a literal search
Searching a text file that contains the following
the quick brown fox
the darkbrown fox
the really *brown* fox
FINDSTR /r .*brown MyFile.txt
or
FINDSTR .*brown MyFile.txt
Will both match the word "brown" in all 3 lines
FINDSTR /L *brown* MyFile.txt
Will only match the last string
Using a script file
Multiple search criteria can be specified with a script file /G.
Multiple files to search can be specified with a source file /F.
When preparing a source or script file, place each item on a new line.
For example: to use the search criteria in CRIT.TXT and
search the files listed in FILES.TXT then
store the results in the file RESULTS.OUT, type
FINDSTR /g:CRIT.TXT /f:FILES.TXT > results.out
Errorlevel
When an item is not found FINDSTR will return an errorlevel >0
Echo 12G6 |FindStr /R "[0-9]"
If %ERRORLEVEL% EQU 0 echo The string contains one or more
numeric characters
Echo 12G6 |FindStr /R "[^0-9]"
If %ERRORLEVEL% EQU 0 echo The string contains one or more non
numeric characters
Bugs
In early versions of FindStr /F:file a path length of more than 80 chars will be
truncated.
"Twenty years from now, you will be more disappointed by the things you didn't do
than by the ones you did do. So throw off the bowlines, sail away from the safe
harbour. Catch the trade winds in your sails. Explore. Dream. Discover." Mark Twain
Related Commands
FIND Search for a text string in a file.
MUNGE Find and Replace text within file(s)
Equivalent Linux BASH commands:
grep Search file(s) for lines that match a given pattern
gawk Find and Replace text within file(s)
tr Translate, squeeze, and/or delete characters
FOR /F
Loop command: against a set of files conditionally perform a command against
each item.
Syntax
FOR /F ["options"] %%parameter IN (filenameset) DO
command
Key
options:
delims=xxx The delimiter character(s) (default = a
space)
By default, /F breaks up the line at each blank space, and any blank lines are
skipped.
You can override this default parsing behavior by specifying the "options" parameter.
The options must be contained within "quotes"
Within a FOR loop the visibility of FOR variables is controlled via SETLOCAL
EnableDelayedExpansion
The ` backquote character is just below the ESC key on most keyboards, the
usebackq option is not available in NT4 or earlier.
Tokens
tokens=2,4,6 will cause the second, fourth and sixth items on each line to be
processed
tokens=26 will cause the second, third, fourth, fifth and sixth items on each line to
be processed
tokens=* will cause all items on each line to be processed
tokens=3* will cause the 3rd and all subsequent items on each line to be processed
Specifying more than 1 token will cause additional parameter names to be allocated.
If the last character in the tokens= string is an asterisk, then additional parameters
are allocated for all the remaining text on the line.
Delims
Specifying more than one delimiter has been known to cause problems with some
data sets, if you have problems try parsing with just one delimiter at a time. When
more than one delimiter is specified it's an OR, i.e either delimiter will work. If you
don't specify anything it will default to "delims=<tab><space>"
When editing a CMD script notice that many text editors will fail to enter the TAB
character correctly.
You can use any character as a delimiter but they are case sensitive.
Examples
Parse the output of a command:
FOR /F %%G IN ('"C:\program Files\command.exe"') DO ECHO %%G
Parse the contents of a file:
FOR /F "usebackq tokens=1,2* delims=," %%G IN ("C:\My
Documents\my textfile.txt") DO ECHO %%G
This will split each line into tokens delimited by a comma, ignoring lines that begin
with a semicolon, as shown below.
"12-AUG-
DEPOSIT "450" "23,55"
99"
* = All the
token1 token3
rest
%%G %%H %%I
%%G is explicitly declared in the FOR statement and the %%H and %%I are
implicitly declared via the tokens= option. You can specify up to 26 tokens via the
tokens= line, provided this does not cause an attempt to declare a parameter higher
than the letter 'Z'.
FOR parameter names are global, so in complex scripts which call one FOR
statement from within another FOR statement you can refer to both sets of
parameters. You cannot have more than 26 parameters active at any one time.
Parse a text string:
A string of text will be treated just like a single line of input from a file, the string must
be enclosed in double quotes (or single quotes with usebackq).
Echo the dollar amount and the date
FOR /F "tokens=1,3* delims=," %%G IN ("12-AUG-
99,deposit,$45.50,23.7") DO @echo %%H was paid on %%G
Filenameset
To specify an exact set of files to be processed, such as all .MP3 files in a folder
including subfolders and sorted by date just use the DIR /b command to create the
list of filenames ~ and use this variant of the FOR command syntax.
Unicode
Many of the newer commands and utilities (e.g. WMIC) output text files in unicode
format, these cannot be read by the FOR command which expects ASCII.
To convert the file format use the TYPE command.
"It's completely intuitive; it just takes a few days to learn, but then it's completely
intuitive" Terry Pratchett.
Related Commands:
FOR Loop commands
FOR Loop through a set of files in one folder
FOR /R Loop through files (recurse subfolders)
FOR /D Loop through several folders
FOR /L Loop through a range of numbers
FOR /F Loop through the output of a command
FORFILES Batch process multiple files
IF Conditionally perform a command
SETLOCAL Control the visibility of environment variables inside a loop
Equivalent Linux BASH commands:
cut Divide a file into several columns
case Conditionally perform a command
eval Evaluate several commands/arguments
for Expand words, and execute commands
until Execute commands (until error)
while Execute commands
FOR /F
Loop command: against the results of another command.
Syntax
FOR /F ["options"] %%parameter IN ('command_to_process')
DO command
Key
options:
delims=xxx - The delimiter character(s)
(default = a space)
skip=n - A number of lines to skip at the
beginning.
(default = 0)
By default, /F breaks up the command output at each blank space, and any blank
lines are skipped.
You can override this default parsing behavior by specifying the "options" parameter.
The options must be contained within "quotes"
Tokens
tokens=2,4,6 will cause the second, fourth and sixth items on each line to be
processed
tokens=26 will cause the second, third, fourth, fifth and sixth items on each line to
be processed
tokens=* will cause all items on each line to be processed
tokens=3* will cause the 3rd and all subsequent items on each line to be processed
Each token specified will cause a corresponding parameter letter to be allocated.
If the last character in the tokens= string is an asterisk, then additional parameters
are allocated for all the remaining text on the line.
Delims
Specifying more than one delimiter has been known to cause problems with some
data sets, if you have problems try parsing with just one delimiter at a time, or
change the order in which they are listed.
You can use any character as a delimiter but they are case sensitive.
Examples:
To ECHO from the command line, the name of every environment variable.
FOR /F "delims==" %G IN ('SET') DO @Echo %G
The same command with usebackq (Windows 2000 and above)
FOR /F "usebackq delims==" %G IN (`SET`) DO @Echo %G
To put the Windows Version into an environment variable
@echo off
::parse the VER command
FOR /F "tokens=4*" %%G IN ('ver') DO SET _version=%%G
:: show the result
echo %_version%
List all the text files in a folder
FOR /F "tokens=*" %%G IN ('dir /b C:\docs\*.txt') DO echo
%%G
Although the above is a trivial example, being able to set %%G equal to each long
filename in turn could allow much more complex processing to be done.
More examples can be found on the Syntax / Batch Files pages
"History never repeats itself, Mankind always does" Voltaire
Related Commands:
FOR Summary of FOR Loop commands
FOR Loop through a set of files in one folder
FOR /R Loop through files (recurse subfolders)
FOR /D Loop through several folders
FOR /L Loop through a range of numbers
FOR /F Loop through items in a text file
SETLOCAL Control the visibility of variables inside a FOR loop
FORFILES Batch process multiple files
GOTO Direct a batch program to jump to a labelled line
IF Conditionally perform a command
Equivalent Linux BASH commands:
for Expand words, and execute commands
case Conditionally perform a command
gawk Find and Replace text within file(s)
m4 Macro processor
until Execute commands (until error)
while Execute commands
FOR
Conditionally perform a command several times.
syntax-FOR-Files
FOR %%parameter IN (set) DO command
syntax-FOR-Files-Rooted at Path
FOR /R [[drive:]path] %%parameter IN (set) DO command
syntax-FOR-Folders
FOR /D %%parameter IN (folder_set) DO command
syntax-FOR-List of numbers
FOR /L %%parameter IN (start,step,end) DO command
syntax-FOR-File contents
FOR /F ["options"] %%parameter IN (filenameset) DO
command
syntax-FOR-Command Results
FOR /F ["options"] %%parameter IN ('command to process')
DO command
The operation of the FOR command can be summarised as...
• Take a set of data
• Make a FOR Parameter %%G equal to some part of that data
• Perform a command (optionally using the parameter as part of the command).
• Repeat for each item of data
If you are using the FOR command at the command line rather than in a batch
program, specify %parameter instead of %%parameter.
FOR Parameters
The first parameter has to be defined using a single character, I tend to use the letter
G.
e.g. FOR %%G IN ...
In each iteration of a FOR loop, the IN ( ....) clause is evaluated and %%G set to a
different value
If this results in a single value then %%G is set = to that value and the command is
performed.
If this results in a multiple values then extra parameters are implicitly defined to hold
each. These are automatically assigned in alphabetical order %%H %%I %%J
...(implicit parameter definition)
For example
FOR /F %%G IN ("This is a long sentence") DO @echo %%G %%H %%J
will result in the output
This is long
You can of course pick any letter of the alphabet other than %%G.
%%G is a good choice because it does not conflict with any of the pathname format
letters (a, d, f, n, p, s, t, x) and provides the longest run of nonconflicting letters for
use as implicit parameters.
G > H > I > J > K > L > M
Other Environment variables
Environment variables within a FOR loop are expanded at the beginning of the loop
and won't change until AFTER the end of the DO section.
The following example counts the files in the current folder, but %count% always
returns 1:
@echo off
SET count=1
FOR /f "tokens=*" %%G IN ('dir /b') DO (
echo %count%:%%G
set /a count+=1)
To make this work correctly we must force the variable %count% to be evaluated
during each iteration, using the CALL :subroutine mechanism:
@echo off
SET count=1
FOR /f "tokens=*" %%G IN ('dir /b') DO (call :s_do_sums "%%G")
GOTO :eof
:s_do_sums
echo %count%:%1
set /a count+=1
GOTO :eof
Nested FOR commands
FOR commands can be nested FOR %%G... DO (for %%U... do ...)
when nesting commands choose a different letter for each part. you can then refer to
both parameters in the final DO command.
If Command Extensions are disabled, the FOR command will only support the basic
syntax with no enhanced variables:
FOR %%parameter IN (set) DO command [commandparameters]
"Those who cannot remember the past are condemned to repeat it" George
Santayana
Related Commands:
FOR Loop through a set of files in one folder
FOR /R Loop through files (recurse subfolders)
FOR /D Loop through several folders
FOR /L Loop through a range of numbers
FOR /F Loop through items in a text file
FOR /F Loop through the output of a command
FORFILES Batch process multiple files
GOTO Direct a batch program to jump to a labelled line
IF Conditionally perform a command
Equivalent Linux BASH commands:
cut Divide a file into several columns
for var in [list]; do Expand list, and execute commands
eval Evaluate several commands/arguments
until Execute commands (until error)
while Execute commands
FORFILES.exe (Resource Kit)
Batch process multiple files
syntax
FORFILES [-pPath] [-s] [-dDate] [-mMask] [-cCommand]
key
-Path : Path to search default=current
folder
-v : Verbose report
The following variables can be used in cCommand (must be upper case)
@FILE,
@FNAME_WITHOUT_EXT,
@EXT,
@PATH,
@RELPATH,
@ISDIR,
@FSIZE,
@FDATE,
@FTIME
To ECHO Hex characters in the Command use: 0xHH
Examples:
To find every text file on the C: drive
FORFILES -pC:\ -s -m*.TXT -c"CMD /C Echo @FILE is a text file"
List every file on the C: drive last modified over 100 days
ago
FORFILES -pc:\ -s -m*.* -d-100 -c"CMD /C Echo @FILE : date >=
100 days"
note:
'0x22' is hex 22 - the double quote character - put these
around any long filenames.
Version 1.0 of FORFILES will only search for files newer than a specified date.
Version 1.1 (described above) can search for file dates Newer or Older then a
specified date.
version 1.1 can be downloaded from Microsoft's ftp site
An alternative method of dealing with files older or newer than a specified date is to
use ROBOCOPY
Rule #1: Don't sweat the small stuff.
Rule #2: It's all small stuff Dr Robert S Eliot, University of Nebraska cardiologist
Related Commands:
FOR Conditionally perform a command several times.
MUNGE Find and Replace text within file(s)
Equivalent Linux BASH commands:
for Expand words, and execute commands
case Conditionally perform a command
eval Evaluate several commands/arguments
if Conditionally perform a command
while Execute commands
FORMAT.com
Format a disk for use with Windows XP
Syntax
FORMAT drive: [/FS:file-system] [/V:label] [/Q] [size]
[/C]
Key
/FS:file-system The file system (FAT or NTFS).
The NTFS file system does not function on
floppy disks.
/Q Quick format.
Related Commands:
Q314878 Choosing Cluster Size when formatting a hard drive
Q252448 How to create an NT Bootdisk
Floppy Disks History from Wikipedia
GDISK Ghost Disk, a popular 3rd party tool.
Equivalent Linux BASH commands:
fdformat Lowlevel format a floppy disk
fdisk Partition table manipulator for Linux
FSUTIL.exe (Win XP/2003 server)
File and Volume specific commands, Hardlink management, Quota management,
USN, Sparse file, Object ID and Reparse point management
Create a hardlink
QUOTA Management
Some features in fsutil are reported to not work correctly under FAT or FAT32
volumes e.g. FSUTIL dirty query.
"You can tune a file system, but you can't tune a fish" Sun man page for tunefs
Related Commands:
CACLS Change file permissions
CHKNTFS Check the NTFS file system
DevCon Device Manager Command Line Utility
DIRUSE Display disk usage
FDISK Disk Format and partition
SHORTCUT Create a windows shortcut (.LNK file)
WINMSD Windows NT Diagnostics
Q286164 Hard Links and System Restore
Q249734 Backup Software, RSM and file last access date
Equivalent Linux BASH commands:
quota Display disk usage and limits
quotacheck Scan a file system for disk usage
quotactl Set disk quotas
FTP
File Transfer Protocol
Syntax
FTP [-options] [-s:filename] [-w:buffer] [host]
key
-s:filename Run a text file containing FTP commands.
-n No auto-login.
-d Debug
close End the FTP session and return to the cmd prompt.
delete remote-file
Delete file on remote host.
lcd [directory]
Change the working directory on the local PC.
By default, the working directory is the
directory in which ftp was started.
ls [remote-directory] [local-file]
List a remote directory's files and folders.
(short format)
mkdir directory
Create a directory on the remote host.
quit End the FTP session with the remote host and exit
ftp.
remotehelp [command]
Display help for remote commands.
rmdir directory
Delete a remote directory.
type [type-name]
Set or display the file transfer type:
`binary' or `ASCII' (the default)
[User_id]
[ftp_password]
binary
get /usr/file1.exe
get file2.html
mget *.jpeg
ascii
mget *.txt
quit
[User_id]
[ftp_password]
binary
mput *.html
cd images
mput *.gif
quit
File Transfer Protocol
FTYPE
Display or change the link between a FileType and an executable program
Syntax
FTYPE fileType=executable_path
FTYPE
FTYPE fileType
FTYPE fileType=
Key
fileType : The type of file
File Types can be displayed in the Windows Explorer GUI: [View, Options, File
Types] however the spelling is usually different to that expected by the FTYPE
command e.g. the File Type "txtfile" is displayed in the GUI as "Text Document"and
"jpegfile" is displayed as "image/jpeg"
Several FileTypes can be linked to the same executable application, but
one FileType cannot be linked to more than one executable application.
FTYPE file type will display the current executable program for that file type.
FTYPE without any parameters will display all FileTypes and the executable program
for each.
Defining command line parameters
It is almost always necessary to supply command line parameters so that when a
document is opened not only is the relevant application loaded into memory but the
document itself also loaded into the application. To make this happen the filename of
the document must be passed back to the application.
Command line parameters are exactly like batch file parameters, %0 is the
executable program and %1 will reference the document filename
so a simple command line might be:
MyApplication.exe "%1"
If any further parameters are required by the application they can be passed as %2,
%3. To pass ALL parameters to an application use %*. To pass all the remaining
parameters starting with the nth parameter, use %~n where n is between 2 and 9.
The FileType should always be created before making a File Association
For example:
FTYPE htmlfile="C:\PROGRA~1\Plus!\MICROS~1\iexplore.exe" nohome
ASSOC .html=htmlfile
FTYPE pagemill.html=C:\PROGRA~1\Adobe\PAGEMI~1.0\PageMill.exe "%1"
ASSOC .html=pagemill.html
FTYPE rtffile="C:\Program Files\Windows NT\Accessories\WORDPAD.EXE" "%1"
ASSOC .rtf=rtffile
FTYPE word.rtf.8="C:\Program Files\Microsoft Office\Office\winword.exe" /n
ASSOC .rtf=word.rtf.8
Switching a File Association between multiple applications
If you have multiple applications that use the same file extension, the ASSOC
command can be used to switch the file extension between the different FileTypes.
Deleting a FileType
Specify executable_path=nothing and the FTYPE command will delete the
executable_path for that FileType.
For example:
FTYPE htmlfile=
Backing up your FileTypes
FTYPE >backup_types.txt
ASSOC >backup_ext.txt
Restoring your FileTypes from a Backup
FOR /F "tokens=* delims=" %G IN (backup_types.txt) DO FTYPE %G
FOR /F "tokens=* delims=" %G IN (backup_ext.txt) DO ASSOC %G
This will recreate the CLASS id's in the registry at HKey_Classes_Root\.<file
extension>
If you put the commands above in a batch file change the %G to be %%G
Using File associations at the command line
If you have a file association between .DOC and Word for Windows then at a
command prompt you can open a document with any of the following commands:
Start "My Document.doc"
"Monthly Report.doc"
JULY.DOC
note that the file extension must be supplied for this to work
"True to type Of a plant, or group of plants, which matches the accepted description
of the cultivar to which it is assumed to belong"
Related Commands:
ASSOC Change file extension associations
Batch file to list the application associated with a file extension
ASSOCIAT One step file association (Resource Kit)
GLOBAL (Resource kit)
Display membership of global groups on remote servers or remote domains.
Syntax
GLOBAL group_name domain_name | \\server
Key
group_name The global group.
domain_name A network domain.
\\server A network server.
Examples:
GLOBAL "Domain Users" Scotland
Displays the members of the group "Domain Users" in the Scotland domain.
GLOBAL PrintUsers \\9G_Server
Displays the members of the group PrintUsers on server 9G_Server.
"The balance of evidence suggests a discernible human influence on global climate"
IPCC
Related commands
NET GROUP Manage network resources
NET LOCALGROUP Manage network resources
FINDGRP List the (global or local) security groups a user has joined (NT 4 Reskit)
LOCAL Display membership of local groups
GetDC Get domain controller
Cusrmgr Console User Manager. (Win 2K ResKit)
Equivalent Linux BASH commands:
groups Print group names a user is in
id Print user and group id's
uname Print system information
GOTO
Direct a batch program to jump to a labelled line.
Syntax
GOTO label
Key
label : a predefined label in the batch program. Each label
must
be on a line by itself, beginning with a colon.
For example:
IF %1==12 GOTO s_december
:: other commands
:s_december
GOTO :eof
An easy way to exit a batch script file without defining a label is to specify
GOTO :eof
this transfers control to the end of the current batch file.
Using a variable as a label
CHOICE
goto s_routine_%ERRORLEVEL%
:s_routine_0
echo You typed Y for yes
:s_routine_1
echo You typed N for no
Skip commands by using a variable as a :: comment (REM)
In this example the COPY command will only run if the parameter "Update" is
supplied to the batch
@echo off
setlocal
IF /I NOT %1==Update SET _skip=::
%_skip% COPY x:\update.dat
%_skip% echo Update applied
...
If Command Extensions are disabled GOTO will no longer recognise the :EOF label
"It's just a jump to the left... and then a step to the right.." The Time Warp
Related Commands:
IF Conditionally perform a command
CALL Call one batch program from another
Equivalent Linux BASH commands:
case Conditionally perform a command
HELP
Online help for MS Windows most commands will give help when run with /? or ?
(COMMAND /? or COMMAND ?)
GUI Help is available from START Help or by running the help files directly:
C:\WINDOWS\help\ntcmds.chm
C:\WINDOWS\help\ntdef.chm
C:\WINDOWS\help\ntchowto.chm
C:\WINDOWS\help\nthelp.chm
C:\WINDOWS\help\ntshared.chm
Syntax
WINHELP [options] helpfile.hlp
In XP: C:\WINDOWS\PCHealth\HelpCtr\Binaries\HelpCtr.exe
options:
-W window
Specify the window for displaying the topic.
This command cannot be used with -P.
-N contextNum | -I topicID
Specify the topic to open using either a topic number,
(defined in the [MAP] section of the HPJ file.)
or a topic ID string
(# footnote in the topic).
-K keyword
Specify the topic to open using a keyword.
This command cannot be used with -N or -I.
Equivalent Linux BASH commands:
man pages
HFNETCHK (Shavlik Technologies)
Network Security Hotfix Checker.
Syntax
hfnetchk.exe [options]
Options
[-h hostname] NetBIOS computer name(s) to scan.
default=local host.
separate multiple host name entries
with a comma,
-? Menu of options
You can use the switches above in combination so a single command can scan a
range of IP addresses plus a list of specific machines.
"It's completely intuitive; it just takes a few days to learn, but then it's completely
intuitive" Terry Pratchett.
Related Commands:
Q303215 Download HFNETCHK (plus examples)
HFNETCHK Microsoft HfNetChk Newsgroup.
Q296861 Use QCHAIN to install multiple hotfixes with only one reboot.
Q310747 System File Checker (Sfc.exe)
Equivalent Linux BASH commands:
rpm Remote Package Manager
IF
Conditionally perform a command.
File syntax
IF [NOT] EXIST filename command
String syntax
IF [/I] [NOT] item1==item2 command
key
item : May be a text string or an environment
variable
a variable may be modified using either
Substring syntax or Search syntax
command : The command to perform
IF ERRORLEVEL statements should be read as IF Errorlevel > OR = number
i.e.
IF ERRORLEVEL 1 will return TRUE for an errorlevel of 1 or greater.
To put that another way, ERRORLEVEL will return 0 on the successful completion of
a command, however IF ERRORLEVEL 0 will also return true even if the errorlevel is
196!
Examples:
IF EXIST C:\install.log (echo complete) ELSE (echo failed)
In the case of a variable that may be NULL a null variable will remove the variable
definition altogether, so testing for NULLs becomes easy:
IF NOT DEFINED _example ECHO Value Missing
IF DEFINED will return true if the variable contains any value (even if the value is just
a space)
Test the existence of files and folders
IF EXIST name will detect the existence of a file or a folder the script empty.cmd
will show if the folder is empty or not.
Brackets
You can improve the readability of a batch script by writing a complex IF...ELSE
command over several lines using brackets
e.g.
IF EXIST filename (
del filename
) ELSE (
echo The file was not found.
)
The IF statement does not use any great intelligence when evaluating Brackets, so
for example the command below will fail:
IF EXIST MyFile.txt (ECHO Some(more)Potatoes)
This version will work:
IF EXIST MyFile.txt (ECHO Some[more]Potatoes)
Testing Numeric values
Do not use brackets or quotes when comparing numeric values
e.g.
IF (2) GEQ (15) echo "bigger"
or
IF "2" GEQ "15" echo "bigger"
These will perform a character comparison and will echo "bigger"
however the command
IF 2 GEQ 15 echo "bigger"
Will perform a numeric comparison and works as expected notice that this
behaviour is exactly opposite to the SET /a command where quotes are required.
Any test made using the compare-op syntax will always be a "string" comparison,
so when comparing numbers note that "026" > "26"
Wildcards
Simple wildcards are not supported by IF, so ==SS6* will not match SS64
The workaround is to spoof a wildcard using SET to retrieve the substring
SET _part_name=%COMPUTERNAME:~0,3%
IF NOT %_part_name%==SS6 GOTO they_matched
Pipes:
When piping commands, the expression is evaluated from left to right, so
IF... | ... is equivalent to (IF ... ) | ...
you can use the explicit syntax IF (... | ...)
Setting an ERRORLEVEL
It is possible to create a string variable called %ERRORLEVEL% (user variable)
if present such a variable will prevent the real ERRORLEVEL (a system variable)
from being used by commands such as ECHO and IF.
If you want to deliberately raise an ERRORLEVEL in a batch script use the command
"COLOR 00" or simply SET MyError=YES
To test for the existence of a user variable use SET errorlevel, or IF DEFINED
ERRORLEVEL
If Command Extensions are disabled IF will only support direct comparisons: IF ==,
IF EXISTS, IF ERRORLEVEL
also the system variable CMDEXTVERSION will be disabled.
You see things; and you say 'Why?' But I dream things that never were; and I say
'why not?' George Bernard Shaw
Related commands:
Conditional execution syntax (AND / OR)
SET Display, or Edit Windows NT environment variables
ECHO Display message on screen
IFMEMBER NT Workgroup member (Resource kit)
SC Is a Service running (Resource kit)
Equivalent Linux BASH commands:
case Conditionally perform a command
if Conditionally perform a command
until Execute commands (until error)
while Execute commands
IFMEMBER (Resource Kit)
Count the NT Workgroups that the current user is a member of.
Syntax
IFMEMBER [options] WorkGroup [ WorkGroup2 WorkGroup3...]
Options:
/verbose or /v : print all matches.
/list or /l : print all groups user is a member
of
The %ERRORLEVEL% return code shows how many of the listed workgroups the
currently loggedin user is a member of.
Examples
IFMEMBER /v /l "MyDomain\Administrators"
IF ERRORLEVEL 1 echo This user is an Administrator
Notice that the syntax here is the opposite to normal in that
%ERRORLEVEL% = 1 = Success
with most other NT commands %ERRORLEVEL% = 1 = Fail/Error
The best way to utilise IFMEMBER is through conditional execution...
IFMEMBER Administrators || ECHO Error is 1 so [%Username%] is in Admin_WG
IFMEMBER Administrators && ECHO Error is 0 so [%Username%] is NOT in
Admin_WG
"The euro will raise the citizens' awareness of their belonging to one Europe more
than any other integration step to date" Gerhard Schroeder
Related Commands:
NET GROUP add or remove a user from a workgroup
SHOWMBRS List the members of an NT Workgroup
SHOWACCS Show access profile (Windows 2000)
GRPTEST SMS support tools enumerate group membership for a user account.
Cusrmgr Console User Manager. (Win 2K ResKit)
Joeware.net MemberOf.exe Like IFMEMBER but able to handle nested AD groups
IPCONFIG
Configure IP.
Syntax
The default is to display only the IP address, subnet mask and default gateway for
each adapter bound to TCP/IP.
For Release and Renew, if no adapter name is specified, then the IP address leases
for all adapters bound to TCP/IP will be released or renewed.
For Setclassid, if no ClassId is specified, then the ClassId is removed.
Examples:
> ipconfig ... Show information.
> ipconfig /all ... Show detailed information
> ipconfig /renew ... renew all adapters
> ipconfig /renew EL* ... renew any connection that
has its
name starting with EL
"Life is a grand adventure or it is nothing." Helen Keller
Related Commands:
BROWSTAT Get domain, browser and PDC info
NETSTAT Display networking statistics (TCP/IP)
NETSH Configure interfaces, routing protocols, filters, routes, RRAS
PATHPING IP trace utility
PING Test a network connection
Q192064 Locate multiple preferred logon servers
Q813878 How to block specific network protocols and ports.
Q313190 Use IPSec IP Filter Lists
The Inq/Jon Honeyball Routing to harden machines against attack
NTFAQ How to disable automatic private IP addressing (2K and XP)
Equivalent Linux BASH commands:
ping Test a network connection
trace Find the IP address of a remote host.
KILL (Resource kit)
Remove a running process from memory.
Syntax
KILL [option] process_id
KILL [option] task_name
KILL [option] window_title
Option
-f Force process kill
Note: Kill f basically just nukes the process from existence, potentially leaking a lot
of memory and losing any data that the process hadn't committed to disk yet. It is
there for worst case scenarios when you absolutely must end the process now, and
don't care whether proper cleanup gets done or not.
In WindowsXP, KILL is replaced with the superior TASKKILL Allowing you to specify
a remote computer, different user account etc for more details run TASKKILL /?
If you're going to tell people the truth, you'd better make them laugh. Otherwise they'll
kill you. George Bernard Shaw
Related Commands:
PsKill Kill processes by name or process ID
PsSuspend Suspend a processes
TASKKILL Kill a local or remote task (XP)
PsList List detailed information about processes
NET Stop a service from running
NET FILE Force an open file to close
RKILL Remote Kill (Resource Kit) view or kill processes on a remote server
Q171773 Kill a background process
Q178893 Terminate an Application "Cleanly" in Win32
Q197155 How to Kill an Orphaned Process
Equivalent Linux BASH commands:
kill Kill a process
LABEL
Edit a disk label.
Syntax
LABEL [drive:][label]
The disk label is never referred to by other batch commands, it's just for human
recognition.
e.g. as a reminder of which floppy disk is actually in the machine.
The maximum length is 11 characters (spaces allowed)
This is not to be confused with the drive description held in the registry.
Example
LABEL A: My work disk
"A name is a label, and as soon as there is a label, the ideas disappear and out
comes labelworship and labelbashing" Richard Bach
Related Commands:
VOL display the volume label
Q159865 How to distinguish a physical disk device (registry settings)
Equivalent Linux BASH commands:
hostname Print or set system name
uname Print system information
LOCAL (Resource kit)
Display membership of local groups on remote servers or remote domains.
Syntax
LOCAL group_name domain_name | \\server
Key
group_name The local group.
domain_name A network domain.
server A network server.
Examples:
Local "Power Users" Scotland
Displays the members of the group 'Power Users' in the Scotland domain.
Local Administrators \\9G_Server
Displays the members of the group Administrators on server 9G_Server.
"This is a local shop for local people, there’s nothing for you here" league of
gentlemen
Related commands
NET GROUP Manage network resources
NET LOCALGROUP Manage network resources
FINDGRP List the (global or local) security groups a user has joined (NT 4 Reskit)
GLOBAL Display membership of global groups.
GetDC Get domain controller
Cusrmgr Console User Manager. (Win 2K ResKit)
Equivalent Linux BASH commands:
groups Print group names a user is in
id Print user and group id's
uname Print system information
LOGEVENT (Resource kit)
Write text to the event log (event viewer)
Syntax
logevent [-m \\MachineName] [options] "Event Text"
Options
-s Severity one of
(S)uccess
(I)nformation
(W)arning
(E)rror
(F)ailure
EVENTCREATE Create a custom event log message (Windows XP)
EVENTQUERY Read an event log message (Windows XP)
EVENTTRIGGERS display and configure Event Triggers (Windows XP)
NET SEND Manage network resources (Popup message)
WshShell.LogEvent Log an item in the Event log
WMIC NTEVENTLOG WMI access to the event log
Q131008 Use eventlog from a batch file
LOGOFF.exe (Resource Kit)
Log a user off.
Syntax
LOGOFF [/f] [/n]
Key
/f Force running processes to close, but will ask for
user confirmation.
The user will not be asked to save unsaved data.
Windows XP includes the SHUTDOWN command that can now logoff a user.
"The man who is tired of London is tired of looking for a parking space" Paul
Theroux
Related Commands:
SHUTDOWN Shutdown the computer
psShutdown SysInternals
JSIFAQ Tip 9130 log off user after n minutes of inactivity
LOGTIME.exe (Resource kit)
Create logtime.txt and adds the date, time and a message
Syntax
LOGTIME text_string
Key
text_string : The message to add to the log file.
The date is stored in the US mm/dd/yy format (NT 4.0)
Sample batch file:
LOGTIME "begin import program"
import.exe
LOGTIME "end import program"
An alternative command is
ECHO. | DATE | FIND /i "current">>C:\Install_log.txt
"You can always tell that an organisation is on the skids when it changes it's name,
and pays a lot of money for consultants to invent some ghastly new corporate
identity" Baroness Helena Kennedy
Related Commands:
ECHO Display message on screen
DATE /T Display or set the date
TOUCH Change file timestamps
Timethis Time how long it takes the system to run a command. (Win 2K ResKit)
Uptime Time since last reboot. (Win 2K ResKit)
Equivalent Linux BASH commands:
echo Display message on screen
select Accept keyboard input
MAPISEND (Back Office/Exchange Resource kit)
Send email from the command line.
Syntax
MAPISEND -u "profile" -p password
-r recipient -s "subject" -m text message [options]
options
-i interactive login (prompts for profile and password)
-c cc: list
-f File Attachment - path and file name(s)
-v generates verbose output (an 8 line summary of the
message)
Related Commands:
Q290499 programmatic access to Outlook email
BLAT (freeware) Send email via SMTP (avoids the need to install MS Outlook)
On machines with a web browser installed the command
START mailto:billg@sun.com
will send email but requires the user to complete and send the message.
Equivalent Linux BASH commands:
sendmail
MEM
Display memory usage.
Syntax
MEM
MEM /C
MEM /D
MEM /P
Key
/P List programs in memory
with the memory address and size of each
Related Commands:
CLEARMEM (Resource Kit) Clear Memory Leaks
WINMSD Windows NT Diagnostics (including Physical Memory)
GUI Task Manager for all program details including Win32 applications.
TLIST Task List
Q184419 DisablePagingExecutive (use when >500M RAM is available)
Q126962 How to increase desktop heap memory for noninteractive processes
/3GB Startup Switch for Windows 2003
Equivalent Linux BASH commands:
free t Display a summary of current memory usage and availability.
MD
Make Directory Creates a new folder.
Syntax
MD [drive:]path
Key
The path can consist of any valid characters up to the
maximum path length available
You should avoid using the following characters in folder names they are known to
cause problems
© ® " & ' ^ ( ) and @
also many extended characters may not be recognised by older 16 bit windows
applications.
The maximum length of a full pathname (folders and filename) under NTFS or FAT is
260 characters.
Folder names are not case sensitive, but only folder names longer than 8 characters
will always retain their case, as typed.
For Example
C:\temp> MD MyFolder
Make several folders with one command
C:\temp> MD Alpha Beta Gamma
will create
C:\temp\Alpha\
C:\temp\Beta\
C:\temp\Gamma\
Make an entire path
MD creates any intermediate directories in the path, if needed.
For example, assuming \utils does not exist then:
MD \utils\downloads\Editor
md \utils
cd \utils
md downloads
cd downloads
md Editor
If you plan to copy data onto CDROM avoid folder trees more than 8 folders deep
MKDIR is a synonym for MD
"We are American at puberty. We die French" Evelyn Waugh
Related Commands:
RD Delete folders or entire folder trees
Linkd link an NTFS directory to a target object. (Win 2K ResKit)
Equivalent Linux BASH commands:
mkdir Create new folder(s)
MODE
Mode is an all purpose configuration command, used without parameters, MODE
displays the status of all devices installed on your system.
Devices
Show the status of all devices: (Typically COM1, COM2, LPT1, CON)
MODE
Show the status of a specific device:
MODE [device]
To additionally show the status of any redirected parallel printer:
MODE [device] [/STATUS]
CMD Prompt window size
Change the CMD prompt screen size/buffer
Number of cols(characters) wide and Number of lines deep
MODE CON[:] [COLS=c] [LINES=n]
Keyboard
Set the keyboard typematic rate, the rate at which a character is repeated when you
hold down the key.
MODE CON[:] [RATE=r DELAY=d]
Printing
To redirect output from a parallel port (PRN, LPT1, LPT2, or LPT3) to a serial
port(COM1, COM2, COM3, etc).
You must be a member of the Administrators group to redirect printing.
To configure a parallel printer port (PRN, LPT1, LPT2, or LPT3):
MODE LPTn[:]=COMm[:]
To setup the parameters for a serial port (* see Start, Help, Commands for more on
this).
MODE COMm [options*]
Configure a printer connected to a parallel printer port.
mode LPTn[:] [c][,[l][,r]]
mode LPTn[:] [cols=c] [lines=l]
This allows you to configure a line printer connected to a parallel printer port.
International Settings
Change the current code page:
MODE CON[:] CP SELECT=yyy
Display the current Code page:
MODE CON[:] CP [/STATUS]
Examples:
MODE CON:cols=80 lines=25
"The dogma of the ghost in the machine" Gilbert Ryle
Related commands:
NET manage network resources
CHCP Display or change device settings
Equivalent Linux BASH commands:
lpc Line printer control program
printcap printer capability database
PROMPT_COMMAND environment variable
screen Terminal window manager
MORE
Display output one screen at a time. MORE can be used to run any executable
command (or batch file) and pause the screen output one screen at a time. MORE
can also be used to TYPE the contents of any file to the screen.
Syntax
command | MORE [/E [/C] [/P] [/S] [/Tn] [+n]]
Key
command : Any executable command or batch file
MORE /E myfile.txt
More (17%)
If extended features are enabled, (/E) the following keystrokes can be used at the
More prompt:
<space> Display next page
<return> Display next line
Q Quit
P n Display next n lines
S n Skip next n lines
F Display next file
= Show line number
? Show help line
"less is more" Ludwig Mies van der Rohe
Related commands:
TYPE display files
ECHO display variables
List Text Display and Search Tool (Win 2K ResKit)
Equivalent Linux BASH commands:
more Display output one screen at a time
less Display output one screen at a time
MOUNTVOL (Windows 2000)
Create, delete or list a volume mount point.
Syntax
Options
WINDISK NT Disk Administrator
BootCFG Edit Boot.ini settings.
Equivalent Linux BASH commands:
mount Mount a file system
MOVE
Move a file from one folder to another
Syntax
MOVE [options] [Source] [Target]
Key
source : The path and filename of the file(s) to move.
In the current folder
MOVE oldfile.wp newfile.doc
Full path specified
MOVE g:\department\oldfile.wp "c:\Files to Convert\newfile.doc"
Specify the drive and filename (assumes the current folder on both drives is correct)
MOVE a:oldfile.wp c:newfile.doc
Specify source only (will copy the file to current folder, keeping the same filename)
MOVE g:\department\oldfile.wp
Quiet move (no feedback on screen)
MOVE oldfile.wp newfile.doc >nul
"If it moves, tax it. If it keeps moving, regulate it, and if it stops moving, subsidize it"
Ronald Reagan
Related Commands:
COPY Copy one or more files to another location
ROBOCOPY /MOVE Robust File and Folder Copy
XCOPY Copy files and folders
MV Copy inuse files
REN Rename a file or files.
Cachemov Offline Files Cache Mover. (Win 2K ResKit)
Equivalent Linux BASH commands:
mv Move or rename files or directories
MOVEUSER.exe (Resource Kit)
Move a user account into a domain or edit an NT username.
Syntax
MOVEUSER [DOMAIN/]user1 [DOMAIN/]user2 [/c:computer]
[/k] [/y]
Key:
Q838191 RestrictRemoteClients registry keys for MOVEUSER under XP sp2
SHUTDOWN Shutdown the computer
ADMT Active Directory Migration Tool (domain to domain)
MSG.exe
Send a popup message to a user.
Syntax
MSG username [options] [message]
Options
ECHO Display message on screen
TYPE Display the contents of a text file
Equivalent Linux BASH commands:
echo Display message on screen
MSIEXEC
Microsoft Windows Installer.
Syntax
Install
MSIEXEC /i package options
Uninstall
MSIEXEC /x package options
Options:
/fp fix - replace missing files
/fo fix - replace Older files
/fe fix - replace older or Equal date files
/fd fix - replace Different version files
/fc fix - replace files based on Checksum
differences
/fa fix - replace All files
/fu fix - rewrite HKCU registry
/fm fix - rewrite HKLM registry
/fs fix - recreate shortcuts
/fv fix - rewrite local cache from source
/l* Logfile Log Everything (not Verbose)
/l*v Logfile Log Everything Verbose
/lv Logfile Log Verbose
/le Logfile Log All error messages
/lw Logfile Log Non-fatal warnings
/li Logfile Log Status messages
/la Logfile Log Startup actions
/lr Logfile Log Actions
/lu Logfile Log User requests
/lc Logfile Log User Interface (UI) parameters
/lm Logfile Log memory use
/lp Logfile Log Terminal properties
/l+ Logfile Append to an existing log file.
/l! Logfile Clear an existing log file.
/q , /qn No UI.
/qb Basic UI.
/qb! Basic UI with no cancel button.
/qr Reduced UI. A modal dialog box is displayed at
the end of the install.
/qf Full UI. A modal dialog box is displayed at the
end of the install.
/qn+ No UI. However, a modal dialog box is displayed
at the end of the installation.
/qb+ Basic UI. A modal dialog box is displayed at the
end of the installation. If you cancel the installation, a
modal dialog box is not displayed.
/qb- Basic UI with no modal dialog boxes.
/y module Register a DLL - only use for registry
information that cannot be added using the registry tables of
the .msi file.
/z module UnRegister a DLL - only use for registry
information that cannot be removed using the registry tables
of the .msi file.
Windows installer versions
Windows NT can support version 1.1 or version 1.2
Windows 2K includes version 1.1
Windows XP Sp1 /Server 2003 include version 2.0
Windows XP SP2 includes version 3.0
Updates to msiexec can be downloaded from MSDN.
"People don't resist change. They resist being changed!" Peter Senge.
Related commands:
CHANGE Change Terminal Server session properties
REGSVR32 Register or unregister a DLL
RunDll32 Uninstall DLL's e.g. MS Java
Q230781 Msiexec commandline
Q310747 System File Checker (Sfc.exe)
InstallSite.org Installer and Setup resources
Equivalent Linux BASH commands:
RPM Rpm Package Manager
MSINFO32 (Windows 2000 or MS Office)
Windows NT diagnostics
Reports: Memory use, Drivers, DLL versions, Audio,Video and Print settings.
Syntax
MSinfo32 <options>
Options
/c List the version, date, and build of
each DLL in
a user-specified folder and determine
whether it's
loaded in memory.
/msinfo_file Open the specified .nfo or .cab file
/nfo or /s Output an .nfo file with the specified
file name
/report Output a text file
/computer Get details from a remote computer
/categories Display or output the specified
categories
/category Set focus to a specific category at
startup
msinfo32 /c [My DLL’s] c:\mydir
(Be sure to include the square brackets.)
Note that early versions of MSinfo do not support all the switches listed above.
MSinfo is typically started from Help,About rather than the command line, if not in the
system path, MS info can usually be found in:
C:\Program Files\Common Files\Microsoft Shared\MSInfo
Note that generation of the text file can take some time, depending on the complexity
of the system.
If you have problems getting MSInfo to run, check permissions on the following key:
HKLM\SOFTWARE\Microsoft\Shared Tools\MSInfo\
Under the W2K commandline you can run WINMSD /? rather than Msinfo32 /?
"Education is not the filling of a pail, but the lighting of a fire." W. B. Yeats
Related Commands:
WINMSDP Windows NT Diagnostics II
Q255713 Windows 2000 CommandLine Parameters for Msinfo32
Microsoft online DLL version Database
MSTSC
Terminal Server Connection, RDP (Remote Desktop
Protocol)
Syntax
MSTSC option
MSTSC /Edit"ConnectionFile"
MSTSC /migrate
Options
ConnectionFile The name of an RDP file for connection
/v:<server[:port]> Terminal server (or PC) to connect to
/console Connect to the console of a server
/f Start in Full Screen mode
/w:width Width of the RDP screen
/h:height Height of the RDP screen
/edit Open the RDP file for editing
/migrate Migrate a Client connection file to RDP
The /console option only works when connecting to an Windows XP Professional
or Windows Server 2003 computer.
When connected to a remote desktop, the key combination CtrlAltEND will send
CtrlAltDel to the remote client.
Examples:
MSTSC /v:MyServer /f /console
MSTSC /v:127.0.0.1 /w:1024 /h:768
MSTSC /v:MyServer /w:800 /h:600
MSTSC /edit filename.rdp
On the Windows XP CD, under \SUPPORT\TOOLS you'll find MSRDPCLI.exe. This
is the setup for use with 9.x/2000 machines.
"Ignorance is preferable to error; and he is less remote from the truth who believes
nothing, than he who believes what is wrong" Thomas Jefferson
Related Commands:
MAPISEND Send email from the command line
RMTSHARE Share a folder or printer
SHORTCUT Create a windows shortcut
SHUTDOWN Shutdown the computer/Log off a user
Equivalent Linux BASH commands:
vncconnect Connect to a VNC server
MUNGE.exe (NT4 Resource Kit)
Find and Replace text within file(s)
Munge.exe has been dropped from the Resource Kit in Windows 2000 and above.
Syntax
MUNGE ScriptFile [options] FilesToMunge...
Key
Editing options
-q : Query only - don't actually make changes.
-e : Query only - display entire line for each match
-o : Query only - just display filename once on first
match
-k : Case - Case sensitive scriptFile
-r : Recurse into subfolders
-m : Collapse multiple carriage returns into one
-@ : Remove null characters
-n : Neuter - Surround all strings with TEXT()
-L : Literals - Dont process any quoted text (excludes
comments)
-l : Literals - Dont process any quoted text (includes
comments too)
Display options
Destination options
oldName newName
"oldString" "newString"
-F .Ext Name. Name.Ext
-F [Name].[Ext]
Munge will only search for a complete string delimited with spaces it won't match
part of a string.
Munge does not support long file names.
Munge does not work reliably for files greater than 2 Mb.
Munge will not read unicode text.
When FilesToMunge (on the command line) is a specific file then this filename will
override any F setting.
When MUNGE is used with a wildcard to modify multiple files then you must specify
F in the scriptfile.
MUNGE will create a backup file called .BAK, for this reason do not process files that
have a .BAK extension unless you specify t (dont create backup)
Example:
MUNGE myChanges.ini FileToMunge.txt
Where myChanges.ini contains the following
::::::::::::
-F FileToMunge.txt
"Driver32=C:\WINNT\System32\odbc16.dll"
"Driver32=C:\WINNT\System32\odbc32.dll"
"Driver32=C:\WINNT\System32\jct16.dll"
"Driver32=C:\WINNT\System32\jct32.dll"
::::::::::::
Notice that the whole string has to be spelled out even though only a small part is
being changed. Watch out for trailing spaces.
In the onscreen feedback a TOKEN means your script may replace one word with
another, while a LITERAL STRING means your script will replace one "Quoted
String" with "Another Quoted string"
Munge script files can contain multiple string replacements these will be applied in
one pass only.
In other words if you replace A with B and also replace B with C. Then A will not be
changed into C (unless you run the MUNGE command twice.
"I understand that change is frightening for people, especially if there's nothing to go
to. It's best to stay where you are. I understand that." Princess Diana
Related:
FOR Conditionally perform a command several times.
FIND Search for a text string in a file
FINDSTR Search for strings in files
QGREP Search file(s) for lines that match a given pattern
gawk for Windows
sed for Windows (Docs)
ReplaceEm GUI Freeware
InfoRapid Search & Replace Freeware
Equivalent Linux BASH commands:
gawk Find and Replace text within file(s)
sed Stream Editor Find and Replace text within file(s)
tr Translate, squeeze, and/or delete characters
MV.exe (Resource Kit)
Move File Copy a file to another location even if the file is in use (Locked)
Syntax
MV /x /d source destination
Key
The first file name is the file to be copied and the second
the destination pathname.
The NT resource kit contains 2 versions of MV.EXE a posix version and a Windows
NT version they are not the same!
The /d option is not available with the posix version of mv, but if you prefer, you can
do a file replace at boot time by manually updating the registry (which is all MV.exe
does)
Start the registry editor (regedt32.exe not regedit.exe)
Move to HKLM\SYSTEM\CurrentControlSet\Control\Session Manager
Double click on
PendingFileRenameOperations
(if it does not exist create of type multi_str )
On the first line is the name of the new file with \??\ in front,
e.g.
\??\d:\temp\ntfs.sys
On the second line is the file to replaced with !\??\ in front,
e.g.
!\??\c:\winnt\system32\drivers\ntfs.sys
Click OK
So the complete MultiString Data would appear like:
\??\d:\temp\ntfs.sys
!\??\c:\winnt\system32\drivers\ntfs.sys
Once the reboot is complete and the file replaced the PendingFileRenameOperations
value will be deleted from the registry
"Anyone who has been to an english public school will always feel comparitively at
home in prison" Evelyn Waugh
Related Commands:
INUSE updated file replacement utility (may not preserve file permissions)
COPY Copy one or more files to another location
MOVE Move a file from one folder to another
Cachemov Offline Files Cache Mover. (Win 2K ResKit)
Equivalent Linux BASH commands:
mv Move or rename files or directories
NET.exe
The NET Command is used to manage network resources as follows:
Manage Services
NET START, STOP, PAUSE, CONTINUE
Connect to a file/print Share (Drive Map)
NET USE
Create/view file/printer Shares
NET SHARE, VIEW, FILE, SESSIONS
Manage Network Print jobs and Network Time
NET TIME, PRINT
Security
NET ACCOUNTS, USER, GROUP, LOCALGROUP
Network Messaging
NET NAME, SEND
Help
NET HELP, HELPMSG
Network configuration
NET COMPUTER, CONFIG_WORKSTATION, CONFIG_SERVER,
STATISTICS_WORKSTATION, STATISTICS_SERVER
When you use NET commands in a batch file, you can use the Y or N switch to
unconditionally answer Yes or No to questions returned by the Net command
"The white man knows how to make everything but he does not know how to
distribute it" Sitting Bull
Related commands:
CON2PRT Connect or disconnect a Printer
GLOBAL Display membership of global groups
LOCAL Display membership of local groups
MODE Configure a system device
NETDOM Domain Manager
SC Service Control
Q149427 Change Password from the CMD prompt
Equivalent Linux BASH commands:
groups Print group names a user is in
hostname Print or set system name
id Print user and group id's
logname Print current login name
mount Mount a file system
ram ram disk device
uname Print system information
users Print login names of users currently logged in
who Print who is currently logged in
NETDOM.exe (NT Resource Kit supplement 2, Win2K
Support Tools)
Domain Manager a whole bag of network management tools in one tool.
/JOINDOMAIN /JOINWORKGROUP
/Add /DELETE a computer account
(including BDC and resource domain computer accounts)
/Query the secure channel of a resource domain or BDC
/List the resource domain/BDCs in a domain
/Edit trust relationships
/Query the computer role of any domain member or BDC.
In Win2K only
Move a workstation or member server (computer) to a new
domain
Rename/Reset a workstation or member server
Verify or reset and synchronize TIME within a domain
Resynchronize 'out of synch' domain controller`s
Run NETDOM /? for full syntax or look in the supplied WinHelp file.
"Between knowledge of what really exists and ignorance of what does not exist lies
the domain of opinion. It is more obscure than knowledge, but clearer than
ignorance" Plato
Related Commands:
Q150493 Join a Domain from the command line
Q104558 Change NT Server Name
Q139055 Change Computer Name without changing DNS
Q222525 Create Computer Account
NETSH (Win2k Resource Kit, standard command in XP)
Configure Interfaces, Routing protocols, Filters, Routes, Routing & remote access.
Syntax
NETSH [-r router name] [-a AliasFile] [-c Context]
[Command | -f ScriptFile]
Key
context may be any of:
DHCP, ip, ipx, netbeui, ras, routing,
autodhcp, dnsproxy, igmp, mib, nat, ospf, relay, rip,
wins.
/offline
Set the current mode to offline.
changes made in this mode are saved, but
require a "commit"
or "online" command to be set in the router.
/online
Set the current mode to online.
Changes in this mode are immediately reflected
in the router.
/alias [alias_name]
Display the string value of the alias.
/unalias alias_name
Delete an alias.
Related commands:
Q242468 How to Use the Netsh.exe Tool
Q257748 Change from Static IP Address to DHCP with NETSH
Q140859 Win NT TCP/IP Routing Basics
ROUTE Manipulate network routing tables
Equivalent Linux BASH commands:
route
NETSVC.exe (Resource Kit)
Commandline Service Controller. Start, Stop and Query services, but does not
cover creating or deleting them.
Although part of the Windows 2000 resource kit this command runs fine under NT
4.
Syntax
NETSVC \\server command servicename
Key
server The workstation or server where the service
is running
commands:
SC Service Control Create, Create remotely, Start, Stop, Query, Delete.
NET manage network resources
SCLIST Display NT Services
INSTSRV Install an NT service (run under a specific account)
DELSRV Delete NT service
START /HIGH Start a specified program or command.
Svcmon Monitor services and raise an alert if they stop. (Win 2K ResKit)
Q166819 Control Services Remotely
NBTSTAT.exe
Display protocol statistics and current TCP/IP connections using NBT (NetBIOS over
TCP/IP).
Syntax
By Name
NBTSTAT -a Remote_host_Name [options] [interval]
By IP address
NBTSTAT -A IP_address [options] [interval]
Key
-a (adapter status) List the remote machine's name table
given its name
-A (Adapter status) List the remote machine's name table
given its IP address
-c (cache) List NBT's cache of remote [machine]
names
and their IP addresses
-n (names) List local NetBIOS names.
-r (resolved) List names resolved by broadcast and
via WINS
-R (Reload) Purge and reloads the remote cache
name table
-S (Sessions) List sessions table with the
destination IP addresses
-s (sessions) List sessions table converting
destination IP
addresses to computer NETBIOS names.
-RR (ReleaseRefresh) Send Name Release packets to WINS and
then, starts Refresh
IPCONFIG IP Configuration
NETSTAT Display networking statistics (TCP/IP)
PING Test a network connection
TRACERT Trace route to a remote host
Q163409 The 16th character is a NetBIOS suffix
Q119493 NetBIOS over TCP/IP Name Resolution
Q314053 TCP/IP and NBT Configuration Parameters
Equivalent Linux BASH commands:
ping Test a network connection
trace Find the IP address of a remote host
NETSTAT.exe
Display current TCP/IP network connections and protocol statistics.
Syntax
NETSTAT [options] [-p protocol] [interval]
Key
-a Display All connections and listening ports.
-e Display Ethernet statistics. (may be combined with -s)
-n Display addresses and port numbers in Numerical form.
-r Display the Routing table.
-o Display the Owning process ID associated with each
connection.
-p protocol
Show only connections for the protocol specified;
may be any of: TCP, UDP, TCPv6 or UDPv6.
If used with the -s option then the following
protocols
may also be specified: IP, IPv6, ICMP,or ICMPv6.
Related Commands:
Dommon.exe GUI Domain Monitor (W2K but works with NT)
BROWSTAT Get domain, browser and PDC info
ROUTE Manipulate network routing tables.
PATHPING IP trace utility
PING Test a network connection
Equivalent Linux BASH commands:
ping Test a network connection
trace Find the IP address of a remote host
NOW.exe (Resource Kit)
Display Message with current Date and Time
Syntax
NOW [message to be printed with time-stamp]
Typical output:
Mon Mar 06 14:58:48 2000 your message here
Related Commands:
ECHO Display message on screen
DATE /t Display or set the date
LOGTIME Log the date and time in a file
Timethis Time how long it takes the system to run a command. (Win 2K ResKit)
Uptime Time since last reboot. (Win 2K ResKit)
Equivalent Linux BASH commands:
date Display or change the date & time
NSLOOKUP (TCP/IP)
Lookup IP addresses on a NameServer.
Syntax
Lookup the ip address of MyHost:
NSLOOKUP
Related Commands:
NBTSTAT Display networking statistics (NetBIOS over TCP/IP)
NETSTAT Display networking statistics (TCP/IP)
TRACERT Trace route to a remote host
Q200525 Using nslookup
networktools.com nslookup
NTBACKUP
Backup to tape: drives, folders and the systemstate.
Syntax:
options:
systemstate
Back up the System State data.
This will also force the backup type to normal or copy.
/J {"job name"}
The job name to be used in the log file
Describe the files and folders and the backup date-time.
/P {"pool name"}
The media pool from which you want to use media.
Usually a subpool of the Backup media pool, such as 4mm DDS.
If you select this you cannot use /A, /G, /F, or /T
/G {"guid name"}
Overwrite or append to this tape.
Don't use with a media Pool (/P).
/T {"tape name"}
Overwrite or append to this tape.
Don't use with a media Pool (/P).
/A
Perform an append operation.
Either "guid name" (/G) or "tape name" (/T) must be
specified with this switch.
Don't use with a media Pool (/P).
/N {"media name"}
The new tape name. Don't use with Append (/A).
/F {"file name"}
Backup to a file - logical disk path and file name.
Do not use with the switches: /P /G /T.
/D {"set description"}
Label for each backup set
/V:{yes|no}
Verify the data after the backup is complete.
/R:{yes|no}
Restrict access to this tape to the Owner/AdministratorS
/L:{f|s|n}
The type of log file: f=full, s=summary, n=none
/M {backup type}
The backup type. One of: normal, copy, differential,
incremental, or daily
/RS:{yes|no}
Backs up the migrated data files located in Remote Storage.
The /RS command-line option is not required to back up the
local Removable
Storage database (that contains the Remote Storage
placeholder files).
When you backup the %systemroot% folder, Backup
automatically backs up the
Removable Storage database as well.
/HC:{on|off}
Use hardware compression, if available, on the tape drive.
/SNAP:{on|off}
Is the backup is a volume shadow copy. Windows XP only.
/um (Windows 2000 only)
Find the first available media, format it, and use for the
current backup.
Use with the /p switch to scan for available media pools.
This command is only for standalone tape devices (not tape
loaders.)
The /UM switch must be at the end of the command line.
Backups made using Windows Server 2003's NT Backup program can't be restored
with any previous WinNT Backup Program (expect a patch for this soon.)
See also: NTBACKUP syntax for Windows NT 4
Mick Jagger sang backup vocals for "You're so Vain" by Carly Simon
Related Commands:
Q821730 Backup does not run as expected (Server 2003)
Q814583 NT Backup in Windows Server 2003
Q104169 Files that are automatically skipped by Ntbackup
Q300135 Using the Windows 2000 Backup Wizard.
Q237310 Manually Edit Ntbackup.exe Selection Script Files
Q260327 NT Backup error codes. (Win2000)
HKCU\Software\Microsoft\Ntbackup\User Interface Undocumented
JSIFAQ Tip 2265 NTBackup without manually managing the media
AT Schedule a command to run at a later time
CIPHER Encrypt or Decrypt files/folders
XCOPY Copy files and folders
RSM Remote Storage Management Eject tapes (Win2000)
MT Tape utility (3rd party)
Equivalent Linux BASH command:
NTRIGHTS.exe (Resource Kit, 2000/2003)
Edit user account Privileges.
Syntax
NTRIGHTS +r Right -u UserOrGroup [-m \\Computer] [-e
Entry]
NTRIGHTS -r Right -u UserOrGroup [-m \\Computer] [-e
Entry]
Key:
Privilege Meaning
This command requires Administrator rights and does not run on NT 4.0
* = Privilege valid in Windows 2003 and above only
Example:
Allow members of the local Users group to logon locally
ntrights -u Users +r SeInteractiveLogonRight
Revoke the above
ntrights -u Users -r SeInteractiveLogonRight
Specifically deny local logon rights to jdoe
ntrights -u jdoe -r SeDenyInteractiveLogonRight
"What distinguishes the majority of men from the few is their inability to act according
to their beliefs." Henry Miller
Related commands:
CACLS Change file permissions
Q267553 Reset User Rights in Group Policy
Q315276 Set Logon User Rights by Using the NTRights
PATH
Display or set a search path for executable files
Syntax
PATH pathname [;pathname] [;pathname] [;pathname]...
PATH
PATH ;
Key
pathname : drive letter and/or folder
; : the command 'PATH ;' will clear the path
PATH without parameters will display the current path.
The %PATH% environment variable contains a list of folders. When a command is
issued at the CMD prompt, the operating system will first look for an executable file in
the current folder, if not found it will scan %PATH% to find it.
Use the PATH command to display or change the list of folders stored in the
%PATH% environment variable.
To view each item on a single line use this batch script:
::viewpath.cmd
@echo off
::echo the path one line at a time
for %%G in ("%path:;=" "%") do @echo %%G
To add items to the current path, include %PATH% in your new setting.
For Example:
PATH=%PATH%;C:\Program Files\My Application
Permanent Changes
Changes made using the PATH command are NOT permanent, they apply to the
current CMD prompt only and remain only until the CMD window is closed.
T o permanently change the PATH use
Control Panel, System, Environment, System Variables
Control Panel, System, Environment, User Variables
You can also do this at the command line with SETX
Changing a variable in the Control Panel will not affect any CMD prompt that is
already open.
Only new CMD prompts will get the new setting.
To change a system variable you must have administrator rights
The %PATH% variable is set as both a system and user variable, the 2 values are
combined to give the PATH for the currently logged in user. This is explained in full by
MS Product Support Article Q100843
If your system has an AUTOEXEC.BAT file then any PATH setting in
AUTOEXEC.BAT will also be appended to the %PATH% environment variable. This
is to provide compatibility with old installation routines which need to set the PATH.
All other commands in AUTOEXEC.BAT are ignored.
Terminology
For a file stored as:
C:\Program Files\Adobe\Acrobat.exe
The Drive is:
C:
The Filename is:
Acrobat.exe
The Path is:
\Program Files\Adobe\
The Pathname is:
\Program Files\Adobe\Acrobat.exe
The Full Pathname is
C:\Program Files\Adobe\Acrobat.exe
"If you do not love your job, change it. Instead of pushing paper, push ideas. Instead
of sitting down, stand up and be heard. Instead of complaining, contribute. Don't get
stuck in a job description" Microsoft job advert
Related Commands:
SET Display, set, or remove environment variables.
PATHMAN Resource Kit utility modify system and user paths. Pathman can
resolve duplicate characters, and can improve performance by removing duplicate
paths. For details see Pathman.wri in the resource kit.
Equivalent Linux BASH commands:
env Display, set, or remove environment variables
CDPATH Environment variable
MAILPATH Environment variable
PATH Environment variable
PATHPING (Windows 2000)
Trace route and provide network latency and packet loss for each router and link in
the path.
Syntax
PATHPING [-n] [-h max_hops] [-g host_list] [-p period]
[-q num_queries] [-w timeout] [-t] [-R] [-r]
target_name
Key
-n Don't resolve addresses to hostnames
-h max_hops Max number of hops to search, default=30
-g host_list Loose source route along host-list
up to 9 hosts in dotted decimal notation,
separated by spaces.
-p period Wait between pings, default=250
(milliseconds)
-q num_queries Number of queries per hop, default=100
-w timeout Wait timeout for each reply, default is
3000 (milliseconds)
-T Test each hop with Layer-2 priority tags
(QoS connectivity)
-R Test if each hop is Resource Reservation
Protocol (RSVP) aware
BROWSTAT Get domain, browser and PDC info
IPCONFIG IP Configuration
NETSTAT Display networking statistics (TCP/IP)
PING Test a network connection
TRACERT Trace route to a remote host
Equivalent Linux BASH commands:
ping Test a network connection
trace Find the IP address of a remote host
PAUSE
Pause the execution of a batch file
Syntax
PAUSE
displays the message "Press any key to continue . . ."
To suppress the message use PAUSE >nul
"Advertising may be described as the science of arresting the human intelligence
long enough to get money from it." Stephen Leacock
Related commands
TIMEOUT Delay that allows the user to press a key and continue immediately.
Equivalent Linux BASH commands:
read p "press any key to continue"
sleep Delay for a specified time
PERMS.exe (Windows 2000)
Display a user’s ACL access permissions for a file. Output from PERMS may be
misleading in cases where a user has inherited permission through membership of
an NT workgroup. [First released in the NT4 Resource Kit]
Syntax
PERMS [account] [path] options
Key
account : username or [domain\|computer\]username
/s : include subfolders
Access Description
R Read file/folder.
W Write file/folder.
X Execute file.
P Change Permission.
O Take Ownership.
A General All
- No Access
CACLS Display or modify Access Control Lists (ACLs) for files and folders
SHOWACL Show file Access Control Lists (win 2000)
SUBINACL Change an ACL's user/domain (use when the file owner has moved to a
new domain)
ATTRIB Display or change file attributes
XCACLS Display or modify Access Control Lists (ACLs) for files and folders
Equivalent Linux BASH commands:
chmod Change access permissions
chown Change file owner and group
Monitor (Resource Kit)
Control Performance Monitor logging from the command line, this removes the
graphical workload of Perfmon from the server making the reported values more
accurate.
The Data Logging Service (DATALOG.EXE) is a Windows NT Service that performs
the same function as the Performance Monitor Alert and Logging facility.
Syntax
MONITOR setup
MONITOR %SYSTEMROOT%\SYSTEM32\MyLogSet.PMW
MONITOR start
MONITOR stop
Key
SETUP is needed once only to install the service.
Use START and STOP to Start/Stop logging.
Save .PMW files from the PERFMON GUI under the file menu.
Any graphical process running on a server will affect performance to some degree,
most interactive programs (in particular the command prompt) will run faster when
minimised.
Monitoring Hard Drives
To enable performance counters run:
diskperf y
This enables the objects and counters for logical and physical disks .
To enable performance counters for a striped array run:
diskperf ye
To disable performance counters run:
diskperf N
or set in the registry
HKLM\SYSTEM\CurrentControlSet\Services\PerfDisk\Performance
REG_DWORD 'Disable' = 1
Monitoring drive performance with perfmon will itself have a small impact on
performance, any changes require a reboot and any errors will be logged in the
event viewer. Disable perfmon when tuning is complete.
Alternatives:
Monitoring a server by running Performance Monitor from a remote workstation is a
good alternative to the Data Logging Service that still gives accurate figures (and you
don't need the resource kit to do this).
"Quality in a product or service is not what the supplier puts in. It is what the
customer gets out and is willing to pay for" Peter Drucker
Related Commands:
LOGEVENT Write text to the event viewer.
PING
Test a network connection if successful, ping returns the ip address.
Syntax
PING [options] destination_host
Options
-w timeout Timeout in milliseconds to wait for each
reply.
-i TTL Time To Live.
-v TOS Type Of Service.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-t Ping the destination host until
interrupted.
-l size Send buffer size.
-f Set Don't Fragment flag in packet.
-r count Record route for count hops.
-s count Timestamp for count hops.
-j host_list Loose source route along host_list.
-k host_list Strict source route along host_list.
destination_host The name of the remote host
A response of "Request timed out" means there was no response to the ping attempt
in the default time period of one second.
If the latency of the response is more than one second. Use the w option on the ping
command to increase the timeout. For example, to allow responses within five
seconds, use ping w 5000.
A successful PING does NOT always return an %errorlevel% == 0
Therefore to reliably detect a successful ping pipe the output into FIND and look for
the text "TTL"
Note that "Reply" in the output of PING does not always indicate a positive response.
You may receive a message from a router such as: Reply from 192.168.1.254:
Destination Net Unreachable.
Four steps to test an IP connection with ping:
1) Ping the loopback address to verify that TCP/IP is installed and configured
correctly on the local computer.
PING 127.0.0.1
2) Ping the IP address of the local computer to verify that it was added to the network
correctly.
PING IP_address_of_local_host
3) Ping the IP address of the default gateway to verify that the default gateway is
functioning and that you can communicate with a local host on the local network.
PING IP_address_of_default_gateway
4) Ping the IP address of a remote host to verify that you can communicate through a
router.
PING IP_address_of_remote_host
Examples
PING -n 1 -w 7500 Server_06
TRACERT Trace route to a remote host
IPCONFIG IP Configuration
PATHPING Route Tracing tool (Windows 2000)
RPings RPC Connectivity Verification Tool (Win 2K but works with NT)
Q115388 Resolving IP Address with Leading Zero
FreePing Freeware Windows GUI Ping
WebPing Ping from any web browser
Equivalent Linux BASH commands:
ping Test a network connection
trace Find the IP address of a remote host
POPD
Change directory back to the path/folder most recently stored by the PUSHD
command.
POPD will also remove any temporary drive maps created by PUSHD
Syntax
POPD
For example
c:\Program Files> PUSHD c:\utils
c:\utils> PUSHD c:\WINNT
c:\Winnt>
c:\Winnt> POPD
c:\utils>
c:\utils> POPD
c:\Program Files>
If Command Extensions are disabled PUSHD and POPD will not create temporary
drive letters.
"It's amazing how low you go to get high" John Lennon
Related Commands
PUSHD Change the current directory/folder and store the previous folder/path
CD Change Directory, select a Folder (and drive)
Equivalent Linux BASH commands:
export Set an environment variable
PORTQRY (Download)
Port Query Display the status of TCP and UDP ports, troubleshoot TCP/IP
connectivity and security, return LDAP base query info, SMTP, POP3, IMAP4 status,
enumerate SQL Server instances (UDP port 1434), Local ports, local services
running (and the DLL modules loaded by each).
Portqry.exe can query a single port, a list of several ports, or a sequential range of
port numbers.
Syntax
Local Mode:
Local Mode gives detailed data on local system's ports
-v Verbose output
Interactive Mode:
An alternative to command line mode
portqry -i [-options]
For help with -i run portqry.exe and then type 'help' <enter>
Examples
portqry -local
portqry -local -l MyLogFile.txt -v
portqry -wpid 1272 -wt 5 -l MyLogFile.txt -y -v
portqry -wport 53 -l dnslog.txt
portqry -n myserver.com -e 25
portqry -n 10.0.0.1 -e 53 -p UDP -i
portqry -n host1.dev.reskit.com -r 21:445
portqry -n 10.0.0.1 -o 25,445,1024 -p both -sp 53
portqry -n host2 -cn !my community name! -e 161 -p udp
Notes
PortQry runs on Windows 2000 and later systems For best results run local
commands in the context of local administrator.
Port to process mapping may not be available on all systems.
Defaults: TCP, port 80, no log file, slow link delay off
Hit CtrlC to terminate prematurely.
Related Commands:
nslookup Lookup IP addresses on a NameServer
NETSH diag Connect to TCP port
WMIC PORTCONNECTOR Access Physical port
Q310099 Description of PortQry
Q832919 PortQry Version2
Q310456 Use PortQry to Troubleshoot Active Directory Connectivity
Q310298 Use PortQry to Troubleshoot MS Exchange
Equivalent Linux BASH commands:
PRINT
Print a file or files to a local or network printer.
syntax
PRINT [/D:device] [pathname(s)]
key
device : either a local printer (LPTx, COMx )
or a network printer by its sharename
(\\servername\print_share)
To delete a print job:
Use Control Panel, Printers (GUI) or use
NET PRINT job# /DELETE
It is possible to delete the relevant .spl and .shd files from
%SystemRoot%\system32\spool\PRINTERS
but the .spl file for a print job at the top of the print queue cannot be deleted.
Printing requires the Spooler service to be running
Related Commands:
NET PRINT View and Delete print jobs
Print Migrator Microsoft tool for moving print queues.
Defptr Default Printer. (Win 2K ResKit)
PRNCNFG Display, configure or rename a printer
WMIC PRINTER Set printing options through WMI.
Print Notification this is set under Control Panel, Printers, File, Server Properties,
Advanced
Q246868 New TCP/IP Printing Options in the Windows Standard Port Monitor
Q234270 Group Policies to Control Printers
prncnfg.vbs
prndrvr.vbs
prnjobs.vbs
prnmngr.vbs
prnport.vbs
prnqctl.vbs
pubprn.vbs
Equivalent Linux BASH commands:
printf Format and print data
PRNCNFG.VBS (XP and .Net)
Display, configure or rename a printer.
Parameters
-s RemoteComputer
The name of the remote computer that manages the
printer.
-p PrinterName
The name of the printer.
-u UserName -w Password
An account with permission to connect WMI services to
the computer
that hosts the printer. e.g. A member of the
Administrators group.
-r PortName
The port to which the printer is connected.
If this is a parallel or a serial port, then use the
ID of the port
(for example, LPT1 or COM1). If this is a TCP/IP port,
then use the
port name that was specified when the port was added.
-l Location
The printer location, such as "Copier Room."
-m Comment
A comment string.
-h ShareName
The share name.
-f SeparatorText
A file that contains the text that appears on the
separator page.
-y DataType
Data types that the printer can accept.
-st StartTime
Specify a time of the day after which the printer is
available.
If you send a document to a printer when it is
unavailable, the
document is held (spooled) until the printer becomes
available.
Specify time as a 24-hour clock. e.g. 2300
-ut EndTime
Specify a time of the day after which the printer is
no longer available.
-o Priority
A priority that the spooler uses to route print jobs.
A print queue with a higher priority receives all its
jobs before any queue with a lower priority.
-i DefaultPriority
The default priority assigned to each print job.
{+ | -}shared
Is this printer is shared on the network.
{+ | -}direct
Is the document to be sent directly to the printer
without being spooled.
{+ | -}published
Is this printer to be published in Active
Directory.
If you publish a printer, other users can search
for it based on its location
and capabilities, such as color printing and
stapling.
{+ | -}hidden
Reserved function.
{+ | -}rawonly
Are only raw data print jobs to be spooled on
this queue.
{+ | -}queued
Do not begin to print until after the last page
of the document is spooled.
The printing program is unavailable until the
document has finished printing.
This option ensures that the whole document is
available to the printer.
{+ | -}keepprintedjobs
Retain documents after they are printed.
Allows a user to resubmit a document to the
printer from the print queue.
{+ | -}workoffline
Allow sending print jobs when computer is not
connected to the network.
{+ | -}enabledevq
Print jobs that do not match the printer setup
(for example, PostScript files
spooled to non-PostScript printers) should be
held in the queue rather than
being printed.
{+ | -}docompletefirst
Allocate jobs to a printer as soon as thay are
spooled.
If this option is disabled, the spooler always
sends higher priority
jobs to their respective queues first.
You should enable this option if you want to
maximize printer efficiency
at the cost of job priority.
{+ | -}enablebidi
Send bi-directional status information to the
spooler.
PRINT Print a text file
CON2PRT Connect or disconnect a Printer
NET VIEW to view a list of printers
NET PRINT View and Delete print jobs
PRNDRVR Add, delete or list printer drivers.
PRNJOBS Pause, resume, cancel, or list print jobs
PRNMNGR Add, delete, or list printers / connections, set the default printer.
PRNPORT Create, delete, or list TCP/IP printer ports, change port configuration.
PRNQCTL Print a test page, pause or resume a printer, clear a printer queue.
RUNDLL32 Install/Remove Printers (plus advanced options)
WMIC PRINTER Set printing options through WMI.
Q246868 New TCP/IP Printing Options in the Windows Standard Port Monitor
WSH Commands:
Add printer .AddPrinterConnection
Add Network printer .AddWindowsPrinterConnection
List printers .EnumPrinterConnections
Set default printer .SetDefaultPrinter
Equivalent Linux BASH commands:
lpc Line printer control program
lpr Off line print
lprint Print a file
lprintd Abort a print job
lprintq List the print queue
lprm Remove jobs from the print queue
PRNMNGR (XP and .Net)
Display, add, remove or set default printer.
Syntax
PRNMNGR [-options] [-s server][-p printer_name][-m
driver model]
[-r port][-u user_name][-w password]
Options
-l list printers
CON2PRT Connect or disconnect a Printer
NET VIEW \\Printserver to view a list of available printers
NET PRINT View and Delete print jobs
PRNCNFG Add, delete, or list printers / connections, set the default printer.
PRNDRVR Add, delete or list printer drivers.
PRNJOBS Pause, resume, cancel, or list print jobs
PRNPORT Create, delete, or list TCP/IP printer ports, change port configuration.
PRNQCTL Print a test page, pause or resume a printer, clear a printer queue.
PRINT Print a text file
RUNDLL32 Install/Remove Printers (plus advanced options)
WMIC PRINTER Set printing options through WMI.
Q246868 New TCP/IP Printing Options in the Windows Standard Port Monitor
WSH Commands:
Add printer .AddPrinterConnection
Add Network printer .AddWindowsPrinterConnection
List printers .EnumPrinterConnections
Set default printer .SetDefaultPrinter
Equivalent Linux BASH commands:
lpc Line printer control program
lpr Off line print
lprint Print a file
lprintd Abort a print job
lprintq List the print queue
lprm Remove jobs from the print queue
PROMPT
Change the cmd.exe command prompt.
Syntax
PROMPT [text]
Key
text : a text string.
The prompt text can be made up of normal characters and the following special
codes:
$A & (Ampersand)
$B | (pipe)
$C ( (Left parenthesis)
$D Current date
$E Escape code (ASCII code 27)
$F ) (Right parenthesis)
$G > (greater-than sign)
$H Backspace (erases previous character)
$L < (less-than sign)
$M Display the remote name for Network drives
$N Current drive
$P Current drive and path
$Q = (equal sign)
$S (space)
$T Current time
$V Windows NT version number
$_ Carriage return and linefeed
$$ $ (dollar sign)
$+ Will display plus signs (+) one for each level of the
PUSHD directory stack
Examples
Display the UNC path whenever you are using a network drive (mapped with NET
USE)
PROMPT $M$_$P$G
Simulate an HPUX prompt with the computername and the current folder on
separate lines:
PROMPT=$p$_%username%@%computername%:.
Restore the default prompt:
PROMPT $P$G
PROMPT is implemented as a hidden NT environment variable called PROMPT,
try doing:
ECHO %prompt%
knowing this you can force a permanent change in the CMD prompt for all sessions
by setting a permanent environment variable with the appropriate prompt text.
e.g. SETX PROMPT $M$_$P$G
You can also create specific shortcut's to the command prompt like this:
CMD /K PROMPT $M$_$P$G
If Command Extensions are disabled the commands $M and $+ are not supported.
Related Commands:
SETX Set an environment variable permanently.
Equivalent Linux BASH commands:
The BASH prompt is set by the BASH variable $PROMPT_COMMAND
env Display, set, or remove environment variables
export Set an environment variable
PsExec (part of PsTools download PsExec)
Execute a commandline process on a remote machine.
Syntax
psexec \\computer[,computer[,..] [options] command
[arguments]
Options:
computer The computer on which psexec will run command.
Default = local system
To run against all computers in the current
domain enter "\\*"
Examples:
Launch an interactive command prompt on \\workstation64:
psexec \\workstation64 cmd
Execute IpConfig on the remote system, and display the output locally:
psexec \\workstation64 ipconfig /all
Copy the program test.exe to the remote system and execute it interactively:
psexec \\workstation64 -c test.exe
Execute a program that is already installed on the remote system:
psexec \\workstation64 "c:\Program Files\test.exe"
Run Internet Explorer on the local machine but with limiteduser privileges:
psexec -l -d "c:\program files\internet explorer\iexplore.exe"
Related Commands:
RUNAS Execute a program under a different user account
Equivalent Linux BASH command:
xon start an X program on a remote machine
PsFile (part of PsTools download PsFile)
Show files opened remotely, or close an open file (kill file locks)
Syntax
psfile [\\Computer [-u User [-p Passwd]]] [[Id | path]
[-c]]
Options:
Unlike the NET FILE command, PsFile does not truncate long filenames.
Examples:
List all the files on \\workstation64 that have been opened remotely:
psfile \\workstation64
Related Commands:
NET FILE Display all the open shared files on a server and the lockid
Equivalent Linux BASH commands:
flock apply or remove an advisory lock on an open file
fcntl manipulate file descriptor
dnotify filemonitoring mechanism
inotify filemonitoring mechanism
PsGetSid (part of PsTools download PsGetSid)
Display the SID of a computer or a user.
Syntax
psgetsid [\\computer[,computer[,...] | @get_file] [-u
user [-p passwd]]] [account|SID]
Options:
Examples:
Get the SID of \\workstation64:
psgetsid \\workstation64
Get the domain SID for the domain: Niamod
psgetsid Niamod
Get the SID for the currently loggedin user
psgetsid %username%
Related Commands:
SYSTEMINFO List system configuration
PsInfo (part of PsTools download PsInfo)
List information about a system including the type of installation, kernel build,
registered organization, owner, processor details, physical memory and the system
install date.
Syntax
psinfo [\\computer[,computer[,..]] [options] [filter]
Options:
List disc information about \\workstation64:
psinfo \\workstation64 -d
echo %errorlevel%
Related Commands:
PsGetSid Display the SID of a computer or a user
SYSTEMINFO List system configuration
Equivalent Linux BASH command:
cat /proc/*
PsKill (part of PsTools download PsKill)
Kill processes by name or process ID
Syntax
pskill [- ] [-t] [\\computer [-u user] [-p passwd]]
<process name | process id>
Options:
process id/name
The process or processes to be killed.
Kill all instances of notepad.exe running on \\workstation64:
pskill \\workstation64 notepad
Related Commands:
PsList List detailed information about processes
The process button of Task Manager in Windows will also identify the process ID
(PID)
PsSuspend Suspend processes (so they can be continued at a later point in time)
KILL Remove a program from memory
Equivalent Linux BASH command:
kill Stop a process from running, either via a signal or forced termination
PsList (part of PsTools download PsList)
List detailed information about processes
Syntax
pslist [-?] [-t] [-m] [-x] [\\computer [-u user] [-p
passwd]] [name | pid]
Options:
List all processes running on \\workstation64:
pslist \\workstation64
Related Commands:
PsKill Kill processes by name or process ID
TASKLIST List running applications and services
Windows Task Manager List of running process IDs (PID)
PerfMon Monitoring tool
Equivalent Linux BASH commands:
ps Process status, information about processes running in memory.
top Process viewer, find the CPUintensive programs currently running.
PsLoggedOn (part of PsTools download PsLoggedOn)
See who is logged onto a computer, either locally or remotely
Syntax
psloggedon [- ] [-l] [-x] [\\computer | username]
Options:
List all processes running on \\workstation64:
pslist \\workstation64
Related Commands:
net session List or disconnect user sessions (Local machine only)
Equivalent Linux BASH commands:
who Print who is currently logged in
PsLogList (part of PsTools download PsLogList)
Event log records
Syntax
psloglist [- ] [\\computer[,computer[,...] | @file
[-u user [-p passwd]]] [-s [-t delim]]
[-m #|-n #|-h #|-d #|-w]
[-c][-x][-r][-a mm/dd/yy][-b mm/dd/yy]
[-f filter] [-i ID[,ID[,...] | -e
ID[,ID[,...]]]
[-o event source[,event source][,..]]]
[-q event source[,event source][,..]]]
[-l event_log_file] <eventlog>
Options:
computer The computer on which the log resides.
Default=local system
-o event source
Show only records from the specified event
source (e.g. \"-o cdrom\").
-q event source
Omit records from the specified event source or
sources (e.g. \"-q cdrom\").
List everything in the application event log on \\workstation64 from the last 24 hours:
psloglist \\workstation64 -h 24 application
Related Commands:
elogdump Resource Kit event log dump (local machine only)
Equivalent Linux BASH command:
Logs are in plain ascii text
PsPasswd (part of PsTools download PsPasswd)
Change account password
Syntax
pspasswd [[\\computer[,computer[,..] | @file
[-u user [-p passwd]]] Username [NewPassword]
Options:
Change the password for user JDoe on \\workstation64
pspasswd \\workstation64 jdoe password567
Related Commands:
NET USER
Equivalent Linux BASH command:
passwd Modify a user password
PsService (part of PsTools download PsService)
View and control services
Syntax
psservice [\\computer [-u user] [-p passwd]] <command>
<options>
Options:
commands:
query Display the status of a service
config Display the configuration of a service
setconfig Set the start type (disabled, auto, demand)
of a service.
start Start a service
stop Stop a service
restart Stop and then restart a service
pause Pause a service
cont Resume a paused service
depend List the services dependent on the one
specified
security Dump the service's security descriptor
find Search the network for the specified service
Typing a command followed by " " displays the syntax for that command.
Service States:
1 Stopped
2 Start Pending
3 Stop Pending
4 Running
Examples:
Restart the spooler service on \\server64
psservice \\server64 restart spooler
Related Commands:
NET START/STOP
SC Service control
PsShutdown (part of PsTools download PsShutdown)
Initiate a shutdown/reboot of a local or remote computer, logoff a user, lock a system.
Syntax
psshutdown [[\\computer[,computer[,..] | @file [-u user
[-p passwd]]]
-s|-r|-h|-d|-k|-a|-l|-o
[-f] [-c] [-t nn|h:m] [-n s] [-v nn]
[-e [u|p]:xx:yy] [-m "message"]
Options:
computer The computer on which the user account resides.
Default=local system
a wildcard (\\*), will affect all computers in
the current domain.
-e [u|p]:xx:yy
Shutdown reason code, 'u' = user, 'p'= planned
shutdown.
xx is the major reason code (must be less than
256)
yy is the minor reason code (must be less than
65536)
Reboot \\workstation64 as part of an OS upgrade
psshutdown \\workstation64 -r -e p:2:3
Related Commands:
SHUTDOWN With full list of reason codes
Equivalent Linux BASH command:
shutdown Shutdown or restart linux
PsSuspend (part of PsTools download PsSuspend)
Suspend processes on the local or a remote system.
Syntax
pssuspend [- ] [-r] [\\computer [-u user] [-p passwd]]
<process name | process id>
Options:
process id/name
The process or processes to suspend or resume.
Suspend the notepad process on \\workstation64
pssuspend \\workstation64 notepad
Related Commands:
PsKill Kill processes by name or process ID
PUSHD
Change the current directory/folder and store the previous folder/path for use by the
POPD command.
Syntax
PUSHD pathname
Key
pathname - the folder to make 'current' (UNC names
accepted)
Example
c:\Program Files> PUSHD c:\utils
c:\utils>
c:\utils> POPD
c:\Program Files>
Temporary drive letters are allocated in reverse alphabetical order
so if Z: is free it will be used.
If Command Extensions are disabled the PUSHD command will not accept a network
(UNC) path.
"One of the phrases that kept running through the conversation was 'pushing the
outside of the envelope' The envelope was a flight test term referring to the limits of a
particular aircraft" Tom Wolfe (The Right Stuff)
Related commands
CD Change directory
CMD UNC options
PROMPT Display the level of the PUSHD stack
Equivalent Linux BASH commands:
export Set an environment variable
QGREP (Windows 2000 Resource Kit)
Search file(s) for lines that match a given pattern.
Syntax
QGREP [options] [-e string] [-f file] [-i file]
[strings] [files]
key:
-L Search strings literally.
-X Treat search strings as regular expressions.
-B Match pattern at beginning of line.
-E Match pattern at end of line.
-y Treat upper and lower-case as equivalent.
Find either arg1 or arg2 in FileName:
qgrep "arg1 arg2" FileName
Find arg1 arg2 in FileName:
qgrep e "arg1 arg2" FileName.
White space separates search strings unless the argument is prefixed with e.
QGREP "all out" x.y
means find either "all" or "out" in x.y, while
QGREP e "all out" x.y
means find "all out".
grep is simply an odd concatenation of the phrase "grab regular expression"
Related Commands:
MUNGE Find and Replace text within file(s)
Equivalent Linux BASH commands:
grep Search file(s) for lines that match a given pattern
RASDIAL (Dial Up Networking)
Manage RAS/DUN connections.
The default location for PhoneBook entries is \%SystemRoot%\system32\ras\
"If advanced switching technology had not been developed and the telephone still
had one operator for every 120 of some 100 million telephones, it would take
2,400,000 telephone operators (on three shifts) John R. Pierce
Related Commands:
RASPHONE Manage RAS connections
Connection Manager Administration Kit VPN connections (2003 Resource Kit)
RASMON Windows 2000 GUI Resource Kit tool
CHECKRAS SMS support tools
RASPHONE (Dial Up Networking)
Manage Remote Access Service (RAS) connections.
This is a part of the DialUp Networking service, typically used to connect a PC to an
Internet Service Provider.
OPTIONS
-a : Add new PhoneBook entry
-e : Edit an existing PhoneBook entry
-c : Clone an existing PhoneBook entry
-r : Delete/remove an existing PhoneBook entry
-v : Disable - 'grey out' the option to rename the
PhoneBook_entry
To use this command requires that Dial Up Networking Service be installed (via
Control Panel Networking)
The default location for PhoneBook entries is %SystemRoot%\System32\ras\
"Someone invented the telephone, And interrupted a nation's slumber, Ringing wrong
but similar numbers" Ogden Nash
Related Commands:
RASDIAL Manage RAS connections
Connection Manager Administration Kit VPN connections (2003 Resource Kit)
RASMON Windows 2000 GUI Resource Kit tool
CHECKRAS SMS support tools
RECOVER
Recover a damaged file from a defective disk.
SYNTAX
RECOVER [drive:][path]filename
Recover is designed to help in the case of hardware failure. When a drive fails the
failure is not always total, in other words you may be able to read some of the files
but not others, and some files will be only partly readable.
The data on a disk is stored in tracks and sectors in an almost random manner. Data
stored in a bad sectors cannot be read.
RECOVER reads a file sector by sector and recovers data from the good sectors.
You must specify a file.
Recover will not allow you to undelete a file.
Recover files one at a time; move each file to a good disk before editing to reenter
missing information.
In the case of complex documents you will probably lose formatting/graphics but will
retain raw text.
"Whom the gods love dies young Menander 300 BC
Related Commands:
CHKDSK Check Disk check and repair disk problems
Equivalent Linux BASH commands:
cksum Print CRC checksum and byte counts (can detect problems but not fix them)
REG.exe (NT Resource Kit, W2K Support Tools, XP)
Read, Set or Delete registry keys and values
The REG command was updated in NT Resource Kit supplement 2 the syntax for
Win 2K/XP is different.
SYNTAX:
Key:
RegistryPath : [ROOTKEY\]Key[\'ValueName']
where ROOTKEY is one of
HKLM = hkey_Local_machine (default)
HKCR = hkey_classes_root
HKCU = hkey_current_user
HKU = hkey_users
Examples
An example of each command is available from the command line
REG QUERY /?
REG ADD /?
REG UPDATE /?
REG DELETE /?
REG COPY /?
REG SAVE /?
REG BACKUP /?
REG RESTORE /?
REG LOAD /?
REG UNLOAD /?
REG FIND /?
REG DUMP /?
REG COMPARE /?
"The way to a mans heart is through his stomach" Fanny Fern (writer)
Related Commands:
SETX Set environment variables permanently, can also read a registry key and
write the value to a text file.
REGEDIT Load Registry settings from a .REG file
REGEDT32.EXE Edit the registry including Security and Auditing Options
Dureg Registry Size Estimator. (Win 2K ResKit)
JsiFaq Tip 6671 How to include a quote mark (")
REGEDIT
Import, export or delete registry settings from a text (.REG) file
Syntax
Export the Registry (all HKLM plus current user)
REGEDIT /E pathname
Silent import
REGEDIT /S pathname
Key
/E : Export
/S : Silent Import
How to add keys and values from the registry:
Create a text file like this:
REGEDIT4
[HKEY_CURRENT_USER\SomeKey]
"SomeStringValue"="Hello"
When double clicking this .reg file the key and value will be added.
Alternatively run REGEDIT MYKEY.REG from the command line.
How to delete keys and values from the registry:
Create a reg file like this, notice the hyphen inside the first bracket
REGEDIT4
[-HKEY_CURRENT_USER\SomeKey]
When double clicking this .reg file the key "SomeKey" will be deleted along with all
string, binary or Dword values in that key.
If you want to just delete values leaving the key in place, set the value you want to
delete = to a hyphen
e.g.
REGEDIT4
[HKEY_CURRENT_USER\SomeKey]
"SomeStringValue"=-
Again double clicking this .reg file will delete the values specified or you can use
REGEDIT /s MyDeleteScript.REG.
Windows XP Registry files.
Under Windows NT all registry scripts start with:
REGEDIT4
Under Windows 2K and XP the first line is:
Windows Registry Editor Version 5.00
To be sure that a .REG script will run under any version of Windows use the earlier
syntax: REGEDIT4.
Compare the Registry of two machines
Windiff is your friend, this simple GUI utility from the resource kit will list all the
differences.
Comments
Within a registry file, comments can be preceded by "; "
e.g.
;
; Turn the NUMLOCK on at login
;
[HKEY_CURRENT_USER\Control Panel\Keyboard]
"InitialKeyboardIndicators"="2"
"I never make stupid mistakes. Only very, very clever ones" John Peel
Related commands:
REGEDT32.EXE Edit the registry including Security and Auditing Options (NT 4)
REG Read, Set or Delete registry keys and values
SET Display, set, or remove Windows NT environment variables
SETX Set environment variables permanently
WMIC REGISTRY Set registry options through WMI.
Q322756 How to backup and edit the registry
Dureg Registry Size Estimator. (Win 2K ResKit)
XP Registry Keys Commonly tweaked user interface settings
registry
; Sanity.REG
; Windows XP Sanity check
; If you edit this file ensure all comment lines are prefixed
with ; so that REGEDIT will ignore them
Windows Registry Editor Version 5.00
; - - - Section1 - - - - MS Explorer - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - -
;
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\P
olicies\Explorer]
;
; - - - Section2 - - - - Explorer\Advanced - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - -
;
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\E
xplorer\Advanced]
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\P
olicies\System]
;
; - - - Section 4 - - - - Policy - Add-Remove Programs
restrictions - - - - - - - - - - - - - - - - -
;
; These keys make sure you can uninstall anything
;
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\P
olicies\Uninstall]
"NoAddRemovePrograms"=dword:00000000
"NoRemovePage"=dword:00000000
"NoAddPage"=dword:00000000
"NoWindowsSetupPage"=dword:00000000
"NoAddFromCDorFloppy"=dword:00000000
"NoAddFromInternet"=dword:00000000
"NoAddFromNetwork"=dword:00000000
"NoServices"=dword:00000000
"NoSupportInfo"=dword:00000000
;
; - - - Section 5 - - - - Control Panel - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - -
;
; Dont hide any cpanel applets see Q207750
[HKEY_CURRENT_USER\Control Panel\don't load]
"appwiz.cpl"=-
; Start menu speed
[HKEY_CURRENT_USER\Control Panel\Desktop]
"MenuShowDelay"="400"
;
; - - - Section 6 - - - - Console - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
;
[HKEY_CURRENT_USER\Console]
; Allow copy and paste from the command line.
"QuickEdit"=dword:00000001
;
; - - - Section 7 - - - - Tip Of the Day - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - -
;
; Turn off the 'Tip Of the Day'
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\E
xplorer\tips]
"Show"=dword:00000000
REGSVR32
Register or unregister a DLL.
Syntax
REGSVR32 [/U] [/S] [/C] [/I:[Command_Line]] DLL_Name
Key
/u Unregister Server.
/s Silent - no dialogue boxes.
/c Console output.
/n Don't call DllRegisterServer
/i Call DllInstall (or DllUninstall if /u is
specified)
Command_Line An optional command line for DllInstall
Examples
Unregister / Disable image viewer (wmf file vulnerability)
REGSVR32 /u shimgvw.dll
Enable image viewer:
REGSVR32 shimgvw.dll
Unregister / Disable XP Zip folders and CAB View:
REGSVR32 /u C:\Windows\System32\zipfldr.dll
REGSVR32 /u C:\Windows\System32\cabview.dll
Register/Enable XP Zip folders and CAB View:
REGSVR32 C:\Windows\System32\zipfldr.dll
REGSVR32 C:\Windows\System32\cabview.dll
Register DAO 3.6 (DLL library):
REGSVR32 "C:\Program Files\Common Files\Microsoft Shared\DAO\DAO360.DLL"
It costs nothing to register and will only take a moment...
Related Commands:
Delsrv unregister a service with the Services Control Manager. (Win 2K ResKit)
MSIEXEC Microsoft Windows Installer
RUNDLL32 Run a DLL command
Microsoft DLL Database which software installed a specific version of a DLL
Q249873 Regsvr32 usage and error messages
SUMMARY
This article describes how to use a script to change permissions defined in a registry key from
a command prompt by using the Regini.exe utility included with Microsoft Windows NT Server 4.0
Resource Kit. The Resource Kit is a separate product that can be purchased from Microsoft.
MORE INFORMATION
CAUTION: When you use a script to change registry permissions, you replace the entire set
of current permissions defined in a registry key. For example, if you have four types of users
whose permissions are defined in a particular registry key, and you create and run a script file
that changes the permissions for only three of the four types of users, the information about the
fourth type is deleted.
To use a script to change permissions defined in a registry key from a command prompt:
1. Install the latest version of the Windows NT Server 4.0 Resource Kit.
Create a script file that contains the change commands:
a. Start any text editor (such as Notepad).
Type the registry keys and the appropriate permissions in the
following format
\Registry\hive\key [permissions]
where hive is the name of the registry hive, key is the name of
the registry key, and [permissions] is the binary number format
of the permissions.
NOTE: Use the -m option only when you edit the registry of a remote
computer. Be sure to include the entire path to the script file.
Reference to Registry Hives and Binary Number Representation for Permissions
You can use the Regdmp utility, also included with the Resource Kit, to obtain the current
permissions of a registry key in the binary number format.
REM
In a batch file
REM signifies a comment or REMARK
adding :: at the start of a line has a similar effect
For example:
@ECHO OFF
::
:: First comment
::
REM Second comment
REM
::
Although you can use rem without a comment to add vertical spacing to a batch file,
you can also use blank lines. The blank lines are ignored when processing the batch
program.
The doublecolon is not documented as a comment command, it is a special case of
a CALL label that acts like a comment. The pro's and cons of each method are listed
below.
Bugs
There are problems using a :: comment within an IF or FOR code bracket
e.g.
@echo off
FOR /L %%i IN (1,1,10) Do (
Echo before comment
:: Some comment
Echo after comment
)
The above will return the error :: was unexpected at this time.
In the script below the DIR command will set an %errorlevel%=2 if the file is not
found, but the REM command is then executed successfully and resets
%errorlevel%=0
If you use :: for the comment the errorlevel stays at 2.
DIR nonexistentfile.txt
REM some comment
ECHO %errorlevel%
The problem above was fixed* in Win XP and later service packs of NT 4.
Finally in Windows 2000 and XP a comment like
::%~
or
REM %~ will be interpreted giving the error:
The following usage of the path operator in batchparameter substitution is invalid:
%~
The bottom line on this is that you must test your comments to be sure they will be
ignored as you expect.
Registry Comments
Within a registry file comments can be preceded by "; "
e.g.
;
; Turn the NUMLOCK on at login
;
[HKEY_CURRENT_USER\Control Panel\Keyboard]
"InitialKeyboardIndicators"="2"
FTP Comments
There is no valid comment character for FTP but you can cheat by escaping to the
shell and running REM
e.g.
C:\WORK>type ftpscript
!REM This is a remark
bye
C:\WORK>ftp s:ftpscript
ftp> !REM This is a remark
ftp> bye
C:\WORK>
* The errorlevels set by DIR are different under Windows NT 4 and XP
"First they ignore you, Then they laugh at you, Then they fight you, Then you win"
Gandhi
Equivalent Linux BASH commands:
### Comment / Remark
REN
Rename a file or files.
You cannot specify a different drive or path for `new_filename` use the MOVE
command instead.
Both the source and/or destination may include wildcards.
e.g.
REN *.txt *.xyz
REN c:\MyFile.txt *.xyz
REN c:\MyFile.txt ????.xyz
"We may dig in our heels and dare life never to change, but, all the same, it changes
under our feet like sand under the feet of a sea gazer as the tide runs out. Life is
forever undermining us. Life is forever washing away our castles, reminding us that
they were, after all, only sand and sea water." Erica Jong (Parachutes and Kisses)
Related Commands:
MOVE Move a file from one folder to another
StampMe.cmd Batch file to rename a file to include the current date and time.
Equivalent Linux BASH commands:
mv Move or rename files or directories
REPLACE
Replace or update one file with another
Syntax
REPLACE Source_PathName Destination_path [/A] [/P] [/R]
[/W]
Key
path : The folder where files are to be replaced.
When replacing in all subdirectories (/S ) you cannot ADD files (/A) or restrict to
replacing older files (/U)
"That's the secret to life... replace one worry with another" Charles M. Schulz
Related Commands:
ROBOCOPY
MOVE Move files from one folder to another folder on the same drive
DEL Delete one or more files
COPY Copy one or more files to another location
Equivalent Linux BASH commands:
install Copy files and set attributes
RD
Delete folder(s)
Syntax
RD pathname
RD /S pathname
RD /S /Q pathname
Key
/S : Delete all files and subfolders
in addition to the folder itself.
Use this to remove an entire folder tree.
RD does not support wildcards but you can remove several folders in one command
by listing the pathname to each.
e.g.
RD c:\docs\Jan c:\docs\Feb "c:\My Documents\Mar"
RMDIR is a synonym for RD
"Dying is the most embarrassing thing that can happen to you, because someones
got to take care of all your details". Andy Warhol
Related commands:
CD Create folder(s)
DEL Delete selected files from an entire folder tree
Delrp Delete a file/directory and NTFS reparse points.(Win 2K ResKit)
INUSE updated file replacement utility (may not preserve file permissions)
Equivalent Linux BASH commands:
rmdir Remove folder(s)
rm rf Delete directory recursively
RDISK
Create a Recovery Disk
Syntax
RDISK
RDISK /s
Key
Related Commands:
In Windows 2000 this command is integrated into the system backup utility.
To create a set of NT 4 boot diskettes the command WINNT32 /OX can be used
from the install CD
FORMAT Format a disk
RMTSHARE.exe (Resource kit)
Manage File and Printer shares, local or on a remote server.
Although missing from the Windows 2000 Resource kit, the NT version works fine
under Windows 2000/2003.
Syntax
Display all shares
RMTSHARE \\server
Share a Folder
RMTSHARE \\server\sharename=drive:path [options]
Share a Printer
RMTSHARE \\server\sharename=printername /PRINTER
[options]
options
/USERS:number
/UNLIMITED
/REMARK:"text"
/GRANT user:perm
/REMOVE user
Notes
Either specify /Users to restrict the number of connections
that can be made
OR specify /UNLIMITED
You can include several /GRANTs in a single command line.
Enclose paths that include spaces like this
\\server\"long share name"="c:\long file name"
"How to be green? consume less, share more, enjoy life" Penny Kemp
Related commands:
NET USE connect to a file share
REMOTE Run a command on a remote computer (Resource Kit)
RUNDLL32 Run a DLL command (add/remove print connections)
SHARE List or edit a file share or print share (on any computer)
Equivalent Linux BASH commands:
mount Mount a file system
ROBOCOPY.exe (Resource Kit)
Robust File and Folder Copy.
By default Robocopy will only copy a file if the source and destination have different
time stamps or different file sizes.
Syntax
ROBOCOPY source_folder destination_folder
[file(s)_to_copy] [options]
Key
file(s)_to_copy : A list of files or a wildcard.
(defaults to copying *.*)
Source options
/S : Copy Subfolders
/E : Copy Subfolders, including Empty
Subfolders.
/COPY:copyflag[s] : What to COPY (default is /COPY:DAT).
(copyflags : D=Data, A=Attributes,
T=Timestamps).
(S=Security=NTFS ACLs, O=Owner info,
U=aUditing info).
/COPYALL : Copy ALL file info (equivalent to
/COPY:DATSOU).
/NOCOPY : Copy NO file info (useful with /PURGE).
Copy options
/L : List only - don't copy, timestamp or
delete any files.
/MOV : MOVe files (delete from source after
copying).
/MOVE : Move files and dirs (delete from source
after copying).
Destination options
Logging options
/L : List only - don't copy, timestamp or
delete any files.
/NP : No Progress - don't display % copied.
/LOG:file : output status to LOG file (overwrite
existing log).
/LOG+:file : output status to LOG file (append to
existing log).
Job Options
/JOB:jobname : take parameters from the named JOB file.
/SAVE:jobname : SAVE parameters to the named job file
/QUIT : QUIT after processing command line (to
view parameters).
/NOSD : NO Source Directory is specified.
/NODD : NO Destination Directory is specified.
/IF : Include the following Files.
Advanced options you'll probably never use
/XO : eXclude Older - if destination file
exists and is the same date
or newer than the source - don't bother
to overwrite it.
/XC | /XN : eXclude Changed | Newer files
/XX | /XL : eXclude eXtra | Lonely files and dirs.
An "extra" file is present in destination
but not source,
excluding extras will delete from
destination.
A "lonely" file is present in source but
not destination
excluding lonely will prevent any new
files being added to the destination.
/IS : Overwrite files even if they are already
the same.
:: Copy files from one server to another
ROBOCOPY \\Server1\reports \\Server2\backup *.doc /S /NP
:: List all files over 32 MBytes in size
ROBOCOPY C:\work /MAX:33554432 /L
:: Move files over 14 days old
ROBOCOPY C:\work C:\destination /move /minage:14
:: Note the MOVE option will fail if any files are open and locked.
:: The script below copies data from FileServ1 to FileServ2, the destination holds a
full mirror (all files), when run regularly to synchronize the source and destination,
robocopy will only copy those files that have changed (changed meaning different
time stamp or different size.)
@ECHO OFF
SETLOCAL
SET _source=\\FileServ1\e$\users
SET _dest=\\FileServ2\e$\BackupUsers
SET _what=/COPYALL /B /SEC /MIR
:: /COPYALL :: COPY ALL file info
:: /B :: copy files in Backup mode.
:: /SEC :: copy files with SECurity
:: /MIR :: MIRror a directory tree
SET _options=/R:0 /W:0 /LOG:MyLogfile.txt /NFL /NDL
:: /R:n :: number of Retries
:: /W:n :: Wait time between retries
:: /LOG :: Output log file
:: /NFL :: No file logging
:: /NDL :: No dir logging
ROBOCOPY %_source% %_dest% %_what% %_options%
If either the source or desination are a "quoted long foldername" do not include a
trailing backslash.
In Windows Vista Robocopy is set to become a standard builtin command.
By copying only the files that have changed, robocopy can be used to backup very
large volumes.
To limit the network bandwidth used by robocopy, specify the InterPacket Gap
parameter /IPG:n
This will send packets of 64 KB each followed by a delay of n Milliseconds.
"And bring me a hard copy of the Internet so I can do some serious surfing" Dilbert,
June 1999
Related Commands:
COPY Copy one or more files to another location
XCOPY Copy files and folders
SyncToy Microsoft Powertoy for synchronizing two folders
SI Units Bits and Bytes, bandwidth calculations
Fcopy File Copy for MMQ (copy changed files & compress. (Win 2K ResKit)
Permcopy Copy share & file ACLs from one share to another. (Win 2K ResKit)
Q323275 Copy Security info without copying files (/SECFIX or /COPY:S)
JsiFAQ 0609 Use Robocopy for Directory Replication.
Equivalent Linux BASH command:
rsync Remote file copy (Synchronize file trees)
ROUTE.exe
Manipulate network routing tables. Route packets of network traffic from one subnet
to another by modifying the route table.
Syntax
Change a route:
ROUTE [-f] CHANGE [destination_host] [MASK
subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
Delete a route:
ROUTE [-f] DELETE [destination_host] [MASK
subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
key
-f Clear (flush) the routing tables of all gateway
entries. If this is
used in conjunction with one of the commands,
the tables are
cleared prior to running the command.
destination_host
The address (or set of addresses) that you want
to reach.
subnet_mask_value
The subnet mask value for this route entry.
This defines how many addresses are there.
If not specified, it defaults to
255.255.255.255.
The symbolic names for gateway are looked up in the host name database file
HOSTS.
If the command is PRINT or DELETE. Destination or gateway can be a wildcard ('*'),
or the gateway argument may be omitted.
An IP address mask of 0.0.0.0 means everything. (rather like the *.* wildcard). In
other words it says, “when matching this pattern, don’t worry about matching any of
the bits everything matches.
If Destination_Host contains a * or ?, it is treated as a shell pattern, and only
matching destination routes are printed. The '*' matches any string, and '?' matches
any one char.
Examples:
157.*.1
157.*
127.*
*224*
"Get your kicks on ROUTE 66" Jack Kerouac.
Related Commands:
NETSTATrn Display TCP/IP network connections, routing and protocol statistics
TRACERT Trace route to a remote host
Q140859 Win NT TCP/IP Routing Basics
Equivalent Linux BASH commands:
ping Test a network connection
trace Find the IP address of a remote host
RUNAS (Windows 2000/XP)
Execute a program under a different user account.
Syntax
RUNAS [/profile] [/env] [/netonly] /user:user Program
Key
/profile Option to load the user's profile (registry)
/env Use current environment instead of user's.
/netonly Use if the credentials specified are for RAS
only.
/user Username in form USER@DOMAIN or DOMAIN\USER
(USER@DOMAIN is not compatible with /netonly)
Program The command to execute
Examples:
runas /profile /user:mymachine\administrator CMD
runas /profile /env /user:SCOT_DOMAIN\administrator NOTEPAD
runas /env /user:jDoe@swest.ss64.com "NOTEPAD \"my
file.txt\""
Enter the password when prompted.
RunAs from the Windows explorer GUI
Select an executable file, ShiftRightclick and select Run As..
This option can be hidden by setting
HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\Explor
er
HideRunAsVerb=1
ErrorLevel
The error level returned by RunAs is not consistent between operating systems
In Windows 2000:
success: %ERRORLEVEL%=1
fails: %ERRORLEVEL%=0
In Windows XP:
success: %ERRORLEVEL%=0
fails: %ERRORLEVEL%=1
For Example
VER | find "2000" > nul
IF %errorlevel% EQU 0 GOTO s_2000
::Running XP
RUNAS /user:jDoe@swest.ss64.com "mycommand.exe"
IF %ERRORLEVEL%==0 Echo command succeeded
goto :eof
:s_2000
::Running Windows 2000
RUNAS /user:jDoe@swest.ss64.com "mycommand.exe"
IF %ERRORLEVEL%==1 Echo command succeeded
goto :eof
RunAs Reqires the "Secondary Logon" service to be running.
"Our deepest fear is not that we are inadequate. Our deepest fear is that we are
powerful beyond measure. It is our light, not our darkness, that most frightens us"
Nelson Mandela
Related Commands:
AT Run a command on a remote machine (at a scheduled time)
Aaron Margosis Running with least privilege
joeware.net CPAU (Create Process As User) like RunAs but with an options to
encrypt the password.
PsExec Execute process remotely
Equivalent Linux BASH commands:
SU Switch User
RunDLL32.exe
Run a DLL program. This command is available on all version of Windows from
Win95 onwards, but the DLL's and options available do vary considerably. Many
options are case sensitive.
Syntax
RUNDLL32.EXE dll_name,EntryPoint [options]
Examples
Lock workstation
RUNDLL32.exe user32.dll, LockWorkStation
RUNDLL32 printui.dll,PrintUIEntry /?
Related commands:
Bruce Sanderson Setup shared printers (PrintUI.dll)
MVPS.org Remove or upgrade Java VM
DX21.com A long list of rundll32 options
CON2PRT Connect or disconnect a Printer
PRNCNFG Add, delete, or list printers / connections, set the default printer.
PRNMNGR Add, delete, or list printers / connections, set the default printer.
REGSVR32 Register or unregister a DLL
WMIC PRINTER Set printing options through WMI.
Q189105 Add Printers with No User Interaction (Win 2000)
Q314486 Add Printers with No User Interaction (Win XP)
SC.exe (Resource Kit)
Service Control Create, Start, Stop, Query or Delete any Windows SERVICE. The
command options for SC are case sensitive.
Syntax
SC [\\server] [command] [service_name] [Options]
Key
server : The machine where the service is running
commands:
query [qryOpt] Show status
queryEx [qryOpt] Show extended info - pid, flags
GetDisplayName Show the DisplayName
GetKeyName Show the ServiceKeyName
EnumDepend Show Dependencies
qc Show config - dependencies, full
path etc
start START a service.
stop STOP a service
pause PAUSE a service.
continue CONTINUE a service.
create Create a service. (add it to the
registry)
config permanently change the service
configuration
delete Delete a service (from the registry)
control Send a control to a service
interrogate Send an INTERROGATE control request
to a service
Qdescription Query the description of a service
description Change the description of a service
Qfailure Query the actions taken by a service
upon failure
failure Change the actions taken by a service
upon failure
sdShow Display a service's security
descriptor using SDDL
SdSet Sets a service's security descriptor
using SDDL
qryOpt:
type= driver|service|all
Query specific types of service
state= active|inactive|all
Query services in a particular state
only
bufsize= bytes
ri= resume_index_number (default=0)
group= groupname
Query services in a particular group
ERRORLEVEL 0 = Running
ERRORLEVEL 1 = Stopped or Paused
The NET START command can be used in a similar way to check if a service is
running:
NET START | FIND "Service name" > nul
IF errorlevel 1 GOTO :s_not_running
The service control manager will normally wait up to 30 seconds to allow a service to
start you can modify this time (30,000 milliseconds) in the registry
HKLM\SYSTEM\CurrentControlSet\Control
ServicesPipeTimeout (REG_DWORD)
Some options only take effect at the point when the service is started e.g. the SC
config command allows the executable of a service to be changed. When the service
next starts up it will run the new executable. Config changes requires the current
user to have “permission to configure the service”.
Examples:
SC GetKeyName "task scheduler"
SC GetDisplayName schedule
SC start schedule
SC QUERY schedule
SC QUERY type= driver
SC QUERY state= all |findstr "DISPLAY_NAME STATE"
>svc_installed.txt
SC \\myServer CONFIG myService obj= LocalSystem password=
mypassword
SC CONFIG MyService binPath=c:\myprogram.exe
obj=".\LocalSystem" password=""
Watch out for extra spaces:
SC QUERY state= all Works
SC QUERY sTate =all Fails!
"There is always room at the top" Daniel Webster
Related Commands:
DELSRV Delete NT service
INSTSRV Install an NT service (run under a specific account)
NET manage network resources
NETSVC Commandline Service Controller (Win 2K ResKit)
PsService View and control services
SCLIST Display NT Services
START /HIGH Start a specified program or command.
Svcmon Monitor services and raise an alert if they stop. (Win 2K ResKit)
Svcacls Service ACL Editor (Win 2K ResKit)
SUBINACL Set service permissions
WMIC SERVICE WMI access to services
List of Windows Services
Q251192 Create a Windows Service using SC
Q166819 Control Services Remotely
Q170738 Debugging a Windows NT Service
Equivalent Linux BASH commands:
nice Change job scheduling priority
SCHTASKS
Create, delete, edit, list, start or stop a scheduled task.
Works on local or remote computers.
Syntax:
create_options:
[/S system #remote system (default is
local)
[/U username [/P password]]] #submit job under this
name
[/RU username [/RP password]] #run job under this name
/SC schedule [/MO modifier] #When to run, see below
[/D day] #day =
MON,TUE,WED,THU,FRI,SAT,SUN
[/M months]
#month=JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC.
[/I idletime] #1 - 999 minutes (ONIDLE
task only)
/TN taskname /TR taskrun #Name and pathname for
task
/ST starttime #HH:MM:SS (24 hour)
[/SD startdate] [/ED enddate] # start and end date
"dd/mm/yyyy"
query_del_options:
/F Force delete, ignore warnings even if the task is
currently runnning.
/FO format Output format: TABLE, LIST, CSV
/NH No header
/V Verbose output
Notes:
For MONTHLY schedules give the DAY as a number 1 31 (default=1)
To prompt for the password, specify /RP * or /RP none
The User Account under which the Schedule service runs may require specific file
access permissions, user permissions and drive mappings.
For the system account, /RU username can be written as "", "NT
AUTHORITY\SYSTEM" or "SYSTEM", a Password is not required.
/SC schedule The schedule frequency.
Valid schedules: MINUTE,HOURLY,DAILY,WEEKLY,MONTHLY,
ONCE,ONSTART,ONLOGON,ONIDLE.
cron Daemon to execute scheduled commands
crontab Schedule a command to run at a later time
SCLIST (Resource Kit)
Display NT Services
Syntax
SCLIST [options] [ComputerName]
Key
-r : Display only running services
NET Manage network resources
SC Service Control
MODE CON Configure width of CMD window
NETSVC Commandline Service Controller (Win 2K ResKit)
Equivalent Linux BASH commands:
ps list processes
Scriptit.exe (NT 4 Server)
Control GUI applications feed values into dialogue boxes, press OK etc
Syntax
SCRIPTIT script_file
ScriptIt.exe is no longer available for download at Microsoft.com
an alternative is the freeware tool AutoIt
Originally for NT4 Server, although it does run (rather crankily) on more recent OS's
Scriptit works by recognising the Window Title of each open Application / Document
/ Dialogue box.
The script_file has to be prepared in advance with all the keystrokes you want to
send to the appropriate Window.
The script_file is a text file in .ini format.
Example Script file:
runwait=notepad.exe
Untitled Notepad=Hello World
run=calc.exe
This will launch an instance of Notepad and then send the string "Hello World", when
notepad.exe is closed the script will run CALC.exe
To TAB through dialogue boxes and send other keys follow the syntax shown below
SendKey
Key Description
Equivalent
~ {~} send a tilde (~)
send an exclamation
! {!}
point (!)
^ {^} send a caret (^)
+ {+} send a plus sign (+)
Alt {ALT} send an Alt keystroke
send a Backspace
Backspace {BACKSPACE}
keystroke
Clear {CLEAR} Clear the field
send a Delete
Delete {DELETE}
keystroke
send a Right Arrow
Right Arrow {RIGHT}
keystroke
send a Down Arrow
Down Arrow {DOWN}
keystroke
End {END} send an End keystroke
send an Enter
Enter {ENTER}
keystroke
Escape {ESCAPE} send an Esc keystroke
F1 through {F1} through send the appropriate
F16 {F16} Function key
send a Page Down
Page Down {PGDN}
keystroke
send a Spacebar
Space {SPACE}
keystroke
Tab {TAB} send a Tab keystroke
{ {{}
} {}}
[ {[}
] {]}
CAPSLOCK {CAPSLOCK}
People in the West are always getting ready to live Chinese proverb
Related Commands:
WshShell.SendKeys Send Keys with WSH
CLIP Copy STDIN to the Windows clipboard.
The freeware tool AutoIt is available from hiddensoft.com/autoIt3/
SET
Display, set, or remove CMD environment variables. Changes made with SET will
remain only for the duration of the current CMD session.
Syntax
SET variable
SET variable=string
SET /A variable=expression
SET variable=
SET /P variable=[promptString]
SET "
Key
variable : A new or existing environment variable name
string : A text string to assign to the variable.
expression: : Arithmetic Sum
To display undocumented system variables:
SET "
Arithmetic expressions (SET /a)
The expression to be evaluated can include the following operators:
Multiply *
Divide /
Add +
Subtract -
Modulus %
AND &
OR |
XOR ^
LSH <<
RSH >>
Multiply Variable *=
Divide Variable /=
Add Variable +=
Subtract Variable -=
AND Variable &=
OR Variable |=
XOR Variable ^=
LSH Variable <<=
RSH Variable <<=
Prompt for user input
SET /P variable=[PromptString]
The /P switch allows you to set a variable equal to a line of input entered by the user.
The PromptString is displayed before the user input is read. The PromptString can
be empty.
To place the first line of a file into a variable:
Set /P _MyVar=<MyFilename.txt
Display variables
Type SET without parameters to display all the current environment variables.
Type SET with just a variable name to display that variable
SET _department
Alternatively use the ECHO command:
ECHO [%_department%]
The SET command invoked with a string (and no equal sign) will display a wildcard
list of all matching variables
e.g. Display variables that begin with 'Pro':
SET pro
Display variables that begin with an underscore '_'
SET _
Examples
Storing a text string:
C:\>SET _department=Sales and Marketing
C:\>set _
_department=Sales and Marketing
One variable can be based on another, but this is not dynamic
E.g.
C:\>set xx=fish
C:\>set yy=%xx% chips
C:\>set yy
yy=fish chips
C:\>set xx=sausage
C:\>set yy
yy=fish chips
C:\>set yy=%xx% chips
C:\>set yy
yy=sausage chips
SET can be CALLed allowing a variable substring to be evaluated:
SET start=10
SET length=9
SET string=The quick brown fox jumps over the lazy dog
CALL SET substring=%%string:~%start%,%length%%%
ECHO (%substring%)
Deleting an environment variable
Type SET with just a variable name and an equals sign
For example:
SET _department=
To be sure there is no trailing space after the command use
(SET _department=)
Variable names can include Spaces
A variable can contain spaces and also the variable name itself may contain spaces,
therefore the following assignment:
SET my var=MyText
will create a variable called "my var"
Similarly
SET _var =MyText
will create a variable called "_var " note trailing space
To avoid problems with extra spaces appearing in your output, issue SET statements
in parentheses, like this
(SET _department=Some Text)
Alternatively you can do
SET "_department=Some Text"
Note: if you wanted to actually include a bracket in the variable you need to use an
escape character.
The SET command will set ERRORLEVEL to 1 if the variable name is not
found in the current environment.
This can be detected using the IF ERRORLEVEL command
Using variables in a SET /a calculation
Enclose any logical expressions in "quotes"
Several calculations can be put on one line if separated with commas.
Any SET /A calculation that returns a fractional result will be rounded down to the
nearest whole number.
For example:
SET /A _result=2+4
(=6)
SET /A _result="2<<3"
(=2 Lsh 3 = binary 10 Lsh 3 = binary 10000 = decimal 16)
SET /A _result=5 %% 2
(=5/2 = 2 + 2 remainder 1 = 1)
SET /A _result=5
(=5)
SET /A _result+=5
(=10)
SET /A _result+=5
(=15)
For example:
SET /A _result=5 + NUMBER_OF_PROCESSORS
:: this will return 6
SET /A _result="NUMBER_OF_PROCESSORS + 5"
:: this will return 6
SET /A _result="5 + NUMBER_OF_PROCESSORS"
:: this will return 5
This last result demonstrates a minor bug present in NT 4 sp3.
Leading Zero will specify Octal
Numeric values are decimal numbers, unless prefixed by
0x for hexadecimal numbers,
0b for binary numbers and
0 for octal numbers.
So 0x12 is the same as 0b10010 is the same as 022.
The octal notation can be confusing all numeric values that start with zeros are
treated as octal but 08 and 09 are not valid numbers because 8 and 9 are not valid
octal digits.
This is often a cause of error when performing date arithmetic. For example SET /a
_day=07 will return the value=7, but SET /a _day=09 will return an error.
Permanent Changes
Changes made using the SET command are NOT permanent, they apply to the
current CMD prompt only and remain only until the CMD window is closed.
To permanently change a variable at the command line use SetX
or in the GUI Control Panel, System, Environment, System/User Variables
Changing a variable permanently with SetX will not affect any CMD prompt that is
already open.
Only new CMD prompts will get the new setting.
You can of course use SetX in conjunction with SET to change both at the same
time, but neither SET or SetX will affect other CMD sessions that are already
running. When you think about it this is a good thing.
It is also possible (although undocumented) to add permanent env variables to the
registry [HKEY_CURRENT_USER\Environment]
(using REGEDIT)
System Environment variables can also be found in
[HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
Autoexec.bat
Any SET statement in c:\autoexec.bat may be parsed at boot time
Variables set in this way are not available to 32 bit gui programs they won't appear
in the control panel.
They will appear at the CMD prompt.
If autoexec.bat CALLS any secondary batch files, the additional batch files will NOT
be parsed at boot.
This behaviour can be useful on a dual boot PC.
If Command Extensions are disabled all SET commands are disabled other than
simple assignments like:
_variable=MyText
# I got my mind set on you
# I got my mind set on you... George Harrison
Related Commands:
CALL Evaluate environment variables
SETX Set an environment variable permanently.
SETLOCAL Begin localisation of environment variable changes
ENDLOCAL End localisation of environment changes, use to return values.
Parameters get a full or partial pathname from a command line variable.
PATH Change the %PATH% environment variable.
PATHMAN This Resource Kit utility allows quick modification of both the system
and user paths. Pathman can resolve many problems such as duplicate characters,
and can improve performance by removing duplicate paths. For details see
Pathman.wri in the resource kit.
REGEDIT Import or export registry settings
WMIC ENVIRONMENT Set environment vars through WMI.
Equivalent Linux BASH commands:
env Display, set, or remove environment variables
export Set an environment variable
set Manipulate shell variables and functions
SETLOCAL
Set options to control the visibility of environment variables in a batch file.
Syntax
SETLOCAL
SETLOCAL EnableDelayedExpansion
Issuing an ENDLOCAL command will restore the previous environment variables.
EnableDelayedExpansion
This is an often misunderstood term, I would have prefered it be called something
like
'Expand_Variables_Inside_FOR_Loop'
To explain when using any kind of FOR loop this is the default behaviour:
@echo off
setlocal
:: count to 5 storing the results in a variable
set _tst=0
FOR /l %%G in (1,1,5) Do (echo [%_tst%] & set /a _tst+=1)
echo Total = %_tst%
C:\>demo_batch.cmd
[0]
[0]
[0]
[0]
[0]
Total = 5
Notice that when the FOR loop finishes we get the correct total, so the variable
correctly increments, but during each iteration of the loop
the variable is stuck at it's initial value of 0
The same script with EnableDelayedExpansion, gives the same final result but also
displays the intermediate values:
@echo off
setlocal EnableDelayedExpansion
:: count to 5 storing the results in a variable
set _tst=0
FOR /l %%G in (1,1,5) Do (echo [!_tst!] & set /a _tst+=1)
echo Total = %_tst%
C:\>demo_batch.cmd
[0]
[1]
[2]
[3]
[4]
Total = 5
Notice that instead of %variable% we use !variable! inside the FOR loop.
EnableDelayedExpansion is Disabled by default.
EnableDelayedExpansion may also be enabled by starting CMD with the /v switch.
In some cases it can be helpful to use EnableDelayedExpansion outside a FOR loop:
when combining or concatenating variables, the delimiters may be confused, by
using EnableDelayedExpansion with the ! and % delimiters this can be avoided.
Overloading a variable
SETLOCAL can be used more than once in the same batch file so that multiple
values can be stored in one Environment Variable.
For example:
@echo off
::
::Standard commission
SET _Commission=20
echo %_Commission%
::Super commission
SETLOCAL
set _Commission=30
echo %_Commission%
::Premium commission
SETLOCAL
set _Commission=40
echo %_Commission%
::Back to Super commission
ENDLOCAL
echo %_Commission%
::back to Standard commission
ENDLOCAL
echo %_Commission%
DISABLEEXTENSIONS
Command Extensions are enabled by default, DisableExtensions will attempt to
disable Command extensions. (ENABLEEXTENSIONS will attempt to reenable)
SETLOCAL will set an ERRORLEVEL if given an argument. It will be zero if one of
the two valid arguments is given and one otherwise.
You can use this in a batch file to determine if command extensions are available,
using the following technique:
VERIFY errors 2>nul
SETLOCAL ENABLEEXTENSIONS
IF ERRORLEVEL 1 echo Unable to enable extensions
This works because "VERIFY errors" sets ERRORLEVEL to 1 and then the
SETLOCAL will fail to reset the ERRORLEVEL value if extensions are not available
(e.g. if the script is running under command.com)
If Command Extensions are permanently disabled then SETLOCAL
ENABLEEXTENSIONS will not restore them.
"A local shop for local people" The League Of Gentlemen
Related Commands:
ENDLOCAL End localisation of environment changes in a batch file.
Equivalent Linux BASH commands:
readonly Mark variables/functions as readonly
SETX.exe (Resource Kit)
Set environment variables permanently
SETX can be used to set Environment Variables for the machine or currently logged
on user:
Key:
-m Set the value in the Machine environment (HKLM)
Default is User (HKCU)
SetX can also be used in modes to edit the Registry or edit CRLF text files, (like
win.ini) for most purposes these tasks are better done with other tools in the
resource kit, e.g. the REG command.
Because SetX writes variables to the master environment in the registry. Edits will
only take effect when a new command window is opened they do not affect the
current command session.
Deleting variables
A value of "" (empty quotes) will appear to delete the variable it's not shown by SET
but the variable name will remain in the registry. Either use the GUI (recommended)
or delete the value from the registry with REG
Deleting a variable in this way does not take effect until next logon due to caching of
registry data. The type is REG_EXPAND_SZ.
Examples:
Set the variable "_mypc" to be COMPAQ in the users permanent environment:
Delete the variable "_myvar" in the users permanent environment:
Set the variable "_myTimeZone" in both the immediate user session and the
permanent environment:
SET _myTimeZone=GMT
SetX _myTimeZone GMT
Store the value of %my_important_var% in a second environment variable.
SetX _mybackupvar %my_important_var%
Sets the value of _mypath to ALWAYS be equal to the value of the %PATH%
environment variable even in the event that the PATH variable changes:
SetX _mypath ~PATH~
Machine variables
These are stored on the machine and won't follow a users roaming profile.
To set a machine variable (m) requires Administrator rights.
Create a machine variable:
Delete a machine variable:
"You are never dedicated to something you have complete confidence in. Noone is
fanatically shouting that the sun is going to rise tomorrow. When people are
fanatically devoted to political or religious faiths or any other kind of dogmas or goals,
its always because these dogmas or goals are in doubt" Robert M Pirsig
Related Commands:
SET Display, set, or remove environment variables
REG Delete keys or values from the registry
Q104011 Modify variables by editing the Registry
SETENV Vincent Fatica's improved version
Equivalent Linux BASH commands:
env Display, set, or remove environment variables
export Set an environment variable
SHARE.VBS (Resource Kit)
List or edit a file share or print share (on any computer)
Although missing from recent Resource Kits, this VBS script does still work under
2K/XP. The preferred method for creating shares is the RMTShare command, which
can also grant permissions.
Syntax:
List Shares
Share.vbs /L [/S <server>] [/U <username>] [/W
<password>] [/O <outputfile>]
Create a Share
Share.vbs /C /N <name> /P <path> [/T <type>] [/V
<description>]
[/S <server>] [/U <username>] [/W
<password>] [/O <outputfile>]
Delete a Share
Share.vbs /D /N <name>
[/S <server>] [/U <username>] [/W
<password>] [/O <outputfile>]
Options:
/L List
/C Create
/D Delete
/N name Name of the share to be created or deleted.
/P path Path of the share to be created.
/v description A description for the share.
/T type Type of the share to be created. (Disk,
Printer, IPC or Special)
/S server A machine name.
/U username The current user's name.
/W password Password of the current user.
/O outputfile Output file name.
Examples:
List the shares on the machine \\Frodo
cscript Share.vbs /L /s Frodo
Create a file share called "scratch" on the local machine:
cscript Share.vbs /c /n scratch /p "c:\my shared files" /t Disk /v "project files"
Delete the share named "scratch" on the machine \\Frodo
cscript Share.vbs /d /n scratch /s Frodo
"The inherent vice of capitalism is the unequal sharing of blessings,
the inherent vice of Socialism is the equal sharing of miseries." Winston Churchill
Related Commands:
CACLS Display or modify Access Control Lists (ACLs) for files and folders
RMTShare The preferred method for creating a file system share (it can also grant
permissions)
RUNDLL32 Run a DLL command (add/remove print connections)
Equivalent Linux BASH commands:
mount Mount a file system
SHIFT
Change the position of command line parameters in a batch file.
Syntax
SHIFT [/n]
for example:
given %1=one, %2=two, %3=three...
SHIFT
will result in %1=two, %2=three
alternatively given %1=one, %2=two, %3=three...
SHIFT & SHIFT
will result in %1=three
/n tells the SHIFT command to start shifting at the nth argument, where n may be
between zero and eight.
for example:
given %1=one, %2=two, %3=three, %4=four...
SHIFT /2
will result in %1=one, %2=three, %3=four
%0 is the name of the batch file itself %1 can be shifted into %0
Relative pathnames
The parameter %0 will initially refer to the path that was used to execute the batch
this could be MyBatch.cmd if in the current directory or a full path like
C:\apps\myBatch.cmd
When SHIFT is used to move a text parameter into %0 then references to %0 will
refer to the current working directory, unless those parameters happen to contain a
valid path.
For example:
%0\..\MyExecutable.exe
will run the executable from the same directory
If the following parameter is passed to myBatch.cmd
myBatch.cmd D:\utils\
Then the following commands in myBatch will run MyExecutable.exe from the
directory D:\utils\
SHIFT
%0\..\MyExecutable.exe
If Command Extensions are disabled, the SHIFT command will not support the /n
switch
"If NumLock is on, pressing a key on the numeric keypad while holding SHIFT
overrides NumLock and instead generates an arrow key" OldNewThing
Related commands
CALL Call one batch program from another
SET Display or edit environment variables
Equivalent Linux BASH commands:
shift Shift positional parameters
SHORTCUT.exe (Server Resource Kit)
Create a windows shortcut (.LNK file)
Syntax
SHORTCUT [options]
Key
Source options
-t target : The path and file name of the application.
-a arguments : The arguments passed when the shortcut is
used.
-d directory : The folder to start the application in.
Export options
-u [spec] : ECHO the contents of an existing shortcut.
'all' is the same as 'natdix' but the
letters
of 'natdix' specify the options to be
exported
(the same option can be specified more than
once
e.g. -u natn)
Example
@ECHO off
MD %userprofile%"\start menu\programs\MY APP"
SHORTCUT -f -t C:\MyApp.exe -n %userprofile%"\start
menu\programs\MY APP\MY APP"
Alternatively use WSH to create a shortcut:
optional sections in the VBscript below are commented out
Set oWS = WScript.CreateObject("WScript.Shell")
sLinkFile = "C:\MyShortcut.LNK"
Resolve Shortcut Links
If a shortcut to a file breaks, then by default Windows will attempt to automatically
locate the shortcut destination by performing a simple search. To change this default
edit the registry:
HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
NoResolveTrack=1
(DWORD)
This can also be controlled at Group Policy level in: User Config\Admin
Templates\Start Menu & Taskbar.
If a shortcut .LNK file is copied to another machine, then by default the shortcut's
target may be automatically updated e.g. create a shortcut on Machine1 to
C:\AUTOEXEC.BAT when copied to Machine2 the shortcut will point back to
\\Machine1\c$\AUTOEXEC.BAT
To change this default add this to the registry before creating the shortcut:
HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
"LinkResolveIgnoreLinkInfo"=dword:00000001
Favourites
Often confused with shortcuts, Internet Explorer Favourite (.URL) files are simple text
files which you can create with a few ECHO statements.
"The reasonable man adapts himself to the world: the unreasonable one persists in
trying to adapt the world to himself. Therefore all progress depends on the
unreasonable man" George Bernard Shaw
Related Commands:
MD Create folder(s)
Slow Network browsing (XP)
NTFAQ Disable NTFS resolving of broken shortcuts
FSUTIL Create a Hardlink
Q158682 Shortcuts created resolve to UNC Path (Link Tracking)
Q150215 Disable Automatic Shortcut Resolution
Q263324 Shortcut Command truncates path names
Equivalent Linux BASH commands:
symlink Make a new name for a file
ln Make links between files
SHOWGRPS (Resource Kit)
List the NT Workgroups a user has joined.
Syntax
SHOWGRPS domain\username
SHOWGRPS username
If no username is specified SHOWGRPS will list the workgroups for the currently
logged in user.
For Example
SHOWGRPS john.smith
"Justice is such a fine thing that we cannot pay too dearly for it" AlainRene Lesage
Related Commands:
NET add or remove a user from a workgroup
FINDGRP List the (global or local) security groups a user has joined (NT 4 Reskit)
SHOWMBRS List the members of an NT Workgroup
GRPTEST SMS support tools enumerate group membership for a user account.
SHOWACCS Show access profile (Windows 2000)
SHOWMBRS (Resource Kit)
List all the users who are members of a Workgroup.
Syntax
SHOWMBRS domain\NT_Workgroup
SHOWMBRS NT_Workgroup
A workgroup must be specified.
Example:
SHOWMBRS wg_finance
Related Commands:
NET GROUP add or remove a user from a workgroup
SHOWGRPS List the Workgroups a user is in
SHOWACCS Show access profile (Windows 2000)
GRPTEST SMS support tools enumerate group membership for a user account
WHOAMI /all List all workgroups
SHUTDOWN.exe
Shutdown the computer
Syntax
logoff_option:
/i Display the GUI (must be the first option)
/l Log off. This cannot be used with /m or /d
option
/s Shutdown
/r Shutdown and Restart
/a Abort a system shutdown.
(only during the time-out period)
/p Turn off the local computer with no time-out or
warning
(only with /d)
/h Hibernate the local computer (only with /f )
/e Document the reason for an unexpected shutdown
of a computer
options:
When using this command to reboot a server, the shutdown process will normally
allow about 30 seconds to ensure each running service has time to stop. The
shutdown can be made faster if all the services are first halted using NET STOP
e.g.
net stop "Microsoft Exchange Internet Mail Service"
net stop "Microsoft FTP Service"
net stop "Some other Service"
SHUTDOWN /t:25 /r
Typical Reason codes:
E = Expected
U = Unexpected
P = planned (C = customer defined)
Type Major Minor Title
U 0 0 Other (Unplanned)
E 0 0 Other (Unplanned)
E P 0 0 Other (Planned)
U 0 5 Other Failure: System Unresponsive
E 1 1 Hardware: Maintenance (Unplanned)
E P 1 1 Hardware: Maintenance (Planned)
E 1 2 Hardware: Installation (Unplanned)
E P 1 2 Hardware: Installation (Planned)
P 2 3 Operating System: Upgrade (Planned)
E 2 4 Operating System: Reconfiguration
(Unplanned)
E P 2 4 Operating System: Reconfiguration (Planned)
P 2 16 Operating System: Service pack (Planned)
2 17 Operating System: Hot fix (Unplanned)
P 2 17 Operating System: Hot fix (Planned)
2 18 Operating System: Security fix (Unplanned)
P 2 18 Operating System: Security fix (Planned)
E 4 1 Application: Maintenance (Unplanned)
E P 4 1 Application: Maintenance (Planned)
E P 4 2 Application: Installation (Planned)
E 4 5 Application: Unresponsive
E 4 6 Application: Unstable
U 5 15 System Failure: Stop error
E 5 19 Security issue
U 5 19 Security issue
E P 5 19 Security issue
E 5 20 Loss of network connectivity (Unplanned)
U 6 11 Power Failure: Cord Unplugged
U 6 12 Power Failure: Environment
P 7 0 Legacy API shutdown
Related Commands:
LOGOFF Log off a user.
BootCFG Edit Boot.ini settings.
PsShutdown SysInternals command line tool
PowerOff Stefan Kuhr utility (NT / 2K)
JSIFAQ Tip 9130 log off user after n minutes of inactivity
SLEEP.exe (Resource Kit)
Add a fixed delay to a batch file
Syntax
SLEEP time
Key
time : the number of seconds to pause
For example:
To pause for an hour before running the next command in a batch file:
SLEEP 3600
Alternative
A fixed delay can also be produced by the PING command with a loopback address:
e.g. for a delay of 60 seconds:
PING -n 61 127.0.0.1>nul
See Clay Calvert's newsgroup posting for a full explanation of this technique.
"I think men talk to women so they can sleep with them and women sleep with men
so they can talk to them" Jay McInerney
Related Commands:
TIMEOUT Delay that allows the user to continue
WAIT the same as sleep but with noises
WScript.Sleep Sleep
Equivalent Linux BASH commands:
crontab Schedule a command to run at a later time
SOON.exe (Resource Kit)
Schedule a command to run in the near future (calls the AT command)
Syntax
SOON [\\computername] delay [/interactive] "command"
SOON /i:[on|off]
Key
delay : When the command should run, in SECONDS from now.
default=5
As with all AT jobs you should test your SOON scripts by using the /INTERACTIVE
option to be sure that they:
• Start at the expected time
• Execute the correct commands (specify a full pathname)
• Finish and close successfully.
This command will work with both the NT 4 "Schedule" service (ATSVC) or with the
"Task Scheduler" service in more recent versions of Windows.
"We want the finest wines available to humanity. And we want them here and we
want them now" Bruce Robinson (Withnail and I )
Related Commands:
AT Schedule a command to run at a later time
Q237840 Setting a delay of less than 60 seconds.
Q226370 IE 5 bugs related to the Task Scheduler (fixed in IE 5.01)
Equivalent Linux BASH commands:
cron Daemon to execute scheduled commands
crontab Schedule a command to run at a later time
watch Execute/display a program periodically
SORT
Sort will accept a redirected or piped file input and TYPE the file, sorted line by line.
Syntax
SORT [options]
Options
/R : Reverse sort order (Z to A, 9 to 0)
/L[OCALE] locale
/M[EMORY] kilobytes
/REC[ORD_MAXIMUM] characters
[drive:][pathname]
/T[EMPORARY] [drive:][path]
SORT < pathname
Piping a command into SORT
command | SORT
Piping the output from SORT into a file
command | SORT > pathname2
SORT < pathname > pathname2
Piping the output from SORT and appending to an existing file
command | SORT >> pathname2
SORT < pathname >> pathname2
Cultivate peace and order before confusion and disorder Tao Teh Ching
Related Commands:
TYPE Display the contents of a text file
Redirection Redirect files, command output and error messages
Equivalent Linux BASH commands:
sort Sort text files
START
Start a specified program or command in a separate window.
Syntax
START "title" [/Dpath] [options] [command] [parameters]
Key
WHAT to run
HOW to run it
/MIN : Minimized
/MAX : Maximized
/WAIT : Start application and wait for it to terminate
/LOW : Use IDLE priority class
/NORMAL : Use NORMAL priority class
/HIGH : Use HIGH priority class
/REALTIME : Use REALTIME priority class
"title" : Text for the CMD window title.
/B : Start application without creating a new
window. In this case
^C will be ignored - leaving ^Break as the
only way to
interrupt the application
/I : Ignore any changes to the current environment.
Document files may be invoked through their file association just by typing the name
of the file as a command.
e.g. START WORD.DOC would launch the application associated with the .DOC file
extension
Printers
A new printer can be installed very quickly (and the driver downloaded) with the
command
START \\print_server\printer_name
Setting a Working Directory
To start an application and specify where files will be saved
START /Dc:\Documents\ /MAX notepad.exe
Note that START /D does not support long filenames which contain spaces, a
workaround is to use the 8.3 compatible name(s)
Forcing a Sequence of Programs
If you require your users to run a sequence of 32 bit GUI programs to complete a
task, create a batch file that uses the start command:
@echo off
start /wait /b First.exe
start /wait /b Second.exe
start /wait /b Third.exe
Create a shortcut to this batch file and place it on the Start menu or desktop. Set it to
run minimized.
When the user doubleclicks the shortcut, <First.exe> runs.
When <First.exe> terminates, <Second.exe> runs
When <Second.exe> terminates, <Third.exe> runs
An alternative method is to run a .BAT batch file under command.com (16 bit)
If Command Extensions are disabled, the START command will no longer recognise
file Associations, and will not automatically evaluate the COMSPEC variable when
starting a second CMD session.
Missing file extensions
When executing a command line whose first token does NOT contain an extension,
then CMD.EXE uses the value of the PATHEXT environment variable to determine
which extensions to look for and in what order. The default value for the PATHEXT
variable is:
.COM;.EXE;.BAT;.CMD
Notice the syntax is the same as the PATH variable, with semicolons separating the
different elements.
When executing a command, if there is no match on any extension, then NT will look
to see if the name, without any extension, matches a directory name and if it does,
the START command will launch Explorer on that path.
"Do not run; scorn running with thy heels" Shakespear, The Merchant of Venice
Related commands:
CALL Call one batch program from another
CMD can be used to call a subsequent batch and ALWAYS return even if errors
occur.
GOTO jump to a label or GOTO :eof
Q162059 Opening Office documents
Equivalent Linux BASH commands:
.period Run commands from a file
SU (Resource Kit)
Switch User.
Syntax
SU "[cmdline]" [domain] [[Winsta\]Desktop] [options]
Key
cmdline The command to run (default =%comspec%)
domain The domain for the user account ('.' = local
m/c)
Winsta\Desktop The profile to load (default = current)
Options
"Our deepest fear is not that we are inadequate. Our deepest fear is that we are
powerful beyond measure. It is our light, not our darkness, that most frightens us"
Nelson Mandela
Related Commands:
RUNAS Execute a program under a different user account.
PsExec Execute process remotely
Equivalent Linux BASH commands:
su Run a command with substitute user and group id
SUBINACL.exe (Resource kit)
Download latest version (2004)
Display or modify Access Control Entries (ACEs) for file and folder Permissions,
Ownership and Domain.
Access Control Lists apply only to files stored on an NTFS formatted drive, each ACL
determines which users (or groups of users) can read or edit the file. When a new file
is created it normally inherits ACL's from the folder where it was created.
Syntax
SUBINACL [/noverbose] /object_type object_name
[/action=parameter] [/help]
Key
object_type: service e.g. /service Messenger
\\ServerName\Messenger
keyreg e.g. /keyreg
HKEY_CURRENT_USER\Software
/keyreg
\\Srv\HKEY_LOCAL_MACHINE\KeyPath
file e.g. /file *.obj /file
c:\test.txt
/file
\\ServerName\Share\Path
subdirectories manipulate files in specified
directory and all subdirectories
action : setowner=owner
will change the owner of the object e.g.
/setowner=MyDomain\Administrators
replace=SamName\OldAccount=DomainName\New_Acc
ount
will replace all ACE (Audit and Permissions)
in the object
e.g.
/replace=MyOldDomain\Finance=NEWDOM\Finance
changedomain=OldDomainName=NewDomainName
will replace all ACEs with a Sid from
OldDomainName
with the equivalent Sid found in NewSamServer
e.g. /changedomain=MyOldDomain=NEWDOMAIN
This option requires a trust relationship
with the server containing the object.
Examples:
subinacl can do everything that cacls and xcacls can do and more besides.
List permissions to log file:
subinacl /noverbose /nostatistic /outputlog=my.log
/subdirectories "C:\Program Files\My Folder" /display
Restore Permissions:
subinacl /nostatistic /playfile my.log
Change owner :
subinacl /file C:\demofile.doc /setowner=MYDOMAIN\BillG
Bugs
Running subinacl against a subfolder, as in the example above will affect just that
folder and it's contents. However if you run subinacl against a folder in the root of the
drive it will scan the entire drive for folders matching that name (which can take some
time).
e.g.
subinacl /subdirectories "C:\Spud"
Will also match
C:\Program Files\Spud
C:\Documents and Settings\Spud etc
"Whether a pretty woman grants or withholds her favours, she always likes to be
asked for them" Ovid (Ars Amatoria)
Related Commands:
ATTRIB Display or change file attributes
PERMS Show permissions for a user
FIXACLS Restore default privs (Resource Kit supplement 2)
SHOWACL Show file Access Control Lists (Windows 2000)
XCACLS Display or modify Access Control Lists (ACLs) for files and folders
Q245031 Change Registry Permissions from the command line
Q265360 Change multiple Subdirectory Permissions
Q288129 Grant users the right to manage services
Equivalent Linux BASH commands:
chmod Change access permissions
chown Change file owner and group
SUBST
Substitute a drive letter for a network or local path.
Syntax
SUBST drive_letter: path
SUBST
SUBST drive_letter: /D
Key
SUBST with no parameters will display current SUBST drives
Bugs
Under NT 4 SUBST'ed drives cannot be disconnected using the Explorer GUI this
was fixed in Windows 2000.
In Windows 2000 (and above) you will have problems creating, accessing and
deleting drive mappings with SUBST.
However under Win 2K/XP the functionality of the NET USE command is improved
so you can now do
NET USE g: \\server\share\folder1\folder2
If the network resource is unavailable (ie the server is down) SUBST will continually
retry unlike NET USE which will try to connect once and fail depending on your
application this may be a good or a bad thing a subst drive that is not available will
badly impact performance of most applications.
Notice that when SUBST is used against a local shared folder, it will create a
RECYCLER for that drive. The RECYCLER is not removed when the drive
substitution is removed, but can be deleted manually.
"A man should never be ashamed to own he has been in the wrong, which is saying
in other words, that he is wiser today than he was yesterday" Alexander Pope
(thoughts on various subjects)
Related Commands:
NET USE Map a drive letter to a network drive
SYSTEMINFO
List system configuration
Syntax
SYSTEMINFO [/S system [/U username [/P [password]]] ]
[/FO format] [/NH]
Key:
/S system Remote system to connect to.
/U [domain\]user User context under which to execute.
/P [password] Password for the given user (will
prompt if omitted)
/FO format Output format: TABLE, LIST or CSV
/NH No "Column Header" in the Table/CSV
output
The output includes OS configuration, security info, product ID, RAM, disk space,
and network cards.
Examples
SYSTEMINFO
SYSTEMINFO |find "Total Physical Memory:"
SYSTEMINFO /S wkstn6324
SYSTEMINFO /S wkstn6325 /FO CSV /NH >>pcaudit.csv
"Thought is fugitive; the mind does not repeat itself; if you do not catch the
whisperings of the oracle as they come to you, they are lost forever. You must; and
this is absolutely essential; convince yourselves that what is offered you this very
moment will never be offered again" Jean Guitton
Related Commands:
WINMSD Windows system diagnostics
WMIC WMI Commands
PsGetSid Display the SID of a computer or a user
TASKLIST (Win XP)
TaskList displays all running applications and services with their Process ID (PID)
This can be run on either a local or a remote computer.
(Under Win NT 4 use the resource kit tool TList.)
Syntax
tasklist options
Key
/fo {TABLE|LIST|CSV}]
Output format, the default is TABLE.
Status eq, ne
RUNNING|NOT RESPONDING
Imagename eq, ne
String
PID eq, ne, gt, lt, ge, le
Positive integer.
Session eq, ne, gt, lt, ge, le Any
valid session number.
SessionName eq, ne
String
CPUTime eq, ne, gt, lt, ge, le Time
hh:mm:ss
MemUsage eq, ne, gt, lt, ge, le Any
valid integer.
Username eq, ne
User name ([Domain\]User).
Services eq, ne
String
Windowtitle eq, ne
String
Modules eq, ne
String
/m [ModuleName] | /svc | /v
/m Show the processes that include the given
module.
/svc List all info for each process without
truncation.
Valid when /fo=TABLE. Cannot be used with
/m or /v
/v Verbose task information
Examples:
tasklist /v /fi "STATUS eq running"
WMI
WMIC can also list running processes and parameters
e.g.
Related Commands:
PsList List detailed information about processes
PSTAT display running tasks including all Process Threads.
MEM Display memory usage
WINMSD Windows NT Diagnostics (including Physical Memory)
Equivalent Linux BASH commands:
top List running processes on the system
time Measure Program Resource Use
times User and system times
TIME
Display or set the system time.
Syntax
TIME [new_time]
TIME
TIME /T
key
new_time : The time as HH:MM
In Control Panel, Regional settings a Time Appearance can be set. This can be used
to change the separator, and the number of characters used to display hours and
minutes.
To display the time including Seconds:
ECHO.| TIME will display the time, including seconds and hundredths of a second
Time Format information in the Registry
The Country Code is a user setting in the registry:
[HKEY_CURRENT_USER\Control Panel\International]
"iCountry"="44"
The Country Code can be read using REG.exe as follows
FOR /F "TOKENS=2,3*" %%A IN ('REG QUERY
"HKEY_CURRENT_USER\Control Panel\International\iCountry"') DO
(FOR %%G in (%%A) DO (SET _country=%%G))
The time separator is also a registry setting
[HKEY_CURRENT_USER\Control Panel\International]
"sTime"=":"
The time separator can be read using REG.exe as follows
FOR /F "TOKENS=2,3*" %%A IN ('REG QUERY
"HKEY_CURRENT_USER\Control Panel\International\sTime"') DO
(FOR %%G in (%%A) DO (SET _time_sep=%%G))
The time formats for different country codes are as follows:
Country or language CountryCode Date format Time format
"To me when a mother puts food in a microwave for her children, it is an act of hate"
Raymond Blanc
Related Commands:
DATE Display or change the date
NOW Display Message with Current Date and Time
TIMESERV Time Service (resource kit)
W32TIME Time Service (y2K compliant update for TIMESERV)
Timethis Time how long it takes the system to run a command. (Win 2K ResKit)
Uptime Time since last reboot. (Win 2K ResKit)
GetTime.cmd Script to get current time
GMT.cmd Current time in GMT (World Time)
Equivalent Linux BASH commands:
date Display or change the date & time
TIMEOUT.exe (Resource Kit)
Delay execution of a batch file.
Syntax
TIMEOUT delay
Key
delay :Delay in seconds (between -1 and 100000) to wait
before continuing.
The value -1 causes the computer to wait
indefinitely for a keystroke
(like the PAUSE command)
Timeout will pause command execution for a number of seconds, after which it
continues without requiring a user keystroke. If the user does press a key at any
point, execution will resume immediately.
Timeout.exe seems to consume less processor time time than Sleep.exe
"It is awful work this love and prevents all a mans projects of good or glory" Lord
Byron
Related Commands:
PAUSE Suspend processing of a batch file and display a message
SLEEP Fixed delay
WAIT Fixed delay
TITLE
Change the title displayed above the CMD window.
Syntax
TITLE [string]
Key
string : The title for the command prompt window.
The default title is %comspec%
To change the title for the duration of a command use:
TITLE This is the initial title text
CMD /c MyBatchFile.cmd
...
If MyBatchFile.cmd contains a different TITLE command it will revert when the
second command session ends.
"The longer the title, the less important the job." George McGovern.
Related commands:
MODE change the size of the CMD window
COLOR change the colour of the CMD window
PROMPT change the CMD window prompt
QuickEdit mode also changes the title (temporarily)
TOUCH (Resource Kit)
Change file timestamps
Syntax
TOUCH [option]... files ...
Key
/t year month day hour minute second
This is a POSIX utility.
Use the optional argument /t to specify a date other than the current time.
( fourdigit years, twodigit months, days, hours, minutes, seconds)
Example
To set the date to 7:30 am 1st October 2015
Related commands:
Q299648 Date and Time Stamps for Files and Folders
COPY Copy one or more files to another location
Equivalent Linux BASH commands:
touch Change file timestamps
TRACERT
Trace Route Find the IP address of any remote host. TRACERT is useful for
troubleshooting large networks where several paths can be taken to arrive at the
same point, or where many intermediate systems (routers or bridges) are involved.
Syntax
TRACERT [options] target_name
Key
target_name The HTTP or UNC name of the host
Options:
-d Do not resolve addresses to hostnames.
(avoids performing a DNS lookup)
Examples
TRACERT www.doubleclick.net
TRACERT 123.45.67.89
TRACERT local_server
Get your kicks on ROUTE 66 Jack Kerouac.
Related Commands:
NSLOOKUP Name server lookup
PING Test a network connection
PATHPING Trace route and provide network latency and packet loss for each router
and link in the path.
ROUTE Manipulate network routing tables
Q162326 Using TRACERT to Troubleshoot TCP/IP Problems
tip 4723 A better description from JSIinc
TRACE.BAT handy report on any given Internet address
tracert.com trace routes from remote locations
Equivalent Linux BASH commands:
trace Find the IP address of a remote host
TYPE
Display the contents of a text file or files.
Syntax
TYPE [drive:]pathname(s)
If more than one file is specified the filenames are included in the output.
If a wildcard is used the filenames are not displayed.
Output can be redirected into a new file:
TYPE file.txt > Newfile.txt
Output can be appended to an existing file:
TYPE file.txt >> ExistingFile.txt
To do the same with user console input :
TYPE CON > Newfile.txt
This will require a CTRL Z to indicate end of file.
When using redirection to SORT a file the TYPE command is used implicitly
For example:
SORT < MyFile.txt
If you TYPE a Unicode text file, the output will be ANSI.
eg:
TYPE UnicodeFile.txt > ANSIFile.txt
To convert multiple Unicode files to ASCII try this script
@echo off
ren *.txt *.txx
for %%G in (*.txx) do (TYPE %%G >%%~nG.txt)
echo del *.txx
"There are few more impressive sights than a Scotsman on the make" Sir James
Barrie
Related Commands:
FOR /F
SORT
List Text Display and Search Tool (Win 2K ResKit)
Equivalent Linux BASH commands:
cat Display the contents of a file
VER
Display the current operating system version.
Syntax
VER
@ECHO OFF
ECHO Unknown OS !
GOTO :EOF
:W9598ME
ECHO Win9x commands go here
GOTO :EOF
:W98
ECHO Win98 commands go here
GOTO :EOF
:s_win_XP
ECHO XP commands go here
goto :eof
:s_win_2000
ECHO WIN2K commands go here
goto :eof
:s_win_NT
ECHO NT4 commands go here
goto :eof
:EOF (End-of-file)
Service Pack Version
This Batch script will give the Service Pack level.
Works for NT, Win2K or WinXP
Bugs
The VER command reports the version of CMD.exe, so if for example you run the
Win XP version of CMD under NT 4 then the VER command will return:
Microsoft Windows XP [Version 4.0.1381]
Related Commands:
Q190899 How to Determine the OS Type in a Logon Script
WINVER.exe Opens the GUI Version dialogue box (Help, About)
FILEVER DLL version information (Resource Kit, XP Support tool)
Equivalent Linux BASH commands:
uname r Print system information
VERIFY
To check that files are saved to disk correctly; the system can reread the disk when
saving and verify (compare) with the data in memory.
Syntax
VERIFY [ON | OFF]
By default the CMD shell has verify OFF
Windows Explorer will always copy with verify ON
Copying files can be up to twice as fast with verify OFF.
VERIFY without a parameter will display the current setting.
"VERIFY dummy_text" will set %ERRORLEVEL% to 1
"Women might be able to fake orgasms. But men can fake whole relationships."
Sharon Stone
Related Commands:
MOVE Move files from one folder to another
Equivalent Linux BASH commands:
cksum Print CRC checksum and byte counts
VOL
Display the volume label of a disk.
Syntax
VOL [drive:]
If they exist, VOL will display both the disk label and serial number.
Related Commands:
LABEL Edit the volume label of a disk
BootCFG Edit Boot.ini settings.
Equivalent Linux BASH commands:
hostname Print or set system name
uname Print system information
WHERE (2K Resource Kit / .Net Server)
Locate and display files in a directory tree.
The WHERE command is roughly equivalent to the UNIX 'which' command.
For early versions of windows that don't have this command you can use this WHICH
batch file.
By default, the search is done in the current directory and in the PATH.
Syntax
WHERE [/r Dir] [/q] [/f] [/t] Pattern ...
key
/r A recursive search, starting with the specified Dir
directory.
To find all files named 'Zappa' in drive C: of the remote computer 'MyPC' and its
subdirectories, and report the executable type for executable files
WHERE /r \\MyPC\c /e Zappa.*
Related commands:
CD Change Directory
TYPE Display the contents of a text file
Equivalent Linux BASH commands:
which Show full path of commands
WHOAMI.exe (Resource kit)
Displays the username and domain for the currently logged in user.
The whoami output is the same as the 2 environment variables %USERDOMAIN%
and %USERNAME%.
So the same output can be achieved with
ECHO %USERDOMAIN%\%USERNAME%
Under Windows 2000 there is an additional switch WHOAMI /all this shows all
permissions and group memberships.
"We can now manipulate images to such an extrodinary extent that there's no lie you
cannot tell" Sir David Attenborough
Related Commands:
SET Display, set, or remove Windows NT environment variables
VER Display version information
VOL Display a disk label
Whereami.cmd Display user information
Equivalent Linux BASH commands:
id Print user and group id's
who Print who is currently logged in
whoami Print the current user id and name (`id un')
WinDiff
Compare the contents of two files or sets of files with a graphical interface.
Syntax
windiff [path1] [path2]
Key
path Individual files to compare
or a directory of files to compare
If either path is not specified it will default to the current directory (or a matching file
in the current directory)
If nothing is specified, the GUI will appear select files to compare with the menus.
White background = parts common to both files.
Red background = parts that belong to the file listed on the left .
Yellow background = parts that belong to the file listed on the right .
Registry files (exported with regedit) can also be compared. Also see the help file
Windiff.hlp.
Downloads
Microsoft Full SDK download 408098 Kb
WinDiff Grigsoft (3rd party) download 75 Kb
"Shall I compare thee to a summer's day? Thou art more lovely and more temperate.
Rough winds do shake the darling buds of May, And summer's lease hath all too
short a date" Shakespeare
Related Commands:
COMP Compare two files and display any characters which do NOT match
FC Compare two files
FIND Search for a text string in a file
FINDSTR Search for strings in files
WinMerge (Sourceforge)
Q171780 Use WinDiff to compare registry files
Equivalent Linux BASH commands:
comm Compare two sorted files line by line
cmp Compare two files
diff Display the differences between two files
WINMSD.exe
Microsoft Windows diagnostics
Reports: Memory use, Services, Devices, IRQ's Ports, Environment variables,
Network (rights, transport, stats), Hardware including Display adapter.
Syntax
WINMSD [\\computername] options
Options:
/a All details
/s Summary details only
/f Send output to a file <computername.txt>
in the current directory
/p Send output to a printer
SHIFT F2 copies the current tab to the clipboard,
F2 copies a summary of the current tab to the clipboard
Winmsd in Windows 2000 will actually run Msinfo32
mmc.exe /s "C:\Program Files\Common Files\Microsoft
Shared\MSInfo\MSInfo32.msc"
It is advisable to have the SERVER service running, if not winmsd will show a
warning dialogue.
Spooling output to file if you have the resource kit WINMSDP allows more control
over this.
Related Commands:
MSINFO Windows NT diagnostics
WINMSDP Windows NT Diagnostics II
DevCon Device Manager Command Line Utility
FSUTIL File and Volume utilities
SRVINFO SMS support tools partition info, running services and Network info.
Dmdiag display disk properties: Size, Status, Type...(Win 2K ResKit)
WINMSDP.exe (Resource Kit)
Windows NT diagnostics II
Reports: Memory use, Services, Devices, IRQ's Ports, Environment variables,
Network (rights, transport, stats), Hardware including Display adapter.
Syntax
WINMSDP option
/e : environment
/d : drives
/i : interrupt resources
/m : memory
/n : network
/o : OS version
/p : port resources
/r : drivers
/s : services
/u : DMA resources
/w : hardware
/y : memory resources
The output is very similar to WINMSD if a little more detailed.
The output will appear in a text file called msdrpt.TXT
"The best is the enemy of the good" Voltaire
Related Commands:
WINMSD Windows NT Diagnostics
Q102468 How to use WINMSDP
Q231368 IIS/Site Server vulnerability via WINMSDP
Q310747 System File Checker (Sfc.exe)
XCACLS.exe (Server Resource Kit)
Display or modify Access Control Lists (ACLs) for files and folders.
Syntax
XCACLS filename [options]
XCACLS filename
Key
If no options are specified XCACLS will display the ACLs
for the file(s)
/P user:permision[;FolderSpec]
Replace user's rights. see /G option below
/G user:permision[;FolderSpec]
Grant specified user access rights, permision can be:
r Read
c Change (write)
f Full control
p Change Permissions (Special access)
o Take Ownership (Special access)
x EXecute (Special access)
e REad (Special access)
w Write (Special access)
d Delete (Special access)
t Used only by FolderSpec. see below
FolderSpec = ;T@ where @ is one of the rights above, when this is specified new
files will inherit FolderSpec instead of permission. At least one folder access
right must follow the T For example ;TF will apply full control (but ;FT is not valid)
Wildcards can be used to specify more that one file in a command. You can specify
more than one user in a command. You can combine access rights.
Versions:
When running this command it is important to use the correct version (NTFS
standards have changed with different versions of Windows and XCACLS has been
updated to suit)
Early versions of xcacls may give unpredictable results against an NTFS v5 partition.
xcacls.vbs is described in Q825751 and can be downloaded here xcacls.vbs is an
unsupported utility that addresses a limitation with the original xcacls.exe, specifically
the inability to append permissions to a folder whose child objects have the
inheritance flag set. The .vbs version does not suppport unc paths.
Examples:
:: Allow guests the right to read and execute in MyFolder
XCACLS MyFolder /E /G guests:rx
:: Allow guests the Full Control permission in MyFolder and all subfolders
XCACLS MyFolder /T /E /G guests:f
:: Grant guests only read access to all files in and below MyFolder,
:: new folders created will be Read Access only, new files will not inherit any rights.
XCACLS MyFolder /T /P guests:R;Tr
:: Grant guests only execute access to all files in and below MyFolder
XCACLS MyFolder /T /P guests:x
:: Take Ownership of "Application Data" folder and grant Administrators Full control
(:OF)
:: Preserve existing permissions (/E) & apply to subfolders (/T)
XCACLS "Application Data" /E /g Administrators:OF /T
"I spent most of the eighties, most of my life, riding around in somebody else's car, in
possession of, or ingested of, something illegal, on my way from something illegal to
something illegal with many illegal things happening all around me" Iggy Pop
Related:
CACLS Display or modify Access Control Lists (ACLs) for files and folders
DIR /Q Display the owner for a list of files (try it for Program files)
AccessEnum GUI to browse a tree view of user privs
NTRIGHTS Edit user account rights
PERMS Show permissions for a user
SHOWACL Show file Access Control Lists (win 2000)
SHOWACCS Show ACLs on the registry, file system, file and print shares
SUBINACL Change an ACL's user/domain
ATTRIB Display or change file attributes
Permissions & Local/Global Workgroups
Permissions explained Microsoft.com
Accessbased Enumeration Set file listing to only display files you can read (Win
2003)
Q245031 Change Registry Permissions from the command line
Q822790 Xcacls /E Objects do not inherit permissions as expected.
ACL utils: SetAcl or FileACL
Equivalent Linux BASH commands:
chmod Change access permissions
chown Change file owner and group
XCOPY
Copy files and/or directory trees to another folder. XCOPY is similar to the COPY
command except that it has additional switches to specify both the source and
destination in detail.
XCOPY is particularly useful when copying files from CDROM to a hard drive, as it
will automatically remove the readonly attribute.
Syntax
XCOPY source [destination] [options]
Key
source : Pathname for the file(s) to be copied.
Source Options
/D:mm-dd-yyyy
Copy files that have changed since mm-dd-yyyy.
If no date is given, the default is to copy
files with a modification date before today.
(at least 1 day before)
/U Copy only files that already exist in
destination.
/EXCLUDE:file1[+file2][+file3]...
Copy Options
Destination Options
Examples:
To copy a file:
XCOPY C:\utils\MyFile D:\Backup\CopyFile
To copy a folder:
XCOPY C:\utils D:\Backup\utils /i
To copy a folder including all subfolders.
XCOPY C:\utils\* D:\Backup\utils /s /i
The /i defines the destination as a folder.
Notes
In many cases the functionality of XCOPY is superseded by ROBOCOPY.
To force the overwriting of destination files under both NT4 and Windows2000 use
the COPYCMD environment variable:
SET COPYCMD=/Y
This will turn off the prompt in Win2000 and will be ignored by NT4 (which overwrites
by default).
When comparing Dates/Times the granularity (the finest increment of the timestamp)
is 2 seconds for a FAT volume and 0.1 microsecond for an NTFS volume.
The WinXP version of XCOPY will accept wildcards for the source e.g. *.txt
It is also more forgiving with trailing backslashes
Related Commands:
COPY Copy one or more files to another location
DEL Delete files
MOVE Move a file from one folder to another
ROBOCOPY Robust File and Folder Copy
Fcopy File Copy for MMQ (copy changed files & compress. (Win 2K ResKit)
Permcopy Copy share & file ACLs from one share to another. (Win 2K ResKit)
MTC XCopy and create a log file. (Win 2K ResKit)
Q240268 XCOPY changes in Win 2K
Equivalent Linux BASH commands:
cp Copy one or more files to another location
install Copy files and set attributes