A
ADDUSERS : Add or list users to/from a CSV file
ADDUSERS.exe (Resource Kit)
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
Filename - The comma-delimited file that AddUsers uses for data.
/s:x - Change the delimiter character used in filename to x.
e.g. /s:~ would make the delimiter "~"
Domain - Query the Primary Domain Controller (PDC) of domain.
You can also use \\Servername to specify the machine where user accounts are created or read.
AddUsers will use the local computer by default (if you do not specify Domain)
/c - Create user accounts, local groups, and global groups as specified by filename.
/d{:u} - Dump user accounts, local groups, and global groups to filename.
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.
/e - Erase the user accounts specified in the file name.
CAUTION: Be careful when erasing user accounts, as it is not possible to recreate
an account with the same SID. This option will not erase built-in accounts.
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 comma-delimited 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
ARP : Address Resolution Protocol
ARP.exe
ARP - Address Resolution Protocol
Display and modify the IP-to-Physical 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]
Add a static Arp entry for frequent accessed hosts
ARP -s ip_addr eth_addr [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.
-N if_addr Display the ARP entries for the network interface specified
by if_addr.
-d ip_addr Delete the host specified by ip_addr.
-d * will delete all hosts.
-s Add the host and associates the Internet address ip_addr
with the Physical address eth_addr. The Physical address is
given as 6 hexadecimal bytes separated by hyphens. The entry
is permanent.
eth_addr Specifies a physical address.
if_addr If present, this specifies the Internet address of the
interface whose address translation table should be modified.
If not present, the first applicable interface will be used.
If two hosts on the same sub-net cannot ping each other successfully, try running ARP -a to list the addresses on each computer to see if they have the correct MAC addresses.
A host's MAC address can be checked using IPCONFIG. If another host with a duplicate IP address exists on the network, the ARP cache may have had the MAC address for the other computer placed in it. ARP -d is used to delete an entry that may be incorrect.
Examples
Display the ARP cache tables for all interfaces:
arp -a
Display the ARP cache table for the interface on IP address 10.1.4.99:
arp -a -N 10.1.4.99
Add a static ARP cache entry on IP addr 10.1.4.77 to the physical address 00-AA-21-4A-2F-9A:
arp -s 10.1.4.77 00-AA-21-4A-2F-9A
~ ASSOC : Change file extension associations
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 double-click 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"
ASSOCIAT : One step file association
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.
AT : Schedule a command to run at a later time
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.
id : An id number AT assigns to each scheduled job.
/delete : Cancel a scheduled job. If id is omitted, all jobs are deleted.
/yes : Use with /delete to supress the confirmation message.
hh:mm : The time to run the command.
/interactive : Allow the job to interact with the desktop of
the current user when the job runs.
/every:day(s) : Run the command every day(s) of the week or month.
(default: dd=today)
/next:day(s) : Run the command on the next occurrence of the day.
(default: dd=today)
"command" : The batch program or command to run. If the path
to this includes spaces, put double quotation marks
around the path. "C:\Program Files\My Batch.cmd"
Day(s) are in this format: (English Locale EN)
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 command-line 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\
ATTRIB : Change file attributes
ATTRIB.exe
Display or change file attributes. Find Filenames.
Syntax
ATTRIB [ + attribute | - attribute ] [pathname] [/S [/D]]
Key
+ : Turn an attribute ON
- : Clear an attribute OFF
pathname : Drive and/or filename e.g. C:\*.txt
/S : Search the pathname including all subfolders.
/D : Process folders as well
attributes:
R Read-only (1)
H Hidden (2)
A Archive (32)
S System (4)
extended attributes:
E Encrypted
C Compressed (128:read-only)
I Not content-indexed
L Symbolic link/Junction (64:read-only)
O Offline
P Sparse file
T Temporary
The numeric values may be used when changing attributes with VBS/WSH
If no attribute is specified attrib will return the current attribute settings. Used with just the /S option ATTRIB will quickly search for a particular filename.
Hidden and System attributes take priority.
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
File Attributes
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.
Directory Attributes
You can display or change the attributes for a directory/folder. 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:*.*
The Read-only attribute for a folder is generally ignored by applications, however the Read-only and System attributes are used by Windows Explorer to determine whether the folder is a special folder, such as My Documents, Favorites, Fonts, etc.
Setting the Read-Only attribute on a folder can affect performance, particularly on shared drives because Windows Explorer will be forced to request the Desktop.ini of every sub-folder to see if any special folder settings need to be set.
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.
B
BOOTCFG : Edit Windows boot settings
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
BOOTCFG /copy Duplicate the entries for an OS instance.
BOOTCFG /dbg1394 Configure 1394 port debugging
BOOTCFG /debug Edit the debug settings for an OS.
BOOTCFG /default Specify the default OS
BOOTCFG /delete Delete an OS entry [operating systems] section of Boot.ini
BOOTCFG /ems Redirect the EMS console to a remote computer (server only).
(Emergency Management Services)
BOOTCFG /list List entries in boot.ini
BOOTCFG /query Display section entries from Boot.ini
BOOTCFG /raw Add OS load options, specified as a string
BOOTCFG /rebuild Totally rebuild boot.ini (use when Windows won't start)
BOOTCFG /rmsw Remove OS load options for an OS
BOOTCFG /timeout Change the OS time-out value.
Detailed options for all the above are available from BOOTCFG /? Items in bold are only available from the recovery console
Default identification strings:
OS Load Options = /Fastdetect
Load Identifier = Microsoft Windows XP Professional
If you intend to rebuild the boot.ini file, delete it first - boot into the recovery console then:
ATTRIB -H -R -S C:\Boot.ini
Bootcfg /Rebuild
Fixboot
BROWSTAT Get domain, browser and PDC info
BROWSTAT.exe (Resource Kit)
Get domain, browser and PDC info.
Syntax
BROWSTAT sta : Status Displays Transport,Primary DNS
and Backup DNS servers.
BROWSTAT sta -v domain : Status Display (Verbose)
includes Server OS and active browsers.
BROWSTAT gp Transport Domain : List the PDC name (using NetBIOS)
BROWSTAT gm Transport Domain : List the remote Master Browser name
(using NetBIOS)
BROWSTAT gb Transport : List of backup DNS Servers
BROWSTAT wfw : List WFW servers that are running browser.
BROWSTAT sts \\ServerName : Dump browser statistics
BROWSTAT TICKLE : Force remote master to stop.
BROWSTAT ELECT : Force election on remote domain
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›
In the list displays, the following flags are used:
W = Workstation NT = Windows NT
S = Server W95 = Windows95
SQL = SQLServer WFW = WindowsForWorkgroups
SS = StandardServer MFPN= MS Netware
PDC = PrimaryDomainController NV = Novell
BDC = BackupDomainController XN = Xenix
TS=TimeSource
MBC=MemberServer
PQ=PrintServer
DL=DialinServer
AFP=AFPServer
OSF=OSFServer
VMS=VMSServer
PBR=PotentialBrowser
BBR=BackupBrowser,
MBR=MasterBrowser
DMB=DomainMasterBrowser
DFS=DistributedFileSystem
C
CACLS : Change file permissions
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:
/T Search the pathname including all subfolders.
/E Edit ACL (leave existing rights unchanged)
/C Continue on access denied errors.
/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.
In all the options above "user" can be a UserName
or a Workgroup (either local or global)
If a UserName or WGname includes spaces then it must
be surrounded with quotes e.g. "Authenticated Users"
If no options are specified CACLS will display the ACLs for the file(s)
Other features to try
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:
ECHO Y| CACLS /g <username>:<permission>
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.
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:
OI - Object inherit - This folder and files. (no inheritance to subfolders)
CI - Container inherit - This folder and subfolders.
IO - Inherit only - The ACE does not apply to the current file/directory
These can be combined as folllows:
(OI)(CI) This folder, subfolders, and files.
(OI)(CI)(IO) Subfolders and files only.
(CI)(IO) Subfolders only.
(OI) (IO) Files only.
So BUILTIN\Administrators:(OI)(CI)F means that both files and Subdirectories will inherit 'F' (Fullcontrol)
similarly (CI)R means Directories will inherit 'R' (Read folders only = List permission)
When cacls is applied to the current folder only there is no inheritance and so no output.
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 Read-Only 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 Full-control:
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
ATTRIB.exe
Display or change file attributes. Find Filenames.
Syntax
ATTRIB [ + attribute | - attribute ] [pathname] [/S [/D]]
Key
+ : Turn an attribute ON
- : Clear an attribute OFF
pathname : Drive and/or filename e.g. C:\*.txt
/S : Search the pathname including all subfolders.
/D : Process folders as well
attributes:
R Read-only (1)
H Hidden (2)
A Archive (32)
S System (4)
extended attributes:
E Encrypted
C Compressed (128:read-only)
I Not content-indexed
L Symbolic link/Junction (64:read-only)
O Offline
P Sparse file
T Temporary
The numeric values may be used when changing attributes with VBS/WSH
If no attribute is specified attrib will return the current attribute settings. Used with just the /S option ATTRIB will quickly search for a particular filename.
Hidden and System attributes take priority.
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
File Attributes
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.
Directory Attributes
You can display or change the attributes for a directory/folder. 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:*.*
The Read-only attribute for a folder is generally ignored by applications, however the Read-only and System attributes are used by Windows Explorer to determine whether the folder is a special folder, such as My Documents, Favorites, Fonts, etc.
Setting the Read-Only attribute on a folder can affect performance, particularly on shared drives because Windows Explorer will be forced to request the Desktop.ini of every sub-folder to see if any special folder settings need to be set.
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.
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:
/T Search the pathname including all subfolders.
/E Edit ACL (leave existing rights unchanged)
/C Continue on access denied errors.
/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.
In all the options above "user" can be a UserName
or a Workgroup (either local or global)
If a UserName or WGname includes spaces then it must
be surrounded with quotes e.g. "Authenticated Users"
If no options are specified CACLS will display the ACLs for the file(s)
Other features to try
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:
ECHO Y| CACLS /g <username>:<permission>
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.
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:
OI - Object inherit - This folder and files. (no inheritance to subfolders)
CI - Container inherit - This folder and subfolders.
IO - Inherit only - The ACE does not apply to the current file/directory
These can be combined as folllows:
(OI)(CI) This folder, subfolders, and files.
(OI)(CI)(IO) Subfolders and files only.
(CI)(IO) Subfolders only.
(OI) (IO) Files only.
So BUILTIN\Administrators:(OI)(CI)F means that both files and Subdirectories will inherit 'F' (Fullcontrol)
similarly (CI)R means Directories will inherit 'R' (Read folders only = List permission)
When cacls is applied to the current folder only there is no inheritance and so no output.
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 Read-Only 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 Full-control:
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
~ CALL : Call one batch program from another
CALL
Call one batch program from another.
Syntax
CALL [drive:][path]filename [parameters]
CALL :label [parameters]
CALL internal_cmd
Key:
pathname The batch program to run
parameters Any command-line arguments
:label Jump to a label in the current batch script.
internal_cmd Any internal command, first expanding any variables in the argument
CALL a second batch file
The CALL command will launch a new batch file context along with any specified arguments.
When the end of the second batch file is reached (or if EXIT is used), control will return to just after the initial CALL statement.
CALL a subroutine (:label)
The CALL command will pass control to the statement after the label specified along with any specified arguments .
To exit the subroutine specify GOTO:eof this will transfer control to the end of the current subroutine.
Arguments can be passed either as a simple string or using a variable:
CALL MyScript.cmd "1234"
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
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
SETLOCAL will make subroutine variables invisible
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 can be done by with an ENDLOCAL command on the same line as a SET statement(s)
For example
@ECHO OFF
SET _sum=64000
CALL :s_calc 200 100
Echo %_return%
Echo %_sum%
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 recommended.
Advanced usage : CALLing internal commands
In addition to the above, CALL can also be used to run any internal command (SET, ECHO etc) and also expand any environment variables passed on the same line.
For example
@ECHO off
SETLOCAL
set server1=frodo3
set server2=gandalf4
set server3=ascom5
set server4=last1
::run the Loop for each of the servers
call :loop server1
call :loop server2
call :loop server3
call :loop server4
goto:eof
:loop
set _var=%1
:: Evaluate the server name
CALL SET _result=%%%_var%%%
echo The server name is %_result%
goto :eof
:s_next_bit
:: continue below
:: Note the line shown in bold has three '%' symbols
:: The CALL will expand this to: SET _result=%server1%
Each CALL does one substitution of the variables. (You can also do CALL CALL... for multiple substitutions)
If you CALL an executable or resource kit utility make sure it's available on the machine where the batch will be running, also check you have the latest versions of any resource kit utilities.
If Command Extensions are disabled, the CALL command will not accept batch labels.
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
My_Command : The NT command, program or batch script to be run.
This can even be several commands separated with '&&'
(the whole should also be surrounded by "quotes")
/T:fg Sets the foreground/background colours
/X Enable extensions to CMD.EXE
under Windows 2000 you can also use /E:ON
/Y Disable extensions to CMD.EXE
under Windows 2000 you can also use /E:OFF
/A Output ANSI Characters
/U Output UNICODE Characters
These 2 swiches are useful when piping or redirecting to a file
Most common text files under WinNT are ANSI, use these switches
when you need to convert the character set.
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
/F:OFF Disable auto-completion of pathnames entered at the CMD prompt (default)
At the command prompt Ctrl-D gives folder name completion and
Ctrl-F gives file and folder name completion.
These ctrl keys build up a list of paths that match and display the
first matching path. Thereafter, repeated pressing of the same control
key will cycle through the list of matching paths. Pressing SHIFT
with the control key will move through the list backwards.
/Q Turn echo off
/S Strip quote characters from the command_line
/V:ON Enable delayed environment variable expansion
this allows a FOR loop to specify !variable! instead of %variable%
expanding the variable at execution time instead of at input time.
/V:OFF Disable delayed environment expansion.
Environment expansion preference can be set permanently in the registry
HKLM | HKCU \Software\Microsoft\Command Processor\DelayedExpansion
Set to either 0x1 or 0x0
/knetdiag /debug
/knetdiag /fix
The knetdiag switches are undocumented and work in XP only
they list and (may) fix these networking issues.
If /C or /K is specified, then the remainder of the command line is
processed as an immediate command in the new shell. Multiple commands
separated by the command separator '&&' are accepted if surrounded by quotes.
The following logic is used to process quote (") characters:
1. If all of the following conditions are met, then quote characters
on the command line are preserved:
- 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.
2. Otherwise, old behavior is to see if the first character is
a quote character and if so, strip the leading character and
remove the last quote character on the command line, preserving
any text after the last quote character.
Command.com vs cmd.exe
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 left-mouse button, select a line of text, now right-click anywhere in the window to COPY. (in NT 4 there is no popup menu)
This saves the selected text to the clipboard.
PASTE:
Now right-click 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 CTRL-S
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 CTRL-C
If one batch file CALLs another batch file CTRL-C will exit both batch scripts.
If CMD /c is used to call one batch file from another then CTRL-C 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
~ CD : Change Directory - move to a specific Folder
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 ..\..
To change to the ROOT directory.
CD \
To display the current directory in the specified drive.
Type CD <drive>:
To display the current drive and directory.
CD
Moving down the folder tree with a full path reference to the ROOT folder...
C:\winnt> CD \winnt\java
C:\winnt\java>
Moving down the folder tree with a reference RELATIVE to the current folder...
C:\winnt> CD java
C:\winnt\java>
Moving up and down the folder tree in one command...
C:\winnt\java> CD ..\system32
C:\winnt\system32>
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 : Change Terminal Server Session properties
CHANGE
Change Terminal Server Session properties, use when installing software on a terminal server.
Syntax
CHANGE USER /options
CHANGE LOGON /options
Options:
To change .INI file mapping: (administrator rights required)
CHANGE USER /INSTALL Enable install mode. This command has to be run before
installing any new software on a Terminal Server.
This will create a .ini file for the application
in the TS system directory.
CHANGE USER /EXECUTE Enable execute mode (default)
Run this when an installation is complete.
CHANGE USER /QUERY Display current settings.
To enable or disable terminal session logins:
CHANGE LOGON /QUERY Query current terminal session login mode.
CHANGE LOGON /ENABLE Enable user login from terminal sessions.
CHANGE LOGON /DISABLE Disable user login from terminal sessions.
To list or change COM port mappings for the current session.
This can allow DOS applications to access high numbered ports e.g. COM12
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.
CHKDSK : Check Disk - check and repair disk problems
chkdsk.exe
Check Disk - check and repair disk problems
Syntax
CHKDSK [drive:][[path]filename] [/F] [/V] [/R] [/L[:size]]
Key
[drive:] The drive to check.
filename File(s) to check for fragmentation (FAT only).
/F Automatically Fix file system errors on the disk.
/X Fix file system errors on the disk, (Win2003 and above)
dismounts the volume first, closing all open file handles.
/R Scan for and attempt Recovery of bad sectors.
/V Display the full path and name of every file on the disk.
/L:size NTFS only: change the log file size to the specified number of kilobytes.
If size is not specified, displays the current log size and the drive type
(FAT or NTFS).
/C Skip directory corruption checks.
/I Skip corruption checks that compare directory entries to the
file record segment (FRS) in the volume's master file table (MFT)
Example:
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
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 disk with a very large number of files (millions), chkdsk may take a long time to complete.
When you delete a file or folder that has 'custom' permissions, the ACL is not deleted, it is cached. Chkdsk /f will remove ACLs that are no longer used. This is often the cause of the rather worrying message: "Windows found problems with the file system. Run chkdsk with the /F (fix) option to correct these."
It is normal for chkdsk /F to remove unused index entries and unused security descriptors every time you run it, these do not indicate a problem with the file system.
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 in-use (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.
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
Running at bootup is often the easiest way to close all open file handles.
Use the GUI, chkntfs or the FSUTIL dirty commands to set or query the volumes 'dirty' bit so that Windows will run chkdsk when the computer is restarted.
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.
To issue chkdsk on a hard drive you must be a member of the Administrators group.
When CHKDSK is set to run at boot-up 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.
CHKNTFS : Check the NTFS file system
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.
/C : Check - schedules chkdsk to be run at the next reboot.
/X : Exclude a drive from the default boot-time check.
Excluded drives are not accumulated between command invocations.
/T : Change the Autochk.exe initiation countdown time (time in seconds)
If you don't specify Time: displays the current countdown time.
/D : Restore the machine to the default behavior; all drives are
checked at boot time and chkdsk is run on those that are dirty.
This undoes the effect of the /X option.
If no switches are specified, CHKNTFS will display the status of the dirty bit for each drive.
/T option is new in Win XP
chkdsk.exe
Check Disk - check and repair disk problems
Syntax
CHKDSK [drive:][[path]filename] [/F] [/V] [/R] [/L[:size]]
Key
[drive:] The drive to check.
filename File(s) to check for fragmentation (FAT only).
/F Automatically Fix file system errors on the disk.
/X Fix file system errors on the disk, (Win2003 and above)
dismounts the volume first, closing all open file handles.
/R Scan for and attempt Recovery of bad sectors.
/V Display the full path and name of every file on the disk.
/L:size NTFS only: change the log file size to the specified number of kilobytes.
If size is not specified, displays the current log size and the drive type
(FAT or NTFS).
/C Skip directory corruption checks.
/I Skip corruption checks that compare directory entries to the
file record segment (FRS) in the volume's master file table (MFT)
Example:
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
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 disk with a very large number of files (millions), chkdsk may take a long time to complete.
When you delete a file or folder that has 'custom' permissions, the ACL is not deleted, it is cached. Chkdsk /f will remove ACLs that are no longer used. This is often the cause of the rather worrying message: "Windows found problems with the file system. Run chkdsk with the /F (fix) option to correct these."
It is normal for chkdsk /F to remove unused index entries and unused security descriptors every time you run it, these do not indicate a problem with the file system.
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 in-use (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.
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
Running at bootup is often the easiest way to close all open file handles.
Use the GUI, chkntfs or the FSUTIL dirty commands to set or query the volumes 'dirty' bit so that Windows will run chkdsk when the computer is restarted.
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.
To issue chkdsk on a hard drive you must be a member of the Administrators group.
When CHKDSK is set to run at boot-up 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.
CHOICE : Accept keyboard input to a batch file
CHOICE.exe (Resource Kit/Standard Vista command)
Accept user input to a batch file.
Choice allows single key-presses 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
The Windows 2003 version has some slight differences:
CHOICE [/c [choiceKeys]] [/N] [/CS] [/t Timeout /d Choice] [/m 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.
/CS : Case Sensitive.
/T dd : Timeout in dd seconds
/d choiceKey : Choice made on Timeout
/m text : Message string to describe the choices available
ERRORLEVEL will return the numerical offset of choiceKeys.
Availability
Choice.com was originally supplied on the Windows 95 install CD, however there are some issues with this version under NT - multiple concurrent invocations of CHOICE will clobber each other. CHOICE.com will also burn a lot of CPU's when in a wait state.
The NT and 2000 Resource Kits contain CHOICE.EXE which behaves a lot better.
In Windows 2003 CHOICE became a built-in command so it is no longer in the resource kit.
Examples:
CHOICE /C:FH /M 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
IF
Conditionally perform a command.
File syntax
IF [NOT] EXIST filename command
IF [NOT] EXIST filename (command) ELSE (command)
String syntax
IF [/I] [NOT] item1==item2 command
IF [/I] item1 compare-op item2 command
IF [/I] item1 compare-op item2 (command) ELSE (command)
Error Check Syntax
IF [NOT] DEFINED variable command
IF [NOT] ERRORLEVEL number command
IF CMDEXTVERSION number 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
NOT : perform the command if the condition is false.
== : perform the command if the two strings are equal.
/I : Do a case Insensitive string comparison.
compare-op : may be one of
EQU : equal
NEQ : not equal
LSS : less than <
LEQ : less than or equal <=
GTR : greater than >
GEQ : greater than or equal >=
This 3 digit syntax is necessary because the > and <
are recognised as redirection symbols
IF EXIST filename will return true if the file exists (this is not case sensitive).
IF ERRORLEVEL statements should be read as IF Errorlevel >= number
i.e.
IF ERRORLEVEL 0 will return TRUE when the errorlevel is 64
IF ERRORLEVEL 1 will return TRUE when the errorlevel is 2
IF ERRORLEVEL 1 will return FALSE when the errorlevel is 0
Examples:
IF EXIST C:\install.log (echo complete) ELSE (echo failed)
IF DEFINED _department ECHO Got the department variable
IF DEFINED _commission SET /A _salary=%_salary% + %_commission%
IF CMDEXTVERSION 1 GOTO start_process
IF ERRORLEVEL EQU 2 goto sub_problem2
Does %1 exist?
To test for the existence of a command line paramater - use empty brackets like this
IF [%1]==[] ECHO Value Missing
or
IF [%1] EQU [] ECHO Value Missing
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 (
) 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 always 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 EXIT /B command.
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.
CIPHER : Encrypt or Decrypt files/folders
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 [...]]
New recovery agent certificate:
CIPHER /r:PathNameWithoutExtension
Remove data:
CIPHER /w:PathName
Backup Keys:
CIPHER /x[:PathName]
options:
/e Encrypt the folders.
Folders are marked so that files that are added to the folder later
are encrypted too.
/d Decrypt the folders.
Folders are marked so that files that are added to the folder later
are encrypted too.
/s:Folder
Performs the operation in the folder and all subfolders.
/a Perform the operation for files and directories.
/i Continue even after errors occur.
By default, cipher stops when it encounters an error.
/f Force the encryption or decryption of all specified objects.
By default, cipher skips files that have been encrypted or decrypted already.
/q Quiet - Report only essential information.
/h Display files with hidden or system attributes.
By default, these files are not encrypted or decrypted.
/k Create a new file encryption key for the user running cipher.
/u Update the user's file encryption key or recovery agent's key
to the current ones in all of the encrypted files on local drives
(that is, if the keys have been changed).
This option only works with /n.
/n Prevent keys from being updated.
Use this option to find all of the encrypted files on the local drives.
This option only works with /u.
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 read-only.
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
CleanMgr : Automated cleanup of Temp files, recycle bin
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.
/sageset:n - Display the Disk Cleanup Settings dialog box and create
a registry key to store the settings you select.
The n value is stored in the registry and allows you to
specify different tasks for Disk Cleanup to run.
n can be any integer from 0 to 65535.
Specify the %systemroot% drive to see all the available options.
/sagerun:n - Run task 'n'
All drives in the computer will be enumerated, and the
selected profile will be run against each drive.
Only one of the 3 options above can be run at a time
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
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
CLEARMEM :Clear memory leaks
CLIP : Copy STDIN to the Windows clipboard.
CLIP.exe (Resource Kit)
Copy the result of any command to the Windows clipboard.
Syntax
command | CLIP
CLIP < filename.txt
When using clip in a batch script you should warn the user that their clipboard is about to be overwritten.
For Example:
DIR | CLIP
DATE /t | CLIP
~ CLS : Clear the screen
CLUSTER : Windows Clustering
CMD :Start a new CMD shell
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
My_Command : The NT command, program or batch script to be run.
This can even be several commands separated with '&&'
(the whole should also be surrounded by "quotes")
/T:fg Sets the foreground/background colours
/X Enable extensions to CMD.EXE
under Windows 2000 you can also use /E:ON
/Y Disable extensions to CMD.EXE
under Windows 2000 you can also use /E:OFF
/A Output ANSI Characters
/U Output UNICODE Characters
These 2 swiches are useful when piping or redirecting to a file
Most common text files under WinNT are ANSI, use these switches
when you need to convert the character set.
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
/F:OFF Disable auto-completion of pathnames entered at the CMD prompt (default)
At the command prompt Ctrl-D gives folder name completion and
Ctrl-F gives file and folder name completion.
These ctrl keys build up a list of paths that match and display the
first matching path. Thereafter, repeated pressing of the same control
key will cycle through the list of matching paths. Pressing SHIFT
with the control key will move through the list backwards.
/Q Turn echo off
/S Strip quote characters from the command_line
/V:ON Enable delayed environment variable expansion
this allows a FOR loop to specify !variable! instead of %variable%
expanding the variable at execution time instead of at input time.
/V:OFF Disable delayed environment expansion.
Environment expansion preference can be set permanently in the registry
HKLM | HKCU \Software\Microsoft\Command Processor\DelayedExpansion
Set to either 0x1 or 0x0
/knetdiag /debug
/knetdiag /fix
The knetdiag switches are undocumented and work in XP only
they list and (may) fix these networking issues.
If /C or /K is specified, then the remainder of the command line is
processed as an immediate command in the new shell. Multiple commands
separated by the command separator '&&' are accepted if surrounded by quotes.
The following logic is used to process quote (") characters:
1. If all of the following conditions are met, then quote characters
on the command line are preserved:
- 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.
2. Otherwise, old behavior is to see if the first character is
a quote character and if so, strip the leading character and
remove the last quote character on the command line, preserving
any text after the last quote character.
Command.com vs cmd.exe
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 left-mouse button, select a line of text, now right-click anywhere in the window to COPY. (in NT 4 there is no popup menu)
This saves the selected text to the clipboard.
PASTE:
Now right-click 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 CTRL-S
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 CTRL-C
If one batch file CALLs another batch file CTRL-C will exit both batch scripts.
If CMD /c is used to call one batch file from another then CTRL-C 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
~ COLOR : Change colors of the CMD window
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
The COLOR command will change the color of all the text in the window, to change individual lines or words you need to use PowerShell (Vista or Win XP) like this: Write-Host -ForeGroundColor Red "some text in red" –nonewline
COMP : Compare the contents of two files or sets of files
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)
pathname2 The path and filename of the second file(s)
/D Display differences in decimal format. (default)
/A Display differences in ASCII characters.
/L Display line numbers for differences.
/N=number Compare only the first X number of lines in the file.
/C do a case insensitive string comparison
Running COMP with no parameters will result in a prompt for the 2 files and any options
To compare sets of files, use wildcards in pathname1 and pathname2 parameters.
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>
CON2PRT : Connect or disconnect a Printer
CON2PRT.exe (Zero Admin Kit)
Connect 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.
~ COPY : Copy one or more files to another location
COPY
Copy one or more files to another location
Syntax
COPY source destination [options]
COPY source1 + source2.. destination [options]
Key
source : Pathname for the file or files to be copied.
/A : ASCII text file (default)
/B : Binary file copy - will copy extended characters.
destination : Pathname for the new file(s).
/V : Verify that the new files were written correctly.
/N : If at all possible, use only a short filename (8.3) when creating
a destination file. This may be necessary when copying between disks
that are formatted differently e.g NTFS and VFAT, or when archiving
data to an ISO9660 CDROM.
/Z : Copy files in restartable mode. If the copy is interrupted
part way through, it will restart if possible. (use on slow networks)
/Y : Suppress confirmation prompt (Windows 2000 only)
/-Y : Enable confirmation prompt (Windows 2000 only)
Prompt to overwrite destination file
NT 4 will overwrite destination files without any prompt, Windows 2000 and above will prompt unless the COPY command is being executed from within a batch script.
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
Copy from the console (accept user input)
COPY CON filename.txt
Then type the input text followed by ^Z (Control key & Z)
To do this in Powershell use the following function:
function copycon {
[system.console]::in.readtoend()
}
Examples:
In the current folder
COPY oldfile.doc newfile.doc
Copy from a different folder/directory:
COPY "C:\my work\some file.doc" "D:\New docs\newfile.doc"
Specify the source only, with a wildcard will copy all the files into the current directory:
COPY "C:\my work\*.doc"
Specify the source with a wildcard and the destination as a single file, this is generally only useful with plain text files.
COPY "C:\my work\*.txt" "D:\New docs\combined.txt"
Quiet copy (no feedback on screen)
COPY oldfile.doc newfile.doc >nul
CSCcmd : Client-side caching (Offline Files)
CSCcmd (Client-side caching command (Q884739 - Non Microsoft mirror)
Run this utility on a client PC to configure offline files. Offline files (CSC) allow the client PC to access copies of network files while disconnected from the network/domain. Files can be synchronized with the network when connected.
Syntax
CSCCMD Option(s)
Options:
/ENABLE Enable Client-Side Caching (CSC) on this client.
Requires Local Administrator rights
/DISABLE Disable CSC, ensure all offline files are closed first.
/Enum[: \\Server\Share [\Path]] [/RECURSE]
Display all the shares in the local cache.
With the /RECURSE option, this will display the contents
of the shares within a parent share.
/DISCONNECT:\\Server
/DISCONNECT:\\Server\Share
Disconnect a server or share from CSC on this client.
/MOVESHARE:\\Server1\Share \\Server2\Share
Move files and folders from one share to another in the cache.
This is useful if the local cache must point to a new/renamed server location.
/RESID Restamp all the entries in the Windows offline files (CSC) database
with a new user security identifier (SID).
useful when moving user accounts from an NT 4.0 domain to 2003.
/ISENABLED Is CSC is enabled on this client PC. (synonym: /ISCSCENABLED)
/PIN2:\\server\share\path [/USER] [/SYSTEM] [/USERINHERIT] [/SYSTEMINHERIT]
Pin shared resources:
Use the PIN2: /USER option to pin a file. This has the same result
as using the Offline Files dialog box to cache the file.
Use PIN2: /SYSTEM to specify that the share will be pinned via Group Policy.
/USERINHERIT and /SYSTEMINHERIT] will determine how the pin data is inherited.
/PIN2:filename /FILELIST [/UNICODE] [/USER] [/SYSTEM] [/USERINHERIT] [/SYSTEMINHERIT]
Use a file to describe the objects to pin
The file contains the UNC path of each object to pin.
/FILELIST = the objects are separated by a carriage return/linefeed.
/UNPIN2:\\server\share\path [/USER] [/SYSTEM] [/USERINHERIT] [/SYSTEMINHERIT] [/RECURSE]
UnPin a shared resource or remove a shared resource from the local cache.
with /RECURSE, CSCCMD will unpin all children of the path.
with /RECURSE2, CSCCMD will unpin the path and children of the path.
/UNPIN2:filename /FILELIST [/UNICODE] [/USER] [/SYSTEM] [/USERINHERIT] [/SYSTEMINHERIT]
UnPin specific shared resources listed in filename.
/FILELIST = the objects are separated by a carriage return/linefeed.
/FILL:\\Server\Share\Path
Copy server-side data to the local cache.
/FILL:FileName /FILELIST [/UNICODE]
Copy server-side data to the local cache using a file.
/DELETE:\\Server\Share\Path [/RECURSE] [/RECURSE2]
Delete a file, a directory, or a share from the local cache.
Ensure that the directory/share is empty before you use this switch.
with /RECURSE, CSCCMD tool only operates on the children of the path.
with /RECURSE2, CSCCMD operates on the path and children of the path.
/ISSERVEROFFLINE:\\Server
Does CSC consider \\server to be offline.
To get a reliable response from this switch, you must first open a
share/file/directory from the local cache for \\server
/SETSPACE:Bytes
Specify the disk space in bytes to allocate to temporary offline files.
These files are nonpinned, auto-cached files.
This is similar to the function provided in the Offline Files dialog box.
/CHECKDB [/QUICK]
Examine the CSC database and display any database error flags.
/QUICK will skip the enumeration and just display database errors.
/EXTRACT[:\\Server\Share[\Path]] /TARGET:Path [/RECURSE] [/ONLYMODIFIED] [/STOPONERROR]
Extract a file, a directory, or a directory tree from the local cache.
This requires Local Administrator permissions
/TARGET will specify a destination.(which need not already exist)
/ONLYMODIFIED, extract only files that have been modified offline.
/STOPONERROR, stop the extract if an error occurs.
Offline files are most often used with laptops to provide access to data when on the move. Folder redirection can be setup to place the users My Documents on a server share, and then Offline Files can be set to copy and cache the data to the laptops C: drive.
This arrangement allows faster synchronisation of files than a full roaming profile (which also synchronises other things you probably don't need on a laptop.)
The /PIN2 switch does not copy the content of the shared resource into the local cache. Pinning is not sufficient to make the files available offline. After you use the /PIN2 switch, you must run CSCCMD /FILL to copy the content of the shared resource to the local cache.
When using FILELIST, any white space at the start of a file is ignored.
With the /UNICODE option, CSCCMD will create or read a file list in Unicode text format.
CSC is available for Windows 2000/XP/2003.
Examples
Move a server share:
csccmd /MOVESHARE:\\oldserver\share \\newserver\share
csccmd /RESID
CSVDE : Import or Export Active Directory data
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]
Import from File:
CSVDE -i [-f FileName] [options]
LDIFDE -i [-f FileName] [options]
Key
-f Filename Input or Output filename
-s servername The server to bind to
-c FromDN ToDN Replace occurrences of FromDN to ToDN
-v Verbose
-j Path Folder to store log files
-t Port_Number (default = 389)
-? Help
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.
Note to successfully import a file it must contain as a minimum
The DN(distinguished name), DisplayName and ObjectClass
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 (comma-separated 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 cross-platform 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 re-enable 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 and create C:\MyLogfiles\csv.log and C:\MyLogfiles\csv.err
CSVDE -i -f MyDomain.csv -j C:\MyLogfiles\
D
~ DATE Display or set the date
DATE
Display or change the date
Syntax
to display the date
DATE /T
to set the system date
DATE
or
DATE <date_today>
A typical output from DATE /T is "Mon 11/09/2000" but this is dependent on the country code.
The date formats for different country codes are as follows:
Country or language CountryCode Date format Time format
International English 061 23/01/1997 17:35:00.00
Canadian-French 002 1997-01-23 17:35:00
Date Formatting
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:
GetDate.cmd - Get todays Date (any region, any OS)
datetime.vbs - Get Date, Time and daylight savings
GetDate.cmd
@echo off&SETLOCAL
:: This will return date into environment vars
:: Works on any NT/2K/XP machine independent of regional date settings
:: 20 March 2002
FOR /f "tokens=1-4 delims=/-. " %%G IN ('date /t') DO (call :s_fixdate %%G %%H %%I %%J)
goto :s_print_the_date
:s_fixdate
if "%1:~0,1%" GTR "9" shift
FOR /f "skip=1 tokens=2-4 delims=(-)" %%G IN ('echo.^|date') DO (
set %%G=%1&set %%H=%2&set %%I=%3)
goto :eof
:s_print_the_date
echo Month:[%mm%] Day:[%dd%] Year:[%yy%]
ENDLOCAL&SET mm=%mm%&SET dd=%dd%&SET yy=%yy%
The above works by taking advantage of a quirk in the date command first noticed by Michael Jerkovic - the DATE command will display something like:
The current date is: Fri 14/04/2000
Enter the new date: (dd-mm-yy)
The useful bit there is the (dd-mm-yy), on a machine with different regional settings it may appear as (mm-dd-yy)
The first FOR command returns the 3 numeric parts of the date e.g. 14 04 2000
The second FOR command returns the 3 text descriptions e.g. dd mm yy
Then the line set %%G=%1&set %%H=%2&set %%I=%3 creates the 3 variables and sets them = numeric values
Effectively: set dd=14&set mm=04&set yy=2000
On a machine with different regional settings this might become: set mm=04&set dd=14&set yy=2000
Datetime.vbs
' Syntax:
' CSCRIPT datetime.vbs
'Returns Year,Month,Day,Hour,Minute,Seconds,Offset from GMT, Daylight Savings=True/False
strComputer = "."
' Date and time
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
For Each objItem in colItems
dtmLocalTime = objItem.LocalDateTime
dtmMonth = Mid(dtmLocalTime, 5, 2)
dtmDay = Mid(dtmLocalTime, 7, 2)
dtmYear = Left(dtmLocalTime, 4)
dtmHour = Mid(dtmLocalTime, 9, 2)
dtmMinutes = Mid(dtmLocalTime, 11, 2)
dtmSeconds = Mid(dtmLocalTime, 13, 2)
Next
' Daylight savings
Set Win32Computer = objWMIService.ExecQuery("SELECT * FROM Win32_ComputerSystem")
For Each objItem In Win32Computer
oGMT = (objItem.CurrentTimeZone / 60)
DaySave = objItem.DaylightInEffect
Next
Wscript.Echo dtmYear & " " & dtmMonth & " " & dtmDay & " " & dtmHour & " " & dtmMinutes & " " & dtmSeconds & " " & oGMT & " " & DaySave
Win32_OperatingSystem is available on Windows NT/2000/XP/2003
Win32_ComputerSystem is available on Windows NT/2000/XP/2003
Alternatives: ' Win32_LocalTime also gives the time but is only available on XP/2003
TIME
Display or set the system time.
Syntax
TIME [new_time]
TIME
TIME /T
key
new_time : The time as HH:MM
TIME with no parameters will display the current time and prompt
for a new value. Pressing ENTER will keep the same time.
/T : Just display the time, formatted according to the current Regional settings.
Time Formatting
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
International English 061 03/01/1994 17:35:00.00
Canadian-French 002 1994-01-03 17:35:00
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
My_Command : The NT command, program or batch script to be run.
This can even be several commands separated with '&&'
(the whole should also be surrounded by "quotes")
/T:fg Sets the foreground/background colours
/X Enable extensions to CMD.EXE
under Windows 2000 you can also use /E:ON
/Y Disable extensions to CMD.EXE
under Windows 2000 you can also use /E:OFF
/A Output ANSI Characters
/U Output UNICODE Characters
These 2 swiches are useful when piping or redirecting to a file
Most common text files under WinNT are ANSI, use these switches
when you need to convert the character set.
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
/F:OFF Disable auto-completion of pathnames entered at the CMD prompt (default)
At the command prompt Ctrl-D gives folder name completion and
Ctrl-F gives file and folder name completion.
These ctrl keys build up a list of paths that match and display the
first matching path. Thereafter, repeated pressing of the same control
key will cycle through the list of matching paths. Pressing SHIFT
with the control key will move through the list backwards.
/Q Turn echo off
/S Strip quote characters from the command_line
/V:ON Enable delayed environment variable expansion
this allows a FOR loop to specify !variable! instead of %variable%
expanding the variable at execution time instead of at input time.
/V:OFF Disable delayed environment expansion.
Environment expansion preference can be set permanently in the registry
HKLM | HKCU \Software\Microsoft\Command Processor\DelayedExpansion
Set to either 0x1 or 0x0
/knetdiag /debug
/knetdiag /fix
The knetdiag switches are undocumented and work in XP only
they list and (may) fix these networking issues.
If /C or /K is specified, then the remainder of the command line is
processed as an immediate command in the new shell. Multiple commands
separated by the command separator '&&' are accepted if surrounded by quotes.
The following logic is used to process quote (") characters:
1. If all of the following conditions are met, then quote characters
on the command line are preserved:
- 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.
2. Otherwise, old behavior is to see if the first character is
a quote character and if so, strip the leading character and
remove the last quote character on the command line, preserving
any text after the last quote character.
Command.com vs cmd.exe
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 left-mouse button, select a line of text, now right-click anywhere in the window to COPY. (in NT 4 there is no popup menu)
This saves the selected text to the clipboard.
PASTE:
Now right-click 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 CTRL-S
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 CTRL-C
If one batch file CALLs another batch file CTRL-C will exit both batch scripts.
If CMD /c is used to call one batch file from another then CTRL-C 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
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
The COLOR command will change the color of all the text in the window, to change individual lines or words you need to use PowerShell (Vista or Win XP) like this: Write-Host -ForeGroundColor Red "some text in red" –nonewline
DEFRAG Defragment hard drive
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
~ DEL Delete one or more files
Delete one or more files.
Syntax
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.
/A Select files to delete based on file_attributes
file_attributes:
R Read-only -R NOT Read-only
S System -S NOT System
H Hidden -H NOT Hidden
A Archive -A NOT Archive
Wildcards: These can be combined with part of a filename
* Match any characters
? Match any ONE character
Examples:
To delete HelloWorld.TXT
DEL HelloWorld.TXT
To delete "Hello Big World.TXT"
To delete all files that start with the letter A
To delete all files that end with the letter A
To delete all files with a .DOC extension
To delete all read only files
To delete all files including any that are read only
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:
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 un-deleting it again, however you can turn any file into a zero-byte file to destroy the file allocation chain like this:
TYPE nul > 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.
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
for /f "Tokens=*" %%G in ('dir /B') do rd /s /q "%%G"
DELPROF Delete NT user profiles
DELPROF (Resource Kit)
Delete windows user profiles.
Syntax
DELPROF [options]
Key
/Q Quiet, no confirmation.
/I Ignore errors and continue deleting.
/P Prompts for confirmation before deleting each profile.
/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)
/R Delete roaming profile cache only ##
## = New in version 5.2 (XP resource kit)
Example:
delprof /D:14
DELTREE Delete a folder and all subfolders
Delete one or more files.
Syntax
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.
/A Select files to delete based on file_attributes
file_attributes:
R Read-only -R NOT Read-only
S System -S NOT System
H Hidden -H NOT Hidden
A Archive -A NOT Archive
Wildcards: These can be combined with part of a filename
* Match any characters
? Match any ONE character
Examples:
To delete HelloWorld.TXT
DEL HelloWorld.TXT
To delete "Hello Big World.TXT"
To delete all files that start with the letter A
To delete all files that end with the letter A
To delete all files with a .DOC extension
To delete all read only files
To delete all files including any that are read only
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:
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 un-deleting it again, however you can turn any file into a zero-byte file to destroy the file allocation chain like this:
TYPE nul > 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.
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
for /f "Tokens=*" %%G in ('dir /B') do rd /s /q "%%G"
popd
DevCon Device Manager Command Line Utility
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.
Example DevCon commands
devcon -m:\\test find pci\*
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.)
devcon -r install %WINDIR%\Inf\Netloop.inf *MSLOOP
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").
devcon classfilter upper !filter1 !filter2
Deletes the two specified filters.
devcon classfilter lower !badfilter +goodfilter
Replaces the "badfilter" with the "goodfilter".
devcon driverfiles =ports
Lists files that are associated with each device in the ports setup class.
devcon disable *MSLOOP
Disables all devices that have a hardware ID that ends in "MSLOOP" (including "*MSLOOP").
devcon drivernodes @ROOT\PCI_HAL\PNP0A03
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.
devcon enable '*MSLOOP
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.
devcon find pci\*
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\").
devcon find =ports *pnp*
Lists devices that are present that are a member of the ports setup class and that contain "PNP" in their hardware ID.
devcon find =ports @root\*
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.
devcon findall =ports
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.
devcon listclass usb 1394
Lists all devices that are present for each class named (in this case, USB and 1394).
devcon remove @usb\*
Removes all USB devices. Devices that are removed are listed with their removal status.
devcon rescan
Rescans for new Plug and Play devices.
devcon resources =ports
Lists the resources that are used by all devices in the ports setup class.
devcon restart =net @'ROOT\*MSLOOP\0000
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 all hardware IDs of mouse class devices on the system.
devcon sethwid @ROOT\LEGACY_BEEP\0000 := beep
Assign the hardware ID, beep, to the legacy beep device.
devcon stack =ports
Lists the expected driver stack for the device. This includes device and class upper/lower filters, and the controlling service.
devcon status @pci\*
Lists the status of each device present that has an instance ID that begins with "pci\".
devcon status @ACPI\PNP0501\1
Lists the status of a specific device instance, in this case an Advanced Configuration and Power Interface (ACPI)-enumerated serial port.
devcon status @root\rdp_mou\0000
Lists the status of the Microsoft Terminal Server or Terminal Services mouse driver.
devcon status *PNP05*
Lists the status of all COM ports.
devcon update mydev.inf *pnp0501
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 folders
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:
* Match any characters
? Match any ONE character
[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:
/A:D Folder /A:-D NOT Folder
/A:R Read-only /A:-R NOT Read-only
/A:H Hidden /A:-H NOT Hidden
/A:A Archive /A:-A NOT Archive
/A Show all files
several attributes may be combined e.g. /A:HD-R
[sorted] Sorted by /O:
/O:N Name /O:-N Name
/O:S file Size /O:-S file Size
/O:E file Extension /O:-E file Extension
/O:D Date & time /O:-D Date & time
/O:G Group folders first /O:-G Group folders last
several attributes may be combined e.g. /O:GEN
[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, file sizes or summary).
/L use Lowercase.
/Q Display the owner of the file.
/N long list format where filenames are on the far right.
/X As for /N but with the short filenames included.
/C Include thousand separator in file sizes.
/-C don't include thousand separator in file sizes.
/4 Display four-digit years
The switches above may be preset by adding them to an environment variable called DIRCMD.
For example: SET DIRCMD=/O:N /S
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.
WHERE (2K Resource Kit / Windows 2003)
Locate and display files in a directory tree.
The WHERE command is roughly equivalent to the UNIX 'which' command. 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.
/q Don't display the files but return either an exit code of 0 for success
or 1 for failure.
/f Display the output file name in quotation marks.
/t Display the size, time stamp, and date stamp of the file.
/e Report the executable type.
pattern The name of a folder, file, or set of files to be found.
you can use wildcard characters ( ? * ) and UNC paths.
As an alternative to this command you can use this 90-character batch file:
@for %%e in (%PATHEXT%) do @for %%i in (%1%%e) do @if NOT "%%~$PATH:i"=="" echo %%~$PATH:i
(from the OldNewthing blog)
Examples
Find all files named 'Zappa' in drive C: (including subdirectories)
WHERE /r c:\ Zappa
Find all files named 'Zappa' on the remote computer 'Server1' searching its subdirectories, and reporting the executable type for executable files
WHERE /r \\Server1\Share1 /e Zappa.*
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 read-only attribute.
Syntax
XCOPY source [destination] [options]
Key
source : Pathname for the file(s) to be copied.
destination : Pathname for the new file(s).
[options] can be any combination of the following:
Source Options
/A Copy files with the archive attribute set (default=Y)
/M Copy files with the archive attribute set and
turn off the archive attribute, use this option
when making regular Backups (default=Y)
/H Copy hidden and system files and folders (default=N)
/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.
/S Copy folders and subfolders
/E Copy folders and subfolders, including Empty folders.
May be used to modify /T.
/EXCLUDE:file1[+file2][+file3]...
(Windows 2000 only) The files can each contain one
or more full or partial pathnames to be excluded.
When any of these match any part of the absolute path
of a SOURCE file, then that file will be excluded.
For example, specifying a string like \obj\ or .obj will exclude
all files underneath the directory obj or all files with the
.obj extension respectively.
Copy Options
/W Prompt you to press a key before starting to copy.
/P Prompt before creating each file.
/Y (Windows 2000 only) Suppress prompt to confirm overwriting a file.
may be preset in the COPYCMD env variable.
/-Y (Windows 2000 only) Prompt to confirm overwriting a file.
/V Verify that the new files were written correctly.
/C Continue copying even if an error occurs.
/I If in doubt always assume the destination is a folder
e.g. when the destination does not exist.
/Z Copy files in restartable mode. If the copy is interrupted part
way through, it will restart if possible. (use on slow networks)
/Q Do not display file names while copying.
/F Display full source and destination file names while copying.
/L List only - Display files that would be copied.
Destination Options
/R Overwrite read-only files.
/T Create folder structure, but do not copy files. Do not
include empty folders or subfolders.
/T /E will include empty folders and subfolders.
/K Copy attributes. XCOPY will otherwise reset read-only attributes.
/N If at all possible, use only a short filename (8.3) when creating
a destination file. This may be nececcary when copying between disks
that are formatted differently e.g NTFS and VFAT, or when archiving
data to an ISO9660 CDROM.
/O (Windows 2000 only) copy file Ownership and ACL information.
/X Copy file audit settings (implies /O).
XCOPY will accept UNC pathnames
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.
DIRUSE Display disk usage
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
/* Report on one level of subfolders (top-level folders)
/D Display only folders that exceed specified sizes.
/S Include detail of every subfolder in the output
/O Don't check subfolders for quota overflow.
/V Display progress report for every subfolder
/C Use Compressed size instead of apparent size.
/L Output overflows to logfile .\DIRUSE.LOG.
/A generate an alert if quota is exceeded
(requires the Alerter service)
Note: the '-' symbol can be used in place of the '/' symbol.
Example
DIRUSE /M /q:1.5 /* e:\users
DISKCOMP Compare the contents of two floppy disks
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:
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:
DOSKEY Edit command line, recall commands, and create macros
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.
text : The commands you want to recall.
options : for working with macros...
/MACROFILE=filename Specify a file of macros to install
/MACROS Display all Doskey macros
/EXENAME=exename Specify an executable other than cmd.exe
/MACROS:exename Display all Doskey macros for the given executable
/MACROS:ALL Display all Doskey macros for all executables
ALT+F10 Clear macro definitions
options : for working with the Command Buffer...
/HISTORY : Display all commands stored in memory.
/LISTSIZE=size : Limit the number of commands remembered by the buffer.
/REINSTALL : Install a new copy of Doskey (clears the buffer).
In normal use the command line is always in overwrite mode, DOSKEY can be used to
change this to Insert, the insert key will always toggle from one to the other
/INSERT : By default new text you type at the command line
will be inserted in old text
/OVERSTRIKE : By default new text you type at the command line
will overwrite old
In addition to the above, DOSKEY is loaded into memory for every cmd session so
you can use the following Keystrokes at the command line
UP and DOWN ARROWS or F8 will recall commands;
F7 : popup command history (enter to accept, ESC to cancel)
<letter>F8 : command history (commands starting with letter)
F9 : select a command by number
ESC : clear command line
ALT+F7 : clear command history
INSERT : toggle Insert/Overwrite
Pressing F8 repeatedly will cycle through all the matching commands.
The size of the command history can be set from Control Panel, Console or from
the properties of any cmd shortcut. Clear all history with DOSKEY /REINSTALL
Examples:
A macro to open notepad
DOSKEY note=notepad.exe
A macro to open WordPad
DOSKEY wpad="C:\Program Files\Windows NT\Accessories\wordpad.exe"
A macro called `d' to run dir/w
DOSKEY d=dir/w
A macro to disable the FORMAT command
DOSKEY FORMAT=;Ive disabled the Format command
More advanced macro definitions:
$T If you put more than one command in a DOSKEY macro, use $T.
to separate them. Equivalent to & in a batch file.
$1-$9 Parameters, equivalent to %1-%9 in a batch file.
$* This represents ALL the parameters $1-9
A macro to open a file with WordPad:
DOSKEY wpad="C:\Program Files\Windows NT\Accessories\wordpad.exe" $1
Using the above macro:
wpad MyTextfile.txt
Save and restore macro definitions
DOSKEY macros are normally only visible to the current CMD session.
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.
DSADD Add user (computer, group..) to active directory
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"
DSMOD Modify user (computer, group..) in active directory
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").
E
~ ECHO Display message on screen
ECHO
Display messages on screen, turn command-echoing 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 text into a FILE
The general syntax is
Echo This is some Text > FileName.txt
or if you want to avoid extra spaces:
Echo Some more text>FileName.txt
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.
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 Ctrl-G (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
FOR /f "delims=*" %%G in (myfile.dat:stream1) DO echo %%G
FOR /f "delims=*" %%G in (myfile.dat:stream2) DO echo %%G
A data stream file can be successfully copied and renamed despite the fact that most applications and commands will report a zero length file. The file size can be calculated from remaining free space. The file must always reside on an NTFS volume
~ ERASE Delete one or more files
Delete one or more files.
Syntax
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.
/A Select files to delete based on file_attributes
file_attributes:
R Read-only -R NOT Read-only
S System -S NOT System
H Hidden -H NOT Hidden
A Archive -A NOT Archive
Wildcards: These can be combined with part of a filename
* Match any characters
? Match any ONE character
Examples:
To delete HelloWorld.TXT
DEL HelloWorld.TXT
To delete "Hello Big World.TXT"
To delete all files that start with the letter A
To delete all files that end with the letter A
To delete all files with a .DOC extension
To delete all read only files
To delete all files including any that are read only
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:
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 un-deleting it again, however you can turn any file into a zero-byte file to destroy the file allocation chain like this:
TYPE nul > 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.
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
for /f "Tokens=*" %%G in ('dir /B') do rd /s /q "%%G"
popd
~ EXIT Quit the current script/routine and set an errorlevel.
EXIT
Quit the current batch script, quit the current subroutine or quit the command processor (CMD.EXE) optionally setting an errorlevel code.
Syntax
EXIT [/B] [exitCode]
Key
/B When used in a batch script, this option will exit
only the script (or subroutine) but not CMD.EXE
exitCode Sets the %ERRORLEVEL% to a numeric number.
If quitting CMD.EXE, set the process exit code no.
You should never attempt to directly write to the %errorlevel% variable, (i.e. don't try anything like SET errorlevel...) using the EXIT command provides a safe way to alter the value of the built-in errorlevel variable.
Examples
:: Exit if a required file is missing
@echo off
If not exist MyimportantFile.txt Exit /b
Echo The file was found
:: Set the error level to 5
@echo off
call :setError
echo %errorlevel%
goto :eof
:setError
exit /B 5
To make this more flexible you can change the subroutine to set any errorlevel like this:
:setError
exit /B %1
Now you can call the subroutine: call :setError 6 replacing 6 with whatever value you need the errorlevel to be set to.
EXPAND Uncompress files
EXPAND
Uncompress one or more compressed files.
Syntax
EXPAND Source Destination
EXPAND -r Source Destination
EXPAND -r Source
Options
Source : Source filename or a wildcard
Destination : Destination filename or folder
-r : Rename the files
EXTRACT Uncompress CAB files
F
FC Compare two files
FC.exe
Compare the contents of two files or sets of files. Display any lines which do NOT match.
Syntax
FC /B pathname1 pathname2
FC [options] pathname1 pathname2
Key
/B : Perform a binary comparison.
options
/C : Do a case insensitive string comparison
/A : Displays only first and last lines for each set of differences.
/U : Compare files as UNICODE text files.
/L : Compares files as ASCII text. (default)
/N : Display line numbers (ASCII only)
/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.
/nnnn : Specify a number of consecutive lines that must match after a mismatch.
This can be used to prevent the display of the two files from getting
too out of sync
/T : Do not expand tabs to spaces.
/W : Compress white space (tabs and spaces) for comparison.
To compare sets of files, use wildcards in pathname1 and pathname2 parameters.
Powershell also has an Alias FC for the Format-Custom command, therefore to run the 'old' FC under powershell you need to explicitly run C:\windows\system32\fc.exe
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
FIND Search for a text string in a file
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.
/C : Count the number of lines containing the string.
/N : Display Line numbers.
/I : Ignore the case of characters when searching for the string.
"string" : The text string to find (must be in quotes).
[pathname] : A drive, file or files to search.
If a [pathname] is not specified, FIND will prompt for text input or will accept text piped from another command.
(use CTRL-Z to end manual text input)
Examples:
If names.txt contains the following:
Joe Bloggs, 123 Main St , Dunoon
To search for "Jones" in names.txt
FIND "Jones" names.txt
---------- NAMES.TXT
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")
FINDSTR Search for strings in files
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.
options may be any combination of the following switches:
/I Case-insensitive search.
/S Search subfolders.
/P Skip any file that contains non-printable characters
/L Use search string(s) literally.
/R Use search string(s) as regular expressions.(default)
/B Match pattern if at the Beginning of a line.
/E Match pattern if at the END of a line.
/X Print lines that match exactly.
/V Print only lines that do NOT contain a match.
/N Print the line number before each line that matches.
/M Print only the filename if a file contains a match.
/O Print character offset before each matching line.
/a color_attribute Display filenames in colour (2 hex digits)
Options in bold are new in Windows 2000
When the search string contains multiple words (separated with spaces) then FINDSTR will show show lines that contains any one word - (an OR of each word) - this behaviour is reversed if the string argument is prefixed with /C.
Regular Expressions
(Searching for patterns of text)
The FINDSTR syntax notation can use the following metacharacters which have special meaning either as an operator or delimiter.
. Wildcard: any character
* Repeat: zero or more occurances of previous character or class
^ Line position: beginning of line
$ Line position: end of line
[class] Character class: any one character in set
[^class] Inverse class: any one character not in set
[x-y] Range: any characters within the specified range
\x Escape: literal use of metacharacter x
\<xyz Word position: beginning of
xyz\> Word position: end of word
Metacharacters are most powerful when they are used together. For example, the combination of the wildcard character (.) and repeat (*) character is similar in effect to the filename wildcard (*.*)
.* Match any string of characters
The .* expression may be useful within a larger expression, for example f.*ing will match any string beginning with F and ending with ing.
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.
~ FOR /F Loop command: against a set of files
FOR /F
Syntax
FOR /F ["options"] %%parameter IN (filenameset) DO command
FOR /F ["options"] %%parameter IN ("Text string 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 of the file.
(default = 0)
eol=; Character at the start of each line to indicate a comment
The default is a semicolon ; Use "eol=" to process all lines
tokens=n Specifies which numbered items to read from each line
(default = 1)
usebackq Specify `back quotes`:
- Use double quotes to quote long file names in filenameset.
- Use single quotes for 'Text string to process'
(useful if the text string contains double quotes)
Filenameset : A set of one or more files. Wildcards may be used.
If (filenameset) is a period character (.) then FOR will
loop through every file in the folder.
command : The command to carry out, including any
command-line parameters.
%%parameter : A replaceable parameter:
in a batch file use %%G (on the command line %G)
FOR /F processing of each text file consists of reading the file one line of text at a time and then breaking the ine up into individual items of data or 'tokens'. The DO command is then executed with the parameter(s) set to the token(s) found.
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.
Tokens
tokens=2,4,6 will cause the second, fourth and sixth items on each line to be processed
tokens=2-6 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
More than one delimiter may be specified so a string like 'abcd+efg+hijk+lmno;pqr;stu+vwzyz' can be broken up using "delims=;+".
You can use any character as a delimiter, but they are case sensitive.
If you don't specify delims it will default to "delims=<tab><space>"
Notice that some text editors will enter the TAB character as a series of spaces, specifying more than one delimiter has been known to cause problems with some data sets.
usebackq
This option is useful when dealing with a filenameset that is a long filename containing spaces, it allows you to put double quotes around the filename.
The backquote character ` is just below the ESC key on most keyboards.
eol
If some lines in your data file contains comments prefixed with ; (or some other character) at the start of the line they can be ignored. If you want to ensure every line of the data file is processed, even if it starts with a semicolon then use eol= which will turn this feature off.
Examples
Extracting data from this text file:
12-AUG-06,DEPOSIT,450,23,55
14-JAN-07,WITHDRAWAL,285,122
03-FEB-07,DEPOSIT,200
FOR /F "tokens=1,3* delims=," %%G IN (myfile.txt) DO @echo %%G %%H %%I
The command above will split each line into tokens delimited by a comma as shown below. token1 token3 *
= All the rest
%%G %%H %%I
12-AUG-06 DEPOSIT 450 23,55
14-JAN-07 WITHDRAWAL 285 122
03-FEB-07 DEPOSIT 200
%%G is 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 just the date from the following string
FOR /F "tokens=4 delims=," %%G IN ("deposit,$45.50,23.7,12-AUG-07") DO @echo Date paid %%G
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
FOR /F "tokens=1,2* delims=," %%G IN (C:\MyDocu~1\mytex~1.txt) DO ECHO %%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.
~ FOR /F Loop command: against the results of another command
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)
eol=; Character at the start of each line to indicate a comment
The default is a semicolon ; Use "eol=" to process all lines
tokens=n Specifies which numbered items to
read from each line
(default = 1)
usebackq Specify `back quotes`
the command_to_process is placed in `BACK quotes`
instead of 'straight' quotes
command_to_process : The output of the 'command_to_process' is
passed into the FOR parameter.
command : The command to carry out, including any
command-line parameters.
%%parameter : A replaceable parameter:
in a batch file use %%G (on the command line %G)
FOR /F processing of a command consists of reading the output from the command one line at a time and then breaking the line up into individual items of data or 'tokens'. The DO command is then executed with the parameter(s) set to the token(s) found.
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"
usebackq
This option is useful when dealing with a command that already contains one or more straight quotes.
The backquote character ` is just below the ESC key on most keyboards. See the FOR /F page for other effects of usebackq.
Tokens
tokens=2,4,6 will cause the second, fourth and sixth items on each line to be processed
tokens=2-6 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
More than one delimiter may be specified so a string like 'abcd+efg+hijk+lmno;pqr;stu+vwzyz' can be broken up using "delims=;+".
You can use any character as a delimiter, but they are case sensitive.
If you don't specify delims it will default to "delims=<tab><space>"
Notice that some text editors will enter the TAB character as a series of spaces, specifying more than one delimiter has been known to cause problems with some data sets.
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
FOR /F "tokens=*" %%G IN ('dir/b ^"c:\program files\*.txt^"') DO echo %%G
In the example above the long filename has to be surrounded in "quotes"
these quotes have to be escaped using ^
The "tokens=*" has been added to match all parts of any long filenames returned by the DIR command.
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 and the other FOR pages below.
~ FOR Loop command: all options Files, Directory, List
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
FOR /F ["options"] %%parameter IN ("Text string to process") 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 equal 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)
Also if the parameter refers to a file, you can use an enhanced variable reference to quickly extract the filename/path/date/size.
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 non-conflicting letters for use as implicit parameters.
G > H > I > J > K > L > M
Using variables correctly
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.
FORFILES Batch process multiple files
FORFILES.exe (Resource Kit + update)
Batch process multiple files
Syntax NT/2000:
FORFILES [-pPath] [-s] [-dDate] [-mMask] [-cCommand]
Syntax 2003/Vista:
FORFILES [-p Path] [-s] [-d Date] [-m Mask] [-c Command]
key
Path : Path to search (default=current folder)
-s : Recurse into sub-folders
Date : This can be
+DDMMYY to select files newer than a given date
(filedate >=DDMMYY) or
-DDMMYY to select files older than a given date
(filedate <=DDMMYY) or
(Recent versions format the date mask as: +MM/DD/YY
+DD to select files newer than DD days ago or
-DD to select files older than DD days ago
Mask : Search mask (wildcards allowed) default=*.*
Command : Command to execute on each file. default="CMD /C Echo @FILE"
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"
To show the path of every HTML file on the C: drive
FORFILES -pC:\ -s -m*.HTML -c"CMD /C Echo @RELPATH is the location of @FILE"
List every folder on the C: drive
FORFILES -pC:\ -s -m*. -c"CMD /C if @ISDIR==TRUE echo @FILE is a folder"
For every file on the C: drive list the file extension in double quotes
FORFILES -pc:\ -s -m*.* -c"CMD /c echo extension of @FILE is 0x22@EXT0x22"
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"
Find files last modified before 01-Jan-1995
FORFILES -pc:\ -s -m*.* -d-010195 -c"CMD /C Echo @FILE is quite old!"
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.
The Vista/2003 version of ForFiles is not compatible with Windows 2000
FORMAT Format a disk
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.
/V:label The volume label.
/Q Quick format.
/C Compression - files added to the new disk will be compressed.
[size] may be defined either with /F:size or /A:size
/F:size size is the size of the floppy disk (720, 1.2, 1.44, 2.88, or 20.8).
/A:size Allocation unit size.
Default settings (via /F) are strongly recommended for general use.
NTFS supports 512, 1024, 2048, 4096, 8192, 16K, 32K, 64K.
FAT supports 8192, 16K, 32K, 64K, 128K, 256K.
NTFS compression is not supported for allocation units above 4096.
FSUTIL File and Volume utilities
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
FSUTIL hardlink create <new filename> <existing filename>
Eg : fsutil hardlink create c:\foo.txt c:\bar.txt
Create a new file of a specific size
FSUTIL file createnew <filename>
Eg : fsutil file createnew C:\testfile.txt 1000
Set the short name for a file
FSUTIL file setshortname <filename> <shortname>
Eg : fsutil file setshortname C:\testfile.txt testfile
Set the valid data length for a file
FSUTIL file setvaliddata <filename> <datalength>
Eg : fsutil file setvaliddata C:\testfile.txt 4096
Set the zero data for a file
FSUTIL file setzerodata offset=<val> length=<val> <filename>
offset : File offset, the start of the range to set to zeroes
length : Byte length of the zeroed range
Eg : fsutil file setzerodata offset=100 length=150 C:\Temp\sample.txt
List all drives (including mapped and Subst drives)
FSUTIL fsinfo drives
Query drive type for a drive
FSUTIL fsinfo drivetype <volume pathname>
Eg : fsutil fsinfo drivetype C:
ListLocalDrives.cmd - List all drives on the local computer
Query volume information
FSUTIL fsinfo volumeinfo <volume pathname>
Eg : fsutil fsinfo volumeinfo C:\
Query NTFS specific volume information
FSUTIL fsinfo ntfsinfo <volume pathname>
Eg : fsutil fsinfo ntfsinfo C:
Query file system statistics
FSUTIL fsinfo statistics <volume pathname>
Eg : fsutil fsinfo statistics C:
QUOTA Management
FSUTIL quota {query|disable|track|enforce } C:
FSUTIL quota violations
FSUTIL quota modify <volume pathname> <threshold> <limit> <user>
Eg : fsutil quota modify c: 3000 5000 domain\user
Find a file by user name (if Disk Quotas are enabled)
FSUTIL file findbysid <user> <directory>
Eg : fsutil file findbysid scottb C:\users
File system options:
FSUTIL behavior query option
FSUTIL behavior set option
FSUTIL dirty query <volume pathname>
FSUTIL dirty set <volume pathname>
Where option is one of:
disable8dot3
allowextchar
disablelastaccess
quotanotify
mftzone
Eg : FSUTIL behavior query disable8dot3 1
FSUTIL dirty query C:
Query a reparse point
FSUTIL reparsepoint query <filename>
Eg : fsutil reparsepoint query C:\Server
Delete a reparse point
FSUTIL reparsepoint delete <filename>
Eg : fsutil reparsepoint delete C:\Server
Edit an object identifier
FSUTIL objectid {query | set | delete | create}
Set sparse file properties
FSUTIL sparse queryflag <filename>
FSUTIL sparse setflag <filename>
FSUTIL sparse queryrange <filename>
FSUTIL sparse setrange <filename>
Eg : fsutil sparse queryflag "C:\My Test.txt"
Query the allocated ranges for a file
FSUTIL file queryallocranges offset=<val> length=<val> <filename>
offset : File Offset, the start of the range to query
length : Size, in bytes, of the range
Eg : fsutil file queryallocranges offset=1024 length=64 C:\Temp\sample.txt
To run FSUTIL, you must be logged on as an administrator or a member of the Administrators group.
Sparse files provide a method of saving disk space for files that contain meaningful data as well as large sections of data composed of zeros. If an NTFS file is marked as sparse, then disk clusters are allocated only for the data explicitly specified by the application.
e.g. The Indexing Service, stores it's catalogs as sparse files.
With 8.3 filennames disabled you'll notice a performance improvement only with a large number of files (over 300,000) in relatively few folders where a lot of the filenames start with similar names. Not having 8.3 filenames available will prevent the use of old applications such as Word 2.0 and Excel 4.0
FSUTIL behavior query disable8dot3 1
If you have a lot of small files, you may need a larger Master File Table to avoid MFT fragmentation:
FSUTIL behavior set mftzone 2 will reserve 25 % of the volume for the MFT.
1 = 12.5 %(default),
2 = 25%
3 = 37.5%,
4 = 50%
The last access time attribute of NTFS can slow performance, if you disable it, the time set will simply be the Creation Time.
FSUTIL behavior set disablelastaccess 1
FTP File Transfer Protocol
FTP
File Transfer Protocol
Syntax
FTP [-options] [-s:filename] [-w:buffer] [host]
key
-s:filename Run a text file containing FTP commands.
host Host name or IP address of the remote host.
-g Disable filename wildcards.
-n No auto-login.
-i No interactive prompts during ftp.
-v Hide remote server responses.
-w:buffer Set buffer size to buffer
(default=4096)
-d Debug
-a Use any local interface when binding data connection.
Commands to run at the FTP: prompt
append local-file [remote-file]
Append a local file to a file on the remote computer.
ascii Set the file transfer type to ASCII, the default.
In ASCII text mode, character-set and end-of-line
characters are converted as necessary.
bell Toggle a bell to ring after each command.
By default, the bell is off.
binary Set the file transfer type to binary.
Use `Binary' for transferring executable program
files or binary data files e.g. Oracle
bye End the FTP session and exit ftp
cd Change the working directory on the remote host.
close End the FTP session and return to the cmd prompt.
debug Toggle debugging. When debug is on, FTP will display
every command.
delete remote-file
Delete file on remote host.
dir [remote-directory] [local-file]
List a remote directory's files and subdirectories.
(or save the listing to local-file)
disconnect Disconnect from the remote host, retaining the ftp prompt.
get remote-file [local-file]
Copy a remote file to the local PC.
glob Toggle the use of wildcard characters in local pathnames.
By default, globbing is on.
hash Toggle printing a hash (#) for each 2K data block transferred.
By default, hash mark printing is off.
help [command]
Display help for ftp command.
lcd [directory]
Change the working directory on the local PC.
By default, the working directory is the directory in which ftp was started.
literal argument [ ...]
Send arguments, as-is, to the remote FTP host.
ls [remote-directory] [local-file]
List a remote directory's files and folders.
(short format)
mdelete remote-files [ ...]
Delete files on remote host.
mdir remote-files [ ...] local-file
Display a list of a remote directory's files and subdirectories.
(or save the listing to local-file)
Mdir allows you to specify multiple files.
mget remote-files [ ...]
Copy multiple remote files to the local PC.
mkdir directory
Create a directory on the remote host.
mls remote-files [ ...] local-file
List a remote directory's files and folders.
(short format)
mput local-files [ ...]
Copy multiple local files to the remote host.
open computer [port]
Connects to the specified FTP server.
prompt Toggle prompting. Ftp prompts during multiple file transfers to
allow you to selectively retrieve or store files;
mget and mput transfer all files if prompting is turned off.
By default, prompting is on.
put local-file [remote-file]
Copy a local file to the remote host.
pwd Print Working Directory
(current directory on the remote host)
quit End the FTP session with the remote host and exit ftp.
quote argument [ ...]
Send arguments, as-is, to the remote FTP host.
recv remote-file [local-file]
Copy a remote file to the local PC.
remotehelp [command]
Display help for remote commands.
rename filename newfilename
Rename remote files.
rmdir directory
Delete a remote directory.
send local-file [remote-file]
Copy a local file to the remote host.
status Display the current status of FTP connections and toggles.
trace Toggles packet tracing; trace displays the route of each packet
type [type-name]
Set or display the file transfer type:
`binary' or `ASCII' (the default)
If type-name is not specified, the current type is displayed.
ASCII should be used when transferring text files.
In ASCII text mode, character-set and end-of-line
characters are converted as necessary.
Use `Binary' for transferring executable files.
user user-name [password] [account]
Specifes a user to the remote host.
verbose Toggle verbose mode. By default, verbose is on.
! command Run command on the local PC.
? [command] Display help for ftp command.
An example FTP Script to retrieve files in binary and ascii mode
::GetFiles.ftp
[User_id]
[ftp_password]
binary
get /usr/file1.exe
get file2.html
mget *.jpeg
ascii
mget *.txt
quit
To run the above script:
FTP -s:GetFiles.ftp [hostname]
This will connect as the user:User_id with password:ftp_password
An FTP Script to publish files in binary mode
::PutFiles.ftp
[User_id]
[ftp_password]
binary
mput *.html
cd images
mput *.gif
quit
To run the above script:
FTP -s:PutFiles.ftp [hostname]
This will connect as the user:User_id with password:ftp_password
~ FTYPE Display or modify file types used in file extension associations
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
executable_path : The executable program including any command line parameters
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"
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