MS- DOS command


LIST OF MS DOS COMMANDS:

ADDUSERS Add or list users to/from a CSV file

   ADmodcmd Active Directory Bulk Modify

   ARP      Address Resolution Protocol

   ASSOC    Change file extension associations•

   ASSOCIAT One step file association

   ATTRIB   Change file attributes

b

   BCDBOOT  Create or repair a system partition

   BOOTCFG  Edit Windows boot settings

   BROWSTAT Get domain, browser and PDC info

c

   CACLS    Change file permissions

   CALL     Call one batch program from another•

   CD       Change Directory - move to a specific Folder•

   CHANGE   Change Terminal Server Session properties

   CHKDSK   Check Disk - check and repair disk problems

   CHKNTFS  Check the NTFS file system

   CHOICE   Accept keyboard input to a batch file

   CIPHER   Encrypt or Decrypt files/folders

   CleanMgr Automated cleanup of Temp files, recycle bin

   CLEARMEM Clear memory leaks

   CLIP     Copy STDIN to the Windows clipboard.

   CLS      Clear the screen•

   CLUSTER  Windows Clustering

   CMD      Start a new CMD shell

   CMDKEY   Manage stored usernames/passwords

   COLOR    Change colors of the CMD window•

   COMP     Compare the contents of two files or sets of files

   COMPACT  Compress files or folders on an NTFS partition

   COMPRESS Compress individual files on an NTFS partition

   CON2PRT  Connect or disconnect a Printer

   CONVERT  Convert a FAT drive to NTFS.

   COPY     Copy one or more files to another location•

   CSCcmd   Client-side caching (Offline Files)

   CSVDE    Import or Export Active Directory data

d

   DATE     Display or set the date•

   DEFRAG   Defragment hard drive

   DEL      Delete one or more files•

   DELPROF  Delete NT user profiles

   DELTREE  Delete a folder and all subfolders

   DevCon   Device Manager Command Line Utility

   DIR      Display a list of files and folders•

   DIRUSE   Display disk usage

   DISKCOMP Compare the contents of two floppy disks

   DISKCOPY Copy the contents of one floppy disk to another

   DISKPART Disk Administration

   DNSSTAT  DNS Statistics

   DOSKEY   Edit command line, recall commands, and create macros

   DSACLs   Active Directory ACLs

   DSAdd    Add items to active directory (user group computer)

   DSGet    View items in active directory (user group computer)

   DSQuery  Search for items in active directory (user group computer)

   DSMod    Modify items in active directory (user group computer)

   DSMove   Move an Active directory Object

   DSRM     Remove items from Active Directory

e

   ECHO     Display message on screen•

   ENDLOCAL End localisation of environment changes in a batch file•

   ERASE    Delete one or more files•

   EVENTCREATE Add a message to the Windows event log

   EXIT     Quit the current script/routine and set an errorlevel•

   EXPAND   Uncompress files

   EXTRACT  Uncompress CAB files

f

   FC       Compare two files

   FIND     Search for a text string in a file

   FINDSTR  Search for strings in files

   FOR /F   Loop command: against a set of files•

   FOR /F   Loop command: against the results of another command•

   FOR      Loop command: all options Files, Directory, List•

   FORFILES Batch process multiple files

   FORMAT   Format a disk

   FREEDISK Check free disk space (in bytes)

   FSUTIL   File and Volume utilities

   FTP      File Transfer Protocol

   FTYPE    Display or modify file types used in file extension associations•

g

   GLOBAL   Display membership of global groups

   GOTO     Direct a batch program to jump to a labelled line•

   GPUPDATE Update Group Policy settings

h

   HELP     Online Help

i

   iCACLS   Change file and folder permissions

   IF       Conditionally perform a command•

   IFMEMBER Is the current user in an NT Workgroup

   IPCONFIG Configure IP

k

   KILL     Remove a program from memory

l

   LABEL    Edit a disk label

   LOCAL    Display membership of local groups

   LOGEVENT Write text to the NT event viewer

   LOGMAN   Manage Performance Monitor

   LOGOFF   Log a user off

   LOGTIME  Log the date and time in a file

m

   MAPISEND Send email from the command line

   MBSAcli  Baseline Security Analyzer.

   MEM      Display memory usage

   MD       Create new folders•

   MKLINK   Create a symbolic link (linkd)

   MODE     Configure a system device

   MORE     Display output, one screen at a time

   MOUNTVOL Manage a volume mount point

   MOVE     Move files from one folder to another•

   MOVEUSER Move a user from one domain to another

   MSG      Send a message

   MSIEXEC  Microsoft Windows Installer

   MSINFO32 System Information

   MSTSC    Terminal Server Connection (Remote Desktop Protocol)

   MV       Copy in-use files

n

   NET      Manage network resources

   NETDOM   Domain Manager

   NETSH    Configure Network Interfaces, Windows Firewall & Remote access

   NETSVC   Command-line Service Controller

   NBTSTAT  Display networking statistics (NetBIOS over TCP/IP)

   NETSTAT  Display networking statistics (TCP/IP)

   NOW      Display the current Date and Time

   NSLOOKUP Name server lookup

   NTBACKUP Backup folders to tape

   NTRIGHTS Edit user account rights

o

   OPENFILES Query or display open files

p

   PATH     Display or set a search path for executable files•

   PATHPING Trace route plus network latency and packet loss

   PAUSE    Suspend processing of a batch file and display a message•

   PERMS    Show permissions for a user

   PERFMON  Performance Monitor

   PING     Test a network connection

   POPD     Restore the previous value of the current directory saved by PUSHD•

   PORTQRY  Display the status of ports and services

   POWERCFG Configure power settings

   PRINT    Print a text file

   PRINTBRM Print queue Backup/Recovery

   PRNCNFG  Display, configure or rename a printer

   PRNMNGR  Add, delete, list printers set the default printer

   PROMPT   Change the command prompt•

   PsExec     Execute process remotely

   PsFile     Show files opened remotely

   PsGetSid   Display the SID of a computer or a user

   PsInfo     List information about a system

   PsKill     Kill processes by name or process ID

   PsList     List detailed information about processes

   PsLoggedOn Who's logged on (locally or via resource sharing)

   PsLogList  Event log records

   PsPasswd   Change account password

   PsService  View and control services

   PsShutdown Shutdown or reboot a computer

   PsSuspend  Suspend processes

   PUSHD    Save and then change the current directory•

q

   QGREP    Search file(s) for lines that match a given pattern.

r

   RASDIAL  Manage RAS connections

   RASPHONE Manage RAS connections

   RECOVER  Recover a damaged file from a defective disk.

   REG      Registry: Read, Set, Export, Delete keys and values

   REGEDIT  Import or export registry settings

   REGSVR32 Register or unregister a DLL

   REGINI   Change Registry Permissions

   REM      Record comments (remarks) in a batch file•

   REN      Rename a file or files•

   REPLACE  Replace or update one file with another

   RD       Delete folder(s)•

   RMTSHARE Share a folder or a printer

   ROBOCOPY Robust File and Folder Copy

   ROUTE    Manipulate network routing tables

   RUN      Start | RUN commands

   RUNAS    Execute a program under a different user account

   RUNDLL32 Run a DLL command (add/remove print connections)

s

   SC       Service Control

   SCHTASKS Schedule a command to run at a specific time

   SCLIST   Display NT Services

   SET      Display, set, or remove environment variables•

   SETLOCAL Control the visibility of environment variables•

   SETX     Set environment variables permanently

   SFC      System File Checker

   SHARE    List or edit a file share or print share

   SHIFT    Shift the position of replaceable parameters in a batch file•

   SHORTCUT Create a windows shortcut (.LNK file)

   SHOWGRPS List the NT Workgroups a user has joined

   SHOWMBRS List the Users who are members of a Workgroup

   SHUTDOWN Shutdown the computer

   SLEEP    Wait for x seconds

   SLMGR    Software Licensing Management (Vista/2008)

   SOON     Schedule a command to run in the near future

   SORT     Sort input

   START    Start a program or command in a separate window•

   SU       Switch User

   SUBINACL Edit file and folder Permissions, Ownership and Domain

   SUBST    Associate a path with a drive letter

   SYSTEMINFO List system configuration

t

   TASKLIST List running applications and services

   TASKKILL Remove a running process from memory

   TIME     Display or set the system time•

   TIMEOUT  Delay processing of a batch file

   TITLE    Set the window title for a CMD.EXE session•

   TLIST    Task list with full path

   TOUCH    Change file timestamps   

   TRACERT  Trace route to a remote host

   TREE     Graphical display of folder structure

   TSSHUTDN Remotely shut down or reboot a terminal server

   TYPE     Display the contents of a text file•

   TypePerf Write performance data to a log file

u

   USRSTAT  List domain usernames and last login

v

   VER      Display version information•

   VERIFY   Verify that files have been saved•

   VOL      Display a disk label•

w

   WAITFOR  Wait for or send a signal

   WHERE    Locate and display files in a directory tree

   WHOAMI   Output the current UserName and domain

   WINDIFF  Compare the contents of two files or sets of files

   WINMSDP  Windows system report

   WINRM    Windows Remote Management

   WINRS    Windows Remote Shell

   WMIC     WMI Commands

   WUAUCLT  Windows Update

x

   XCACLS   Change file and folder permissions

   XCOPY    Copy files and folders

   ::       Comment / Remark•

Commands marked • are Internal commands only available within the CMD shell.
All other commands (not marked with •) are external commands which may be used under the CMD shell, PowerShell, or directly from START-RUN.

MS DOS COMMAND IN NETWORKING

Help with ping, winipcfg, and other network commands.
Issue: Help with ping, winipcfg, and other network commands.

Cause: It may be necessary to utilize utilities such as ping, winipcfg, tracert, etc to help identify and fix network related issues.

Solution: Below is a listing of the various network related commands used in MS-DOS, Windows, Linux, Unix, and other operating systems. Each command includes additional information to what the command does, the command's syntax, and miscellaneous information.

Note: If you are not the root or admin of a computer, it is possible for these commands to be disabled or revoked.

Arp
Finger
Hostname
Ipconfig
Pathping
Ping
Nbtstat
Net
Netstat
Nslookup
Route
Tracert / Traceroute
Whois
Winipcfg


ARP

Display or manipulate the ARP information on a network device or computer.

  • Additional information about the MS-DOS arp command can be found here.
FINGER

The finger command available in Unix / Linux variants allows a user to find sometimes personal information about a user. This information can include the last time the user logged in, when they read their e-mail, etc... If the user creates a .PLAN or other related file the user can also display additional information.

  • Unix / Linux and variant finger command information can be found here.
HOSTNAME

The hostname command displays the host name of the Windows XP computer currently logged into.

  • Additional information about the MS-DOS hostname command can be found here.
IPCONFIG

Ipconfig is a MS-DOS utility which can be used from MS-DOS and a MS-DOS shell to display the network settings currently assigned and given by a network. This command can be utilized to verify a network connection as well as to verify your network settings.

Windows 2000 users should use this command to determine network information.

  • Additional information about ipconfig can be found here.
PATHPING

Pathping is a MS-DOS utility available for Microsoft Windows 2000 and Windows XP users. This utility enables a user to find network latency and network loss.

  •  Additional information about the pathping command can be found here.
PING

Ping is one of the most commonly used and known commands. Ping allows a user to ping another network IP address. This can help determine if the network is able to communicate with the network.

  • MS-DOS / Windows ping command and information can be found here.
  • Unix / Linux and variant ping command information can be found here.
NBTSTAT

The nbtstat MS-DOS utility that displays protocol statistics and current TCP/IP connections using NBT.

  • MS-DOS / Windows nbtstat command and information can be found here.
NET

The net command is available in MS-DOS / Windows and is used to set, view and determine network settings.

  • MS-DOS / Windows net command and information can be found here.
NETSTAT

The netstat command is used to display the TCP/IP network protocol statistics and information.

  • MS-DOS / Windows netstat command and information and be found here.
  • Unix / Linux netstat command and information and be found here.
NSLOOKUP

The nslookup MS-DOS utility that enables a user to do a reverse lookup on an IP address of a domain or host on a network.

  • MS-DOS / Windows nslookup command and information can be found here.
  • Unix / Linux nslookup command and information and be found here. Linux users may also be interested in the host command that performs a similar task.
ROUTE

The route MS-DOS utility enables computers to view and modify the computer's route table.

  • MS-DOS route command information can be found here.
TRACERT / TRACEROUTE

The tracert command in MS-DOS / Windows or the traceroute command in Unix / Linux and variants is another commonly used network command to help determine network related issues or slowdowns. Using this command you can view a listing of how a network packet travels through the network and where it may fail or slow down. Using this information you can determine the computer, router, switch or other network device possibly causing your network issues.

  • MS-DOS / Windows tracert command and information can be found here.
  • Unix / Linux and variant traceroute command information can be found here.
WHOIS

The whois command available in Unix / Linux variants helps allow a user to identify a domain name. This command provides information about a domain name much like the WHOIS on network solutions. In some cases the domain information will be provided from Network Solutions.

  • Unix / Linux and variant whois command information can be found here.
WINIPCFG

The winipcfg command available in Windows allows a user to display network and network adapter information. Here, a user can find such information as an IP address, Subnet Mask, Gateway, etc...

  • Windows winipcfg command and information can be found here.
  • NOTE: Windows 2000, Windows XP and above users do not have winipcfg. Instead, use ipconfig.

To Get More In to details sepeartely with all the command dos...Please look below


ALSO YOU CAN SEARCH SPECIFIC COMMANDS BY USING A SIMPLE SEARCHING TECHNIQUE AND WHICH WILL ALSO HELP YOU TO FIND IT VERY EASILY AND WILL SAVE LOTS OF TIME:::




FOR THAT :
STEP1: CLICK "CTRL+F"
STEP2: A SEARCH BOX APPEARS JUST TYPE THE COMMAND AND IT WILL TAKE YOU THAT PARAGRAPH INSTANTLY
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

Related:

Q199878 - further examples of ADDUSERS
DSADD - Add user (computer, group..) in active directory
CSVDE - Import and export from Active Directory.
Equivalent bash command (Linux): useradd - Create new user accounts

ADmodcmd.exe Active Directory Bulk Modify Tool (Command Line Version) There is also a GUI for this tool called admodify.exe

Syntax

      admodcmd [-dn BaseDN] [-p pagesize] [-s] [-server servername]

            [-f LDAPFilter] [modification]



Key

   -dn BaseDN      Base DN to begin the LDAP query.



   modification    Modification to perform:

                   Terminal Server Attributes | Exchange Related Attributes

                   Mailbox Rights | User Account Settings | Custom Attributes                 



   -p pagesize     LDAP Page size to use for query.



   -s              Perform a subtree search

                   (Default = one level search)



   -server servername

                   The server to make the changes to.

                   by default, changes are made locally if on a DC.

                   If on a member, DNS is used to find a DC.



   -f LDAPFilter   A Valid LDAP filter to use when enumerating objects

                   The default filter is (object).  

Changes made with ADModcmd can be undone, as long as the xml log file that logged the changes still exists. These log files are typically located in the same folder as the admodify executable.

Syntax:

      admodcmd [-dn BaseDN] [-p pagesize] [-s] [-server servername]

         -undo logfilename -server servername]



Key:

   logfilename     The log file that contains the changes to be undone.

   servername      The DC to write the changes to.

                   by default, changes are made locally if on a DC.

                   If on a member, DNS is used to find a DC.

For information on users that were skipped during an undo process, refer to the undo.log file.

“A free people claim their rights as derived from the laws of nature, and not as the gift of their magistrate” - Thomas Jefferson

Related:

DSQuery - Search for items in active directory (user group computer)
DSMod - Modify items in active directory (user group computer)

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:

C:\> arp -a

Display the ARP cache table for the interface on IP address 10.1.4.99:

C:\> 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:

C:\> arp -s 10.1.4.77 00-AA-21-4A-2F-9A

“One resolution I have made, and try always to keep, is this: To rise above little things” - John Burroughs

Related:

ROUTE - Manipulate network routing tables
Q199773 - Behaviour of Gratuitous ARP
Q140859 - Win NT TCP/IP Routing Basics

ASSOC

Display or change the association between a file extension and a fileTypeSyntax

   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"

"Of all forms of caution, caution in love is perhaps the most fatal to true happiness" - Bertrand Russell 

Related:

FTYPE - Edit file types (used in file extension associations)
Batch file to list the application associated with a file extension
ASSOCIAT - One step file association (Resource Kit)
Q162059 - Associate Internet Explorer with MS Office files
JSIFAQ - List File Types with executable path

ASSOCIATE.exe (Resource Kit) One step file association.

This utility does the job of both ASSOC and FTYPE, in one step. ASSOCIATE assigns an extension directly with an executable application. This is done by automatically adding a new FileType to the system registry.

Syntax

      ASSOCIATE .ext filename [/q /d /f]



Key

   .ext     : Extension to be associated.

   filename : Executable program to associate .ext with.

   /q       : Quiet - Suppress interactive prompts.

   /f       : Force - Force overwrite or delete without questions.

   /d       : Delete - Delete the association.

A file extension is the last few characters in a FileName after the period.
So a file called JANUARY.HTML has the file extension .HTML

The File extension is used by Windows NT to determine the type of information stored in the file and therefore which application(s) will be able to display the information in the file. File extensions are not case sensitive and are not limited to 3 characters.

Example: adding a File Association

To add the File Type "SQLfile"=Notepad.exe and also set the File Association of .SQL="SQLfile" run this command:

ASSOCIATE .SQL Notepad.exe

Example: Removing a File Association

ASSOCIATE .SQL /d

Note that /d will delete the File Association but will NOT delete the File Type.

File types created by Associate.exe are always given a name in the form xxxfile, where xxx is the file extension.

"There are three roads to ruin; women, gambling and technicians. The most pleasant is with women, the quickest is with gambling, but the surest is with technicians" - Georges Pompidou 

Related:

ASSOC Change file extension associations
FTYPE Display or modify file types used in file extension associations

\

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)
        N  Normal (0: cannot be used for file selection)
        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.

Constants - the following attribute values are returned by the GetFileAttributes function:

FILE_ATTRIBUTE_READONLY = 1
FILE_ATTRIBUTE_HIDDEN = 2
FILE_ATTRIBUTE_SYSTEM = 4
FILE_ATTRIBUTE_DIRECTORY = 16
FILE_ATTRIBUTE_ARCHIVE = 32
FILE_ATTRIBUTE_ENCRYPTED = 64
FILE_ATTRIBUTE_NORMAL = 128
FILE_ATTRIBUTE_TEMPORARY = 256
FILE_ATTRIBUTE_SPARSE_FILE = 512
FILE_ATTRIBUTE_REPARSE_POINT = 1024
FILE_ATTRIBUTE_COMPRESSED = 2048
FILE_ATTRIBUTE_OFFLINE = 4096
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 8192

"The moral sense of conscience is by far the most important.. it is the most noble of all the attributes of man" - Charles Darwin

Related:

CACLS - Change file permissions
Show superhidden file extensions
Q326549 - Read-only & System attributes for folders
Equivalent bash command (Linux): chmod - Change access permissions

BCDBOOT.exe (Windows 7 /2008)

Set up a system partition, repair the boot environment located on the system partition.

Syntax

      BCDBOOT source [/l locale] [/s volume-letter]

         [/v] [/m [{OS Loader GUID}]]

Options

   source  The location of the Windows directory to use as the source for

           copying boot-environment files.

   /l      The locale. default = US English.

   /s      The volume letter of the system partition.

           The default is the system partition identified by the firmware.

   /v      Enable verbose mode

   /m      By default, merge only global objects.

           If an OS Loader GUID is specified, merge the given loader object within

           the system template to produce a bootable entry.

BCDboot may also be run from Windows PE (Preinstallation Environment)

Examples

Initialize the system partition using files from the operating system image installed on the C: volume:

C:\> bcdboot C:\Windows

Set the default BCD locale to Japanese, and copy BCD (Boot Configuration Data) files to drive S:

C:\> bcdboot C:\Windows /l ja-jp /s S:

Merge the OS loader in the current BCD store identified with the given GUID in the new BCD store:

C:\> bcdboot c:\windows /m {d58d10c6-df53-11dc-878f-00064f4f4e08}

“When all the world is young, lad, / And all the trees are green / And every goose a swan, lad / And every lass a queen / Then hey for boot and horse, lad, / And round the world away / Young blood must have its course, lad, / And every dog his day” - Charles Kingsley

Related:

FSUTIL - File and Volume utilities

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

 DEL C:\Boot.ini

 Bootcfg /Rebuild

 Fixboot

The moral sense of conscience is by far the most important.. it is the most noble of all the attributes of man" - Charles Darwin

Related Commands:

Fixboot - Write a new partition boot sector
Q291980 - The XP Bootcfg command
Q317521 - The 2003 Bootcfg command
Recovery console

BROWSTAT.exe (Resource Kit)

Get domain, browser and PDC info.

Syntax

      BROWSTAT option

Options:

 BROWSTAT Dumpnet

 BROWSTAT dn                  : Display the transports bound to browser

 BROWSTAT GetPdc Transport Domain

 BROWSTAT gp Transport Domain : List the PDC name (via NetBIOS)

 BROWSTAT GetMaster Transport Domain

 BROWSTAT gm Transport Domain : List the remote Master Browser name(via NetBIOS)

 BROWSTAT Getblist Transport       

 BROWSTAT gb Transport        : List the backup DNS Servers.

 BROWSTAT ListWfw

 BROWSTAT wfw                 : WindowsForWorkgroups servers running browser.

 BROWSTAT Stats \\ServerName   

 BROWSTAT sts \\ServerName    : List all browser statistics

 BROWSTAT Status              : Display Transport,Primary DNS

 BROWSTAT sta                   and Backup DNS servers.

 BROWSTAT Status -v domain    : Verbose Status Display

 BROWSTAT sta -v domain         include Server OS and active browsers.

 BROWSTAT Tickle

 BROWSTAT Tic                 : Force remote master to stop.

 BROWSTAT Elect

 BROWSTAT el                  : Force election on remote domain

 BROWSTAT View Transport

 BROWSTAT vw Transport

 BROWSTAT vw Transport ‹domain›

 BROWSTAT vw Transport \\Server

 BROWSTAT vw Transport \\‹Server› /DOMAIN ‹DomainToQuery

The VIEW options can enumerate server services running across a server or domain. Other Browstat features will only work only within a single network subnet. To span subnets/routers across a domain, run browstat via psexec.

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  = Time Source

MBC = Member Server

PQ  = Print Queue Server

DL  = Dial-in Server

AFP = AFP Server

OSF = OSF Server

VMS = VMS Server

PBR = Potential Browser

BBR = Backup Browser,

MBR = Master Browser

DMB = DomainMaster Browser

DFS = Distributed File System

Examples

Display transports:

C:\>browstat dn

List of transports currently bound to the browser

1 \Device\NetBT_Tcpip_{B1AFFCA2-6410-4644-9FE7-BA6C274FD4F3}

List the backup DNS servers for transport #1:

C:\>browstat gb 1

Browser: \\PC00096
Browser: \\PC00082

List Print queues for transport #1:

C:\> BROWSTAT vw 1 |find "PQ"

“If your experiment needs statistics, you ought to have done a better experiment” - Ernest Rutherford

Related:

Q188305 - Troubleshooting the Browser Service
DNSSTAT - DNS Statistics
NETSTAT - Display networking statistics (TCP/IP)
SETPRFDC - Set preferred Domain Controller

CACLS.exe Display or modify Access Control Lists (ACLs) for files and folders.

Access Control Lists apply only to files stored on an NTFS formatted drive, each ACL determines which users (or groups of users) can read or edit the file. When a new file is created it normally inherits ACL's from the folder where it was created.

Syntax

      CACLS pathname [options]

       

Options:



   /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)


You can specify more than one user:permission in a single command. Wildcards can be used to specify multiple files.

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)

Setting Deny permission (/D) will deny access to a user even if they also belong to a group that grants access.

Limitations

Cacls cannot display or modify the ACL state of files locked in exclusive use.

Cacls cannot set the following permissions: change permissions, take ownership, execute, delete use XCACLS to set any of these.

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 filename /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)

To actually change the inheritance of a folder/directory use iCACLS /grant or iCACLs /deny

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

"Whether a pretty woman grants or withholds her favours, she always likes to be asked for them" - Ovid (Ars Amatoria) 

Related:

ATTRIB - Display or change file attributes
iCACLS - Change file and folder permissions (ACLs)
XCACLS - Change file and folder permissions (ACLs)
Powershell: Set-Acl - Set permissions
AccessEnum - GUI to browse a tree view of user privs
DIR /Q - Display the owner for a list of files (try it for Program files)
PERMS - Show permissions for a user
FIXACLS - Restore default privs (Resource Kit supplement 2)
FSUTIL - File System Options
NTRIGHTS - Edit user account rights
SHOWACL - Show file Access Control Lists (Windows 2000)
TAKEOWN - Take ownership of shares
Q237701 - Cacls cannot apply security to root
Q271876 - Complex ACLs impair directory service performance
Q834721 - Permissions on Folder are incorrectly ordered
Q135268 - How to use CACLS.EXE in a Batch File
Q245031 - Error when using the | pipe symbol
NT Permissions explained
ACL utils: SetACL or FileACL (free)
Equivalent bash command (Linux):chmod - Change access permissions

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. This is the basis of a batch file function.

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

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.

"My mother never saw the irony in calling me a son-of-a-bitch." - Jack Nicholson 

Related
:

Syntax: Functions - How to package blocks of code
CMD - can be used to call a subsequent batch and ALWAYS return even if errors occur.
GOTO - jump to a label or GOTO :eof
START - Start a separate window to run a specified program or command
Equivalent bash command (Linux): . (source) - Run a command script in the current shell, builtin - Run a shell builtin

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.

   C:\Work> CD ..

  

   To change to the grant-parent directory.

   C:\Work\backup\January> CD ..\..

  

   To change to the ROOT directory.

   C:\Work\backup\January> CD \

  

   To display the current directory in the specified drive.

   C:\>  CD D:

  

   To display the current drive and directory.

   C:\Work> CD



   To display the current drive and directory.

   C:\Work> ECHO "%CD%"



   In a batch file to display the location of the batch script file (%0) 

   C:\> ECHO "%~dp0"



   Moving down the folder tree with a full path reference to the ROOT folder...

   C:\windows> CD \windows\java

   C:\windows\java>

  

   Moving down the folder tree with a reference RELATIVE to the current folder...

   C:\windows> CD java

   C:\windows\java>

  

   Moving up and down the folder tree in one command...

   C:\windows\java> CD ..\system32

   C:\windows\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:\

C:> CD pro*
will move to
C:\Program Files

CHDIR is a synonym for CD

Tab Completion

This allows changing current folder by entering part of the path and pressing TAB

   C:> CD Prog [PRESS TAB]

   Will go to C:\Program Files\

Tab Completion is disabled by default, it has been known to create difficulty when using a batch script to process text files that contain TAB characters.

Tab Completion is turned on by setting the registry value shown below

REGEDIT4
[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"CompletionChar"=dword:00000009

Changing the Current drive

simply enter the drive letter followed by a colon
C:> E:
E:>

To change drive and directory at the same time, use CD with the /D switch
C:> cd /D E:\utils
E:\utils\>

"Change is the law of life. And those who look only to the past or the present are certain to miss the future" - John F. Kennedy

Related:

You can also change directory using the pushd command
Q156276 - Cmd does not support UNC names as the current directory
JSIFaq Tip 4757 - cd Folder navigation
Powershell: Set-Location - Set the current working location
Equivalent bash command (Linux): cd - Change Directory

CHANGE Change Terminal Server Session properties, use when installing software on a terminal server.

Syntax

      CHANGE USER /options

      CHANGE LOGON /options

      CHANGE PORT /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



  CHANGE PORT portx=porty      Map port x to port y.

  CHANGE PORT /D portx         Delete mapping for port x.

  CHANGE PORT /QUERY           Display current mapping ports.


How .ini files work:

Installing an application will create a .ini file in the TS system directory.

The first time a user runs the application, the application looks in the home directory for its .ini file. If none is found then Terminal Server will copy the .ini file from the system directory to the users home directory.

Each user will have a unique copy of the application's .ini file in their home directory.

To learn more about what happens when the system is put into install mode run CHANGE USER /?

The CHANGE command replaces CHGLOGON, CHGUSER, and CHGPORT from Citrix Winframe.

"There are two ways to slide easily through life; to believe everything or to doubt everything. Both ways save us from thinking" - Alfred Korzybski

Related:


Other Terminal Server commands
INSTSRV - Install an NT Service
LOGOFF - Log a user off
MSIEXEC - Microsoft Windows Installer
Q243202 - TS Session Management Tools
Equivalent bash command (Linux): who - Print all usernames currently logged in

chkdsk.exe

Check Disk - check and repair disk problems

Syntax

      CHKDSK [drive:][[path]filename] [/F] [/V] [/R] [/L[:size]]

Key

   [drive:]   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 was improved by 30% under Windows 2003 and around 50% in 2008 R2.

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.

Chkdsk is also available from the Recovery Console (with different parameters.)

Disk Errors
"The file system structure on the disk is corrupt and unusable"

If you have disk corruption, run the drive manufacturers diagnostics:
Toshiba | Hitachi | ibm | Seagate/Maxtor/Freeagent | Western digital

"I either want less corruption, or more chance to participate in it" - Ashleigh Brilliant 

Related:

CHKNTFS - Schedule CHKDSK to run at boot time.
FSUTIL dirty query C: - Is the drive dirty
CleanMgr - Automated cleanup of Temp files, recycle bin etc
VrfyDsk - Check a volume for errors online (2003 server)
Q837326 - How to use the Vrfydsk.exe tool
Q187941 - New /C and /I Switches
Q283340 - Windows XP does not detect corruption
Q303079 - Locate and correct NTFS problems.
Q310747 - System File Checker (Sfc.exe)
Q327009 - Chkdsk Finds Incorrect Security IDs
Q329394 - Long Delays Occur When You Run Chkdsk.exe
Ultimate Boot CD - Recovery tool
HDTune - Performance & SMART Info. (Self-Monitoring Analysis and Reporting Technology)
Equivalent bash command (Linux): fsck - filesystem consistency check and interactive repair

CHKNTFS.exe Check the NTFS file system with CHKDSK

Syntax

      CHKNTFS drive: [...]

      CHKNTFS /C drive: [...]

      CHKNTFS /X drive: [...]

      CHKNTFS /t[:Time]

      CHKNTFS /D



Key

   drive : Specifies a drive letter.



   /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

"I don't make no dirty movements" - Elvis 

Related:

CHKDSK - Check Disk - check and repair disk problems
FSUTIL - File and Volume utilities
BOOTCFG - Edit the Boot.ini file
Q160963 - ChkNTFS What you can use it for

CHOICE.exe Accept user input to a batch file. Choice allows single key-presses to be captured from the keyboard.

    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 the end of the prompt string.



   /CS             : Make the choiceKeys Case Sensitive.



   /T Timeout      : Timeout in Timeout seconds

                     If Timeout is 0 there will be no pause and the

                     default will be selected.



   /d choice       : Default choice made on Timeout.



   /m text         : Message string to describe the choices available.

ERRORLEVEL will return the numerical offset of choiceKeys.
Choice.exe is a standard command in Windows 2003, Vista and Windows 7 (for XP you can use the early resource kit versions).

Bugs
Early versions of Choice.com (not Choice.exe) burn a lot of CPU's when in a wait state, plus there are some issues where multiple concurrent invocations will clobber each other.

Examples:

CHOICE /C CH /M Select [C] CD or [H] Hard drive
IF errorlevel 2 goto sub_hard
IF errorlevel 1 goto sub_cd

The order of the IF statements above matters, 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 you limit your choices only to what seems possible or reasonable, you disconnect yourself from what you truly want, and all that is left is compromise” - Robert Fritz

Related:

IF - Conditionally perform a command
SET /P - Prompt for user input (accepts a whole string instead of one keypress)
PowerShell: Read-Host - Read a line of input from the console.
Equivalent bash command (Linux): case / select - Accept keyboard input

CIPHER Encrypt or Decrypt files and folders.
Without parameters cipher will display the encryption state of the current folder and files.
NTFS volumes only.

Syntax:

 

Encrypt/Decrypt:

    CIPHER [{/e | /d}] [/s:Folder] [options] [/u[/n]] [{PathName [...]]

 

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

"He that would make his own liberty secure must guard even his enemy from oppression; for if he violates this duty he establishes a precedent that will reach to himself" - Thomas Paine 

Related:

FSUTIL - File and Volume utilities
CMDKEY - Manage stored usernames/passwords
Powershell: ConvertTo-SecureString - Convert to a secure string

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.

"Then will I sprinkle clean water upon you, and ye shall be clean: from all your filthiness, and from all your idols, will I cleanse you." - Ezekiel 36:25

Related commands:

DELPROF - Delete NT user profiles and/or User Profile cache
DEFRAG - Defragment hard drive (XP)
Q253597 - Automating Disk Cleanup in Windows
Q315246 - Automating Disk Cleanup in Windows XP
Q812248 - Disk Cleanup stops responding while compressing old files

Equivalent bash command (Linux):

watch - Execute/display a program periodically

CLIP.exe (Resource Kit / Windows 7)

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

"The stupid neither forgive nor forget, the naive forgive and forget, the wise forgive but do not forget" - Thomas Szasz (The second sin)

Related:

cmdtools.com - clip.zip - copy clipboard to a file
Script-It - Control GUI applications
SET - Display, set, or remove Windows NT environment variables
Powershell: Out-Clipboard (PowerShell Community Extension)
Equivalent bash command (Linux): xsel - get and set the contents of an X-window selection

CMD.exe Start a new CMD shell.

Syntax

      CMD [charset] [options] [My_Command]



Options  

   /C     Carries out My_Command and then terminates

   /K     Carries out My_Command but remains



   My_Command : The 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.



   /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 key-strokes will 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 or 64 bit command line (cmd.exe)

The old 16 bit command processor command.com is supplied to provide backward compatibility for 16 bit DOS applications. Command.com has very limited functionality compared to cmd.exe e.g. it will fail to set an %errorlevel% after many commands.

If you name your batch scripts with the extension .CMD rather than .BAT then they will not run under command.com even if copied to a Windows 95 machine.

The %COMSPEC% environment variable will show if you are running CMD.EXE or command.com

On 64 bit versions of windows the 32 bit CMD.exe can be found at %windir%\SysWoW64\cmd.exe To reduce compatibility issues, the WOW64 subsystem isolates 32-bit binaries from 64-bit binaries by redirecting registry calls and some file system calls.

Opening CMD from Windows Explorer

You can open a new CMD prompt by choosing START, RUN, cmd, OK

Registry Keys for CMD:

;Allow UNC paths at command prompt

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]

"DisableUNCCheck"=dword:00000001



; Run a command when CMD.exe starts

[HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor]

"AutoRun"=-



; Activate Automatic Completion

[HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor]

"CompletionChar"=0x9



; For Windows 7: Add an elevated 'Open CMD prompt here (Admin)' option to the

; context menu for file system folders:

[HKEY_CLASSES_ROOT\Directory\shell\runas]
@="Open CMD prompt here (Admin)"

[HKEY_CLASSES_ROOT\Directory\shell\runas\command]

@="cmd.exe /k pushd %L"



; For Windows 7: Add an elevated 'Open CMD prompt here (Admin)' option to the

; My Computer context menu:

[HKEY_CLASSES_ROOT\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\shell\runas]

@="Open CMD prompt here (Admin)"

[HKEY_CLASSES_ROOT\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\shell\runas\command]

@="cmd.exe"

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


To simplify the use of cut and paste at the Command Prompt, enable QuickEdit mode as follows:

Activate the control menu at the top left of the current cmd window, go to Properties, Options tab and then tick against QuickEdit Mode.

Now you can select text with the mouse and hit Enter (or right click) to copy it to the clipboard. Paste anywhere using Control+V (or Right Click) or via the menu.

ESC will cancel any selection and return to editing mode.
When copying between windows, you may need one click to select the window and a second click to paste.

Run multiple instances of CMD.exe

At the command line or 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

The native version of CMD.exe is always in %windir%\system32, on 64 bit operating systems there is also a 32 bit CMD.exe in%windir%\SysWOW64

Pausing or stopping 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.

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 and long filenames

Under Windows XP, the CMD command line is limited to 8,191 characters.
For all versions of Windows, 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

ErrorLevel

CMD /C will return an errorlevel, for example CMD /c dir Z: where the drive Z: does not exist, will return %errorlevel% = 1 to the calling CMD shell.

Full Screen

The key combination ALT + ENTER will switch a CMD window to full screen mode.
press ALT and ENTER again to return to a normal Window.

Command Extensions

Much of the functionality of CMD.exe can be disabled - this will affect all the internal commands, Command Extensions are enabled by default. This is controlled by setting a value in the registry: HKCU\Software\Microsoft\Command Processor\EnableExtensions Alternatively under Win XP you can run CMD /e:on or CMD /e:off

"Those who can command themselves, command others" - Hazlitt

Related:

EXIT - Use this to close a CMD shell and return.
CALL - Call one batch program from another
START - Start a separate window to run a specified program or command
DOSKEY Edit command line, recall commands
Q156276 - Cmd does not support UNC names as the current directory
Powershell: You may run the CMD shell under Powershell, Exit will return you to the PS prompt.
Equivalent bash command (Linux): bash - run the bash shell (also csh, ksh, sh)

CMDKEY.exe (Windows 7)

Create, list or delete stored user names, passwords or credentials.

Syntax

      cmdkey [{/add:TargetName|/generic:TargetName}]

         {/smartcard|/user:UserName [/pass:Password]}

            [/delete{:TargetName|/ras}]

               /list:TargetName

Key:

   /add            Add a user name and password to the list.

   TargetName      The computer or domain name that this entry will be associated with.

   /generic        Add generic credentials to the list.

   /smartcard      Retrieve the credential from a smart card.

   /user:UserName  The user or account name to store with this entry.

                   If UserName is not supplied, it will be requested.

   /pass:Password  The password to store with this entry. If Password is not supplied, it will be requested.

   /delete:        Delete a user name and password from the list.

                   If TargetName is specified, that entry will be deleted.

                   If /ras is specified, the stored remote access entry will be deleted.

   /list           Display the list of stored user names and credentials.

                   If TargetName is not specified, all stored user names and credentials will be listed.

If more than one smart card is found, cmdkey will prompt the user to specify which one to use.

Once stored, passwords are not displayed.

Examples:


Display a list of stored user names and credentials:

cmdkey /list

Add a user name and password for user Kate to access computer Server01 with the password passme, type:

cmdkey /add:server01 /user:Kate /pass:passme

Add a user name for user Kate to access computer Server01 and prompt for the password whenever Server01 is accessed:

cmdkey /add:server01 /user:Kate

Delete the stored credential for remote access:

cmdkey /delete /ras

Delete the stored credential for Server01:

cmdkey /delete:Server01

"The stupid neither forgive nor forget, the naive forgive and forget, the wise forgive but do not forget" - Thomas Szasz (The second sin)

Related:

CIPHER - Encrypt or Decrypt files/folders

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.

"How much more black could this be?" and the answer is "None...none more black." - Spinal Tap

Related:
CMD - Start a new CMD shell
EXIT - Set a specific errorlevel
PowerShell: Write-Host - Write output to the screen (colour can be set for individual strings).
Average colour codes - HTML/CSS
Aaron Margosis - Change prompt colors for all Admin level prompts
Color Scheme Designer - Design colour themes
Equivalent bash command (Linux): dircolors - Colour setup for `ls'

COMP.exe Compare two files (or sets of files). Display items which do not match.

Syntax

      COMP [pathname1] [pathname2] [/D] [/A] [/L] [/N=number] [/C]



Key

   pathname1 The path and filename of the first file(s)



   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 lines (common portion of each file.)

COMP will normally finish with a Compare more files (Y/N) prompt
to suppress this: ECHO n|COMP <options>

"Shall I compare thee to a summer's day" - William Shakespeare

Related:

FC - Compare two files and display any LINES which do not match
Powershell: Compare-Object - Compare the properties of objects, e.g. compare content of files.
Equivalent bash command (Linux): cmp - Compare two files

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.

For recent versions of Windows Microsoft now recommend the more flexible RUNDLL32 in preference to con2prt.

The freeware utility AdPrintX is very similar to Con2Prt but has additional functionality, including compatibility with Windows 9x systems.

"I think you know as well as I do what the problem is, Dave. You and Dr. Poole were planning to disconnect me. I cannot allow this to happen" - HAL

Related:

Qchange.vbs - Change printer connections
Network Printing - Advice & Tips
PRINT - Print a text file
NET VIEW - to view a list of printers
NET PRINT - View and Delete print jobs
PRNCNFG - Display, configure or rename a printer
PRNDRVR - Add, delete or list printer drivers.
PRNJOBS - Pause, resume, cancel, or list print jobs
PRNMNGR - Add, delete, or list printers / connections, set the default printer.
PRNPORT/PRNQCTL - Manage printer ports & printer queues.
RUNDLL32 - Install/Remove Printers (plus advanced options)
WMIC PRINTER - Set printing options through WMI
WSH: Add printer - WshNetwork.AddPrinterConnection
Q314486 - Add Printers with No User Interaction (Win XP)
Equivalent bash command (Linux): lpc - Line printer control program

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

"Success seems to be connected with action. Successful men keep moving. They make mistakes, but they don't quit" - Conrad Hilton


Related:

ROBOCOPY - Robust File and Folder Copy
XCOPY - Copy files and folders
MOVE - Move a file from one folder to another
Fcopy - File Copy for MMQ (copy changed files & compress. (Win 2K ResKit)
Permcopy - Copy share & file ACLs from one share to another. (Win 2K ResKit)
PowerShell: Copy-Item - Copy an item from one location to another
Equivalent bash command (Linux): cp - Copy one or more files to another location.

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

“I think the laptop is very good. It helps us to find some words, like our teacher will teach us... The things we didn't know, we go check on the laptop” - One Laptop per child project, Abuja, Nigeria

Related:

Q252509 - PST and MDB files cannot be made available offline
Q884739 - CSCcmd Version 1.1
mobsync /logon - Synchronization Manager

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 "(object*)")

     -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/eDirectoryOracle 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(object)(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\

"Give me your tired, your poor,
Your huddled masses yearning to breathe free,
The wretched refuse of your teeming shore.
Send these, the homeless, tempest-tossed to me,
I lift my lamp beside the golden door!"
- Emma Lazarus

Related Commands:

Q271517 - Ldifde fails if an attribute contains blank spaces.
Q327620 - Import contacts and users with CSVDE
Q263991 - How to set a user's password with Ldifde
Q276440 - Backup and Restore Connection Agreements with CSVDE

Equivalent bash command (Linux):

ldapadd - Add LDAP information

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


   United States         001          01/23/1997  5:35:00.00p



   Czechoslovakia        042          23.01.1997 17:35:00

   France                033          23.01.1997 17:35:00
   Germany               049          23.01.1997 17:35:00



   Latin America         003          23/01/1997  5:35:00.00p

   International English 061          23/01/1997 17:35:00.00



   Portugal              351          23-01-1997 17:35:00
   Finland               358          23.1.1997   17.35.00

   Switzerland           041          23.01.97   17 35.00

   Norway                047          23.01.97   17:35:00



   Belgium               032          23/01/97   17:35:00

   Brazil                055          23/01/97   17:35:00
   Italy                 039          23/01/97   17.35.00

   United Kingdom        044          23/01/97   17:35:00.00



   Denmark               045          23-01-97   17.35.00
   Netherlands           031          23-01-97   17:35:00


   Spain                 034          3/12/98    17:35:00



   Hungary               036          1997.01.23 17:35:00


   Canadian-French       002          1997-01-23 17:35:00

   Poland                048          1997-01-23 17:35:00
   Sweden                046          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:

%DATE% - variable containing current Date.
GetDate.cmd - Get todays Date (any region, any OS)
datetime.vbs - Get Date, Time and daylight savings (VB Script)
NOW - Display Message with Current Date and Time
NET TIME - Display the Date in US Format (mm-dd-yy)
REG - Read, Set or Delete registry keys and values
TIME - Display or set the system time
TOUCH - Change file timestamps
PowerShell: Set-Date - Change the computer system time
Equivalent Linux bash command: date - Display or change the date

DEFRAG Defragment hard drive.

Syntax

      DEFRAG <volume> [-a] [-f] [-v] [-?]


Options

  volume  drive letter or mount point (d: or d:\vol\mountpoint)

  -a      Analyze only

  -f      Force defragmentation even if free space is low

  -v      Verbose output

Example:

DEFRAG c: -f

"How can you expect to govern a country that has two hundred and forty-six kinds of cheese?" - Charles de Gaulle

Related Commands:

CleanMgr - Automated cleanup of Temp files, Internet files, downloaded files, recycle bin
DISKPART - Partition manager
pagefileconfig.vbs - PageFile Configuration

DEL Delete one or more files.

Syntax

      DEL [options] [/A:file_attributes] files_to_delete


Key

   files_to_delete : This may be a filename, a list of files or a Wildcard

options

   /P  Give a Yes/No Prompt before deleting.

   /F  Ignore read-only setting and delete anyway (FORCE)

   /S  Delete from all Subfolders (DELTREE)

   /Q  Quiet mode, do not give a Yes/No Prompt before deleting.



   /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"
DEL "Hello Big World.TXT"

To delete all files that start with the letter A
DEL A*

To delete all files that end with the letter A
DEL *A.*

To delete all files with a .DOC extension
DEL *.DOC

To delete all read only files
DEL /a:R *

To delete all files including any that are read only
DEL /F *

Folders
If a folder name is given instead of a file, all files in the folder will be deleted, but the folder itself will not be removed.

Temporary Files
You should clear out TEMP files on a regular basis - this is best done at startup when no applications are running. To delete all files in all subfolders of C:\temp\ but leave the folder structure intact:

   DEL /F /S /Q %TEMP%

When clearing out the TEMP directory it is not generally worthwhile removing the subfolders too - they don't use much space and constantly deleting and recreating them can potentially increase fragmentation within the Master File Table.

Deleting a file will not prevent third party utilities from 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
DEL C:\examples\MyFile.txt

Undeletable Files

Files are sometimes created with the very long filenames or reserved names: CON, AUX, COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, NUL
To delete these use the syntax: DEL \\.\C:\somedir\LPT1
Alternatively SUBST a drive letter to the folder containing the file.

If a file (or folder) still appears to be 'undeletable' this is often caused by the indexing service.
Right click the file you need to delete, choose properties, advanced and untick "allow indexing" you will then be able to delete the file.
To cure the problem permanently - Control Panel, Add/Remove programs, Win Accessories, indexing service.

Delete Locked files (Typically IE temp files or the Offline cache)
This works on any version of NT, 2000 or XP

Close all applications
Open a command prompt
Click Start, and then Shut Down
Simultaneously press CTRL+SHIFT+ALT.
While you keep these keys pressed, click Cancel in the Shut Down Windows dialog box.
In the command prompt window, navigate to the cache location, and delete all files from the folder (DEL /s)
At the command prompt, type explorer, and then press ENTER.

DELTREE

Previous versions of Windows had the DELTREE command that deletes all files and sub folders.
DEL /s will delete all files
RD /s will remove all files and folders including the root folder.

:: Remove all files and subfolders but NOT the root folder

:: From tip 617 at JsiFAQ.com

@echo off

pushd %1

del /q *.*

for /f "Tokens=*" %%G in ('dir /B') do rd /s /q "%%G"

popd

Normally DEL will display a list of the files deleted, if Command Extensions are disabled; it will instead display a list of any files it cannot find.

ERASE is a synonym for DEL

"It devoured my paper, it was a really good paper" - Ellen Feiss

Related:

DELPROF
 Delete NT user profiles
Delrp - Delete a file/directory and NTFS reparse points.(Win 2K ResKit)
RD - Delete folders or entire folder trees ()
CleanMgr - Automated cleanup of Temp files, Internet files, downloaded files, recycle bin
FORFILES - Delete files older than X days
INUSE - updated file replacement utility (may not preserve file permissions)
Q120716 - Delete in-use files with rm
Q315226 - Remove Files with Reserved Names
Q320081 - Cannot delete a file or folder
Q159199 - A file cannot be deleted (NTFS)
PowerShell: Remove-Item - Delete the specified items.
Equivalent bash command (Linux): rmdir / rm - Remove folders/ files

DELPROF (Resource Kit) Delete windows user profiles.

Syntax

      DELPROF [options days]



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

“The best way to destroy the capitalist system is to debauch the currency”- John Keynes

Related Commands:

DEL Delete one or more files
DELTREE Delete a folder and all subfolders
RD - Delete folders or entire folder trees (DELTREE)

DEVCON.exe (Download)

Device Manager

Syntax

      devcon.exe [-r] [-m:\\machine] command [arg...]

      devcon.exe help command

Key

   -r       Reboot the machine after command is complete, if needed.

   machine  Name of target machine.

   command  The command to perform (see below).

   arg...   One or more arguments if required by command.

Commands:

  classfilter    Allow modification of class filters.

  classes        List all device setup classes.

  disable        Disable devices that match the specific hardware/instance ID.

  driverfiles    List driver files installed for devices.

  drivernodes    List all the driver nodes of devices.

  enable         Enable devices that match the specific hardware/instance ID.

  find           Find devices that match the specific hardware/instance ID.

  findall        Find devices including those that are not present.

  help           Display this information.

  hwids          List 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/instance ID.

  rescan         Scan for new hardware.

  resources      List hardware resources of devices.

  restart        Restart devices that match the specific hardware/instance ID.

  stack          List 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        Add, delete, and change the order of hardware IDs of root-enumerated devices.

DevCon is not redistributable. It is provided for use as a debugging and development tool. 

Examples:


List all known PCI devices on the computer pc64.

devcon -m:\\pc64 find pci\*

Install a new instance of the Microsoft loopback adaptor and restart if required. This creates a new root-enumerated device node with which you can install a "virtual device," such as the loopback adaptor.

devcon -r install %WINDIR%\Inf\Netloop.inf *MSLOOP

List all known setup classes. Displays both the short name and the descriptive name.

devcon classes

Lists files that are associated with each device in the ports setup class.

devcon driverfiles =ports

Disable all devices that have a hardware ID that ends in "MSLOOP" (including "*MSLOOP").

devcon disable *MSLOOP

List 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 drivernodes @ROOT\PCI_HAL\PNP0A03

Enable 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 enable '*MSLOOP

List device instances of all devices that are present on the local computer.

devcon find *

List 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 pci\*

List devices that are a member of the ports setup class and that contain "PNP" in their hardware ID.

devcon find =ports *pnp*

List 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 find =ports @root\*

List "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 findall =ports

List all devices that are present for each class named (in this case, USB and 1394).

devcon listclass usb 1394

Remove all USB devices. Devices that are removed are listed with their removal status.

devcon remove @usb\*

Rescan for new Plug and Play devices.

devcon rescan

List the resources that are used by all devices in the ports setup class.

devcon resources =ports

Restart the loopback adaptor ROOT\*MSLOOP\0000. The single quotation mark in the command indicates that the instance ID must be taken literally.

devcon restart =net @'ROOT\*MSLOOP\0000

List all hardware IDs of mouse class devices on the system.

devcon hwids=mouse

Assign the hardware ID, beep, to the legacy beep device.

devcon sethwid @ROOT\LEGACY_BEEP\0000 := beep

List the status of each device present that has an instance ID that begins with "pci\".

devcon status @pci\*

List the status of an Advanced Configuration and Power Interface (ACPI)-enumerated serial port.

devcon status @ACPI\PNP0501\1

List the status of all COM ports.

devcon status *PNP05*

Errorlevels returned by DevCon.exe:
0 = success.
1 - restart is required.
2 = failure.
3 = syntax error.

“I've learned that people will forget what you said, people will forget what you did, but people will never forget how you made them feel” - Maya Angelou

Related:

DISKPART - Disk Administration
FSUTIL - File and Volume utilities
Powershell: Out-Clipboard (PowerShell Community Extension)
Equivalent bash command (Linux): xsel - get and set the contents of an X-window selection

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 and above)

   /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.

On Windows Vista and later, a list of alternate data streams can be obtained using DIR /R, On earlier operating systems, the SysInternals utilitystreams can be used instead.

“There it was, hidden in alphabetical order” - Rita Holt

Related

WHERE - Locate and display files in a directory tree.
XCOPY /L - List files without copying.
ROBOCOPY /L - List files with specific properties
DIRUSE - show size of multiple subfolders. (Resource Kit)
Freedisk.exe - check free disk space. (Win 2K ResKit)
Powershell: Get-ChildItem - Get child items (contents of a folder or registry key) dir / ls / gci
You can also get File Sizes and Date/Time from Windows 2000/XP Batch Parameters
Use DIR to display drive status - disk missing / ready / empty
Q226370 - Browsing LAN directories is slow
Equivalent bash command (Linux): ls - List information about file(s)

DIRUSE (2K Resource Kit / XP Support Tools) Display disk usage

Syntax

      DIRUSE [options] Folders...

Options

   /M  Display in Mb

   /K  Display in Kb

   /B  Display in bytes (default)

   /,  Use thousand separator when displaying sizes.

   /Q:#    Quota limit, mark folders that exceed the size (#) with a "!".

           set %errorlevel% to ONE if any folders are found that

           exceed the specified size



   /* 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

"Work is achieved by those employees who have not yet reached their level of incompetence" - Laurence J. Peter (The Peter Principle)

Related

DIR
 - Display a list of files and folders
You can also list files with XCOPY /L
Freedisk.exe - check free disk space. (Win 2K ResKit)
FSUTIL - File and Volume utilities
Powershell: Get-ChildItem - Get child items (contents of a folder or registry key) dir / ls / gci
Equivalent bash command (Linux): quotacheck - Scan a file system for disk usage

DISKCOMP.com Compare the content of two floppy disks.

Syntax

      DISKCOMP floppy_drive1: floppy_drive2:



Key

      floppy_drive is the drive letter

The two disks must be the same type,
e.g. both 1.44 Mb or both 720 K

If you specify the same drive letter for floppy_drive1 and floppy_drive2 - you will be prompted to enter each disk.

For Example:

DISKCOMP A: A:

"I don't want to sound like I'm bragging but I think I've finally managed to play the record at the right speed - John Peel 

Related:

DISKCOPY - Copy the contents of one floppy disk to another
FC - Compare two files or sets of files, and display the differences between them
Equivalent bash command (Linux): cksum - Print CRC checksum and byte counts

DISKCOPY.com Copy the content of one floppy disk to another.

Syntax

      DISKCOPY flopppy_drive1: floppy_drive2: [/V]

Key
         /V   Verify that the information was copied correctly.

The two disks must be the same type,
e.g. both 1.44 Mb or both 720 K

If you specify the same drive letter for floppy_drive1 and floppy_drive2 - you will be prompted to enter each disk.
DISKCOMP A: A:

"The great secret that all old people share is that you really haven't changed in seventy or eighty years. Your body changes, but you don't change at all. And that, of course, causes great confusion." - Doris Lessing 

Related:

DISKCOMP - Compare the contents of two floppy disks
FC - Compare two files or sets of files, and display the differences between them

DiskPart (Windows 7) Disk Administration, Partition a disk. This page documents the Windows 7/2008 version of Diskpart, an earlier version of Diskpart is supplied in the 2003 Resource kit with a reduced set of options.

Syntax

      DISKPART



Commands you may then issue at the DISKPART prompt:



LIST Disk

LIST Partition

LIST Volume



SELECT Disk=n

SELECT Partition=n

SELECT Volume=n_or_d  (Number or Drive Letter)



DETAIL Disk

DETAIL Partition

DETAIL volume



ACTIVE  (set the current in-focus partition to be the system partition)

ASSIGN         (allocate the next free drive letter)

ASSIGN LETTER=E   (Choose a free letter)

ATTRIBUTES DISK [{set | clear}] [readonly] [noerr]
 ATTRIBUTES VOLUME [{set | clear}] [{hidden | readonly | nodefaultdriveletter | shadowcopy}] [noerr]

AUTOMOUNT [enable] [disable] [scrub] [noerr]

FILESYSTEMS     (Use 'Select Volume' first)

HELP

INACTIVE   (mark a system/boot partition as inactive [don't boot], use 'Select Partition' first)

OFFLINE disk [noerr] (Take the current disc offline, use 'Select Disk' first)

ONLINE {disk|volume} [noerr]

REM  (remark/comment)

REMOVE letter=E [dismount] [noerr]  (Remove drive letter E from the in-focus partition)

REMOVE mount=path [dismount] [noerr]  (Remove mount point from the in-focus partition)

REMOVE /ALL [dismount] [noerr]    (Remove ALL current drive letters and mount points)

RESCAN     (Locate new disks that have been added to the computer)

SHRINK [desired=n] [minimum=n] [nowait] [noerr]  (Reduce the size of the in-focus volume)
 SHRINK querymax [noerr]

EXIT

UNIQUEID disk [id={dword | GUID}] [noerr]   (Display or set the GUID partition table identifier

                                              or MBR signature for the disk with focus)

 

Commands to Manage Basic Disks:



ASSIGN MOUNT=path  (Choose a mount point path for the volume)



CREATE PARTITION Primary Size=50000  (50 GB)

CREATE PARTITION Extended Size=25000

CREATE PARTITION logical Size=25000

DELETE Partition

EXTEND Size=10000

GPT attributes=n   (assign GUID Partition Table attributes)

SET id=byte|GUID [override] [noerr]   (Change the partition type)



Commands to Manage Dynamic Disks:



ADD disk=n   (Add a mirror to the in-focus SIMPLE volume on the specified disk

               see 'Diskpart Help' for more.)

BREAK disk=n  (Break the current in-focus mirror)

CREATE VOLUME Simple Size=n Disk=n

CREATE VOLUME Stripe Size=n Disk=n,n,...

CREATE VOLUME Raid Size=n Disk=n,n,...

DELETE DISK

DELETE PARTITION

DELETE VOLUME

EXTEND Disk=n [Size=n]

EXTEND Filesystem [noerr]

IMPORT [noerr]   (Import a foreign disk group, use 'Select Disc' first)

RECOVER [noerr]  (Refresh disc pack state, attempt recovery on an invalid pack,

                   & resynchronize stale plex/parity data.)

REPAIR disk=n [align=n] [noerr]  (Repair the RAID-5 volume with focus, replace with the specified dynamic disk)

RETAIN   (Prepare an existing dynamic simple volume to be used as a boot or system volume)



Commands to Convert Disks



CONVERT basic

CONVERT dynamic

CONVERT gpt

CONVERT mbr

CLEAN [ALL]   (remove all partition and volume info from the hard drive)

FORMAT [{fs=ntfs|fat|fat32] [revision=x.xx] | recommended}]

           [label="label"] [unit=n] [quick] [compress]

              [override] [nowait] [noerr]

The diskpart commands may be placed in a text file (one command per line) and used as an input file to diskpart.exe:

DiskPart.exe < myscript.txt



Example:



SELECT DISK=0

CREATE PARTITION PRIMARY

ASSIGN LETTER=E

SELECT PARTITION=1

FORMAT FS=NTFS LABEL="New Volume" QUICK

EXIT

noerr - This option is for scripting only. With noerr set, when an error is encountered, DiskPart will continue to process commands as if the error did not occur. Without this parameter, an error causes DiskPart to exit with an error code.

When selecting a volume or partition, you may use either the number or drive letter or the mount point path.

Always back up the hard disk before running diskpart.

"Divide et impera" - Latin saying (Divide and conquer) 

Related:

Q325590 - Use Diskpart.exe to extend a data volume
Q300415 - Diskpart for Win XP
FSUTIL - File and Volume utilities
Equivalent bash command (Linux): fdisk - Partition table manipulator for Linux

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 Keyboard shortcuts at the command line

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 only saved for the current 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. Then to restore all the doskey macros setup in the current session at a later date, just run ' macros.cmd'.

“No man steps in the same river twice, for it's not the same river, and he's not the same man” - Heraclitus

Related:

Powershell: SendKeys (Snapin)
Equivalent bash commands (Linux): m4 - Macro processor, history - Command history

DSACLS.exe View or Edit ACLs (access control entries) for objects in Active Directory.

Syntax

      DSACLS "[\\Computer\]ObjectDN" [/A] [/D PermissionStatement [PermissionStatement]...]

         [/G PermissionStatement [PermissionStatement]...] [/I:{T | S | P}]

            [/N] [/P:{Y | N}]

               [/R {User | Group} [{User | Group}]...] [/S [/T]]

                   

      PermissionStatements:

         {User | Group}:Permissions[;{ObjectType | Property}][;InheritedObjectType]

  

Key

   ObjectDN  Distinguished name of the object.

             If omitted will be taken from standard input (stdin)



   /A   Add ownership and auditing information to the results.



   /D   Deny permissions to a user or group



   /G   Grant permissions to a user or group.



   /I:  Inheritance

           T  The object and its child objects (default)

           S  The child objects only

           P  The object and child objects down one level only



   /N   Replace the current ACEs in the ACL.

        By default, dsacls adds the ACE to the ACL.

          

   /P:  Inherit permissions from parent objects (Y/N).



   /R   Revoke/Delete all ACEs for the users or groups.



   /S   Restore the default security.

        Default security for each object class is defined in the Active Directory schema.



  /S /T Restore the default security on the tree of objects.



Permissions

      GR: Generic Read

      GE: Generic Execute

      GW: Generic Write

      GA: Generic All



      SD: Delete an object

      DT: Delete an object and all of its child objects

      RC: Read security information

      WD: Change security information

      WO: Change owner information

      LC: List the child objects of the object

      CC: Create a child object•

      DC: Delete a child object•

      WS: Write to a self object (group membership) group object + {ObjectType | Property} = "member."

      RP: Read a property•

      WP: Write to a property•

      CA: Control access (normally a specific extended right for control access)

             If you do not specify {ObjectType | Property} this permission will apply to all

             meaningful control accesses on the object.

      LO: List the object access, AD DS does not enforce this permission by default.

             Grant list access to a specific object when List Children (LC) is not granted to the parent.

             Deny list access to a specific object when the user or group has LC permission on the parent.



   ObjectType | Property

          Limit the permission to the specified object type or property.

          Enter the display name of the object type or the property.

          Default=all object types and properties.



          For example, Grant the user rights to create all types of child objects:

          /G Domain\User:CC



          Grant the user rights to create only child computer objects:

          /G Domain\User:CC;computer



   InheritedObjectType

          Limit inheritance of the permission to the specified object type.

          For example, Grant only User objects to inherit the permission:

          /G Domain\User:CC;;user



   Object Types

          User,Contact,Group,Shared Folder,Printer,Computer,Domain Controllers,OU

• If you do not specify {ObjectType | Property} to define a specific child object type, this permission applies to all types of child objects; otherwise, it applies only to the child object type that you specify.

You can Grant, Deny or Delete ACEs for multiple users and groups with a single parameter (/G /D /R), list the users/groups separated with spaces.

DS* commands are available on networked machines with the server role A.D. Domain Services installed, Domain Controllers (or for XP users: XP Professional).

Examples

Grant Generic Read (GR) and Generic Execute (GE) on computer objects in the Laptops OU to Jdoe:

C:\> dsAcls "OU=Laptops,OU=AcmeCo,DC=ss64,DC=Com" /G Domain\JDoe:GRGE;computer

“If future generations are to remember us with gratitude rather than contempt, we must leave them more than the miracles of technology. We must leave them a glimpse of the world as it was in the beginning, not just after we got through with it” - President Lyndon B. Johnson

Related:

Q281146 - How to Use Dsacls in Windows Server 2003
DSAdd - Add object
DSMod - Modify object
DSGet - Display object
DSMove - Move object
DSQuery - Search for objects
DSdbUtil - Maintenance of AD, Authorative Restore, manage snapshots.
DSAMain - Expose Active Directory data that is stored in a snapshot or backup
DSMgmt - Configure Directory Services

DSADD.exe Add active directory object.

Syntax

   DSADD Computer

   DSADD Contact

   DSADD Group

   DSADD OU

   DSADD User

   DSADD Quota

DS* commands are available on networked machines with the server role A.D. Domain Services installed, Domain Controllers (or for XP users: XP Professional).

Special characters in distinguished names

Commas within a CN must be escaped with the backslash \ character
e.g. "CN=Company\, Inc.,CN=Users,DC=ss64,DC=com"

Backslashes must also 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:
e.g. "CN=John Smith,CN=Users,DC=SS64,DC=com"

Redirection
You can pipe results from DSQUERY into DSMOD in order to modify an object. If the DN contains any commas or backslashes you will need to redirect to a file first and add the escape characters as above.

Special Tokens
The token $username$ (case insensitive) may be used to place the SAM account name.
Entering * as a password will cause DSADD to prompt for the new password.

Adding multiple Objects
For any DS command you can enter multiple values separated by spaces.
e.g. to add several user accounts at once just supply a list of the distinguished names separated with spaces.
It is also possible to store multiple values in a text file and redirect into DSADD.

How to Organize Active Directory This is a common question, so below is an example starting point, this assumes a domain name of SS64.com, obviously customise that to your own domain.

Placing everything under a single OU, (in this case ACMECo) makes it easy to apply group policy to everything, though in almost all cases you would do this one level down - applying policy to all users or all workstations. Separate OUs are setup for Users, Groups, Servers, Workstations and the IT department (Admin).

AcmeCo

AcmeCo/Admin        (OU=Admin,OU=AcmeCo,DC=ss64,DC=com)

AcmeCo/Groups       (OU=Groups,OU=AcmeCo,DC=ss64,DC=com)

AcmeCo/Users        (OU=Users,OU=AcmeCo,DC=ss64,DC=com)

AcmeCo/Servers      (OU=Servers,OU=AcmeCo,DC=ss64,DC=com)

AcmeCo/Laptops      (OU=Laptops,OU=AcmeCo,DC=ss64,DC=com)

AcmeCo/Workstations (OU=Workstations,OU=AcmeCo,DC=ss64,DC=com)

AcmeCo/Workstations/Site1

AcmeCo/Workstations/Site2

AcmeCo/Workstations/Site3



PartnerCo           An OU for external contacts

PartnerCo/Users        (OU=Users,OU=PartnerCo,DC=ss64,DC=com)

PartnerCo/Workstations (OU=Workstations,OU=PartnerCo,DC=ss64,DC=com)

If possible store all USER accounts in a single OU. Organisations change and people move around, there is rarely any reason to reflect every such change in Active Directory. One reason for adding additional USER OUs is to allow delegated rights i.e. to allow super users to do password resets.

The default (built in) Organizational Units (OUs) for Users (CN=Computers,DC=ss64,DC=com) and Computers (CN=Users,DC=ss64,DC=com) will often be used by application installers when creating service accounts.

“Find a job you like and you add five days to every week” - H. Jackson Brown, Jr

Related commands:

DSMod - Modify object
DSGet - Display object
DSMove - Move object
DSQuery - Search for objects
DSRM - Delete object
CSVDE - Import or export AD info in CSV format.
LDIFDE - Edit AD Objects, extend schema, import or export AD information.
Equivalent bash commands (Linux): ldapmodify - Modify Lightweight Directory Access Protocol

DSGET.exe View active directory objects.

Syntax

   DSGet Computer

   DSGet Contact

   DSGet Group

   DSGet OU

   DSGet Partition

   DSGet Quota

   DSGet Server

   DSGet Subnet

   DSGet User

DS* commands are available on networked machines with the server role A.D. Domain Services installed, Domain Controllers (or for XP users: XP Professional).

Special characters in distinguished names

Commas within a CN must be escaped with the backslash \ character
e.g. "CN=Company\, Inc.,CN=Users,DC=ss64,DC=com"

Backslashes must also 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:
e.g. "CN=John Smith,CN=Users,DC=SS64,DC=com"

Redirection
You can pipe results from DSQUERY into DSGet in order to view multiple objects. If the DN contains any commas or backslashes you will need to redirect to a file first and add the escape characters as above.

Special Tokens
The token $username$ (case insensitive) may be used to place the SAM account name.
Entering * as a password will cause DSMOD to prompt for the new password.

For any DS command you can enter multiple values separated by spaces.
e.g. to modify several user accounts at once just supply a list of the distinguished names separated with spaces.

“A good reputation is more valuable than money” - Publilius Syrus

Related commands:

DSAdd - Add object
DSMod - Modify object
DSGet - Display object
DSMove - Move object
DSQuery - Search for objects
DSRM - Delete object
CSVDE - Import or export AD info in CSV format.
LDIFDE - Edit AD Objects, extend schema, import or export AD information.
Q322684 - Directory Service Command-Line Tools
Equivalent bash commands (Linux): ldapmodify - Modify Lightweight Directory Access Protocol

DSQUERY Search for an active directory object.

Syntax

   DSQuery Computer

   DSQuery Contact

   DSQuery Group

   DSQuery OU

   DSQuery Site

   DSQuery Server

   DSQuery User

   DSQuery Quota

   DSQuery Partition

   DSQuery *  (LDAP query)

DS* commands are available on networked machines with the server role A.D. Domain Services installed, Domain Controllers (or for XP users: XP Professional).

Commas within a CN must be escaped with the backslash \ character CN=Company\, Incorporated...

Escape Backslashes with a second backslash CN=Sales\\ Latin America...

If any value contains spaces, use quotation marks: "CN=John Smith,CN=Users,DC=SS64,DC=com"

Special Tokens
The token $username$ (case insensitive) may be used to place the SAM account name.
Entering * as a password will prompt for a new password.

Adding multiple Objects
For any DS command you can enter multiple values separated by spaces.
e.g. to add several user accounts at once just supply a list of the distinguished names separated with spaces.

It is also possible to store multiple values in a text file and redirect into DSQUERY.

Powershell
To call dsquery and store the resulting string in a powershell array variable (from PowershellHell):
$arrComputerList = $(&dsquery computer -limit 0)|%{$_.Split("=")[1].replace(",OU","").replace(",CN","")}

“A good question is like a miniskirt. Long enough to cover the essentials, but short enough to keep everyone interested” - Charles Halsey

Related commands:

DSAdd - Add object
DSMod - Modify object
DSGet - Display object
DSMove - Move object
DSQuery - Search for objects
DSRM - Delete object
CSVDE - Import or export AD info in CSV format.
LDIFDE - Edit AD Objects, extend schema, import or export AD information.
Equivalent bash commands (Linux): ldapmodify - Modify Lightweight Directory Access Protocol

DSMOD.exe Modify active directory object.

Syntax

   DSMOD Computer

   DSMOD Contact

   DSMOD Group

   DSMOD OU

   DSMOD Server

   DSMOD User

   DSMOD Quota

   DSMOD Partition

DS* commands are available on networked machines with the server role A.D. Domain Services installed, Domain Controllers (or for XP users: XP Professional).

Special characters in distinguished names

Commas within a CN must be escaped with the backslash \ character
e.g. "CN=Company\, Inc.,CN=Users,DC=ss64,DC=com"

Backslashes must also 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:
e.g. "CN=John Smith,CN=Users,DC=SS64,DC=com"

Redirection
You can pipe results from DSQUERY into DSMOD in order to modify an object. If the DN contains any commas or backslashes you will need to redirect to a file first and add the escape characters as above.

e.g. To find all users in the Marketing OU (organizational unit) and add them to the Sales group:

DSQUERY user -startnode "ou=Marketing,dc=SS64,dc=com" | DSMOD group "cn=Sales,ou=Marketing,dc=SS64,dc=com" -addmbr

Special Tokens
The token $username$ (case insensitive) may be used to place the SAM account name.
Entering * as a password will cause DSMOD to prompt for the new password.

For any DS command you can enter multiple values separated by spaces.
e.g. to modify several user accounts at once just supply a list of the distinguished names separated with spaces.

“The aim of science is not to open the door to infinite wisdom but to set a limit to infinite error” - Bertolt Brecht ‘Life of Galileo’

Related commands:

DSAdd - Add object
DSMod - Modify object
DSGet - Display object
DSMove - Move object
DSQuery - Search for objects
DSRM - Delete object
ADmodcmd - Active Directory Bulk Modify
CSVDE - Import or export AD info in CSV format.
LDIFDE - Edit AD Objects, extend schema, import or export AD information.
Q322684 - Directory Service Command-Line Tools
Equivalent bash commands (Linux): ldapmodify - Modify Lightweight Directory Access Protocol

DSMOVE.exe Rename or Move an active directory object (user, computer, group..) to a different Organisational Unit (OU).

Syntax

      dsmove ObjectDN [-newname NewRDN] [-newparent ParentDN]

        [{-s Server | -d Domain}]

            [-u UserName] [-p {Password | *}]

               [-q] [{-uc | -uco | -uci}]



Options

   ObjectDN   Distinguished name of the computer that you want to add.

              If omitted will be taken from standard input (stdin)



   -newname   Rename the object with a new Relative Distinguished Name.



   -newparent New location for the object, enter the new parent DN.



   -q         Quiet, suppress all output



   -uc        Unicode format

   -uco       Unicode format for output only

   -uci       Unicode format for input only



   -u UserName The user name with which a user logs on to a remote server.

               By default, the currently logged on user.



   -p Password The password, or * to prompt for a password.

By default, DSMOVE connects the computer to the domain controller in the logon domain.

DS* commands are available on networked machines with the server role A.D. Domain Services installed, Domain Controllers (or for XP users: XP Professional).

For any DS command you can enter multiple values separated by spaces.
e.g. to modify several user accounts at once just supply a list of the distinguished names separated with spaces.

Examples

Rename a user:

C:\> set _andy="CN=Andrew Gorden,OU=Europe,DC=ss64,DC=Com"

C:\> dsmove %_andy% -newname "Andrew Gordon"

Move a user to a different OU

C:\> set _andy="CN=Andrew Gordon,OU=Europe,DC=ss64,DC=Com"

C:\> set _newOrgUnit="OU=Asia,DC=ss64,DC=Com"

C:\> dsmove %_andy% -newparent %_newOrgUnit%

“All that glitters is not gold. All who wander are not lost” - William Shakespeare

Related commands:

DSAdd - Add object
DSMod - Modify object
DSGet - Display object
DSQuery - Search for objects
DSRM - Delete object
CSVDE - Import or export AD info in CSV format.
LDIFDE - Edit AD Objects, extend schema, import or export AD information.
Q322684 - Directory Service Command-Line Tools
Equivalent bash commands (Linux): ldapmodify - Modify Lightweight Directory Access Protocol

DSRM

Delete objects from active directory.

Syntax

      DSRM ObjectDN [-subtree [-exclude]] [-noprompt]

            [{-s Server | -d Domain}] [-u UserName] [-p {Password | *}]

               [-c] [-q] [{-uc | -uco | -uci}]

Key

   ObjectDN  Distinguished name of the group that you want to remove.

             If omitted will be taken from standard input (stdin)

   -subtree  Delete the object and all objects contained in its subtree.

   -exclude  Delete all objects contained in the subtree, but not the object itself.

   -noprompt Do not prompt to confirm deletion.

   -s Server Connect to a remote server/domain, default=%logonserver% domain controller.

   -c        Continue with the next object after any error (when you specify multiple target objects)

             by default dsrm will exit when the first error occurs.

   -q        Quiet, suppress all output

   -uc       Unicode format

   -uco      Unicode format for output only

   -uci      Unicode format for input only

DS* commands are available on networked machines with the server role A.D. Domain Services installed, Domain Controllers (or for XP users: XP Professional).

Examples

Remove all objects under the OU AcmeCo, but leave the OU intact:

C:\> dsrm -subtree -exclude -noprompt -c "OU=AcmeCo,DC=ss64,DC=Com"

Find all computers that have been inactive for the last eight weeks and remove them:

C:\> dsquery computer -inactive 8 | dsrm

“If future generations are to remember us with gratitude rather than contempt, we must leave them more than the miracles of technology. We must leave them a glimpse of the world as it was in the beginning, not just after we got through with it” - President Lyndon B. Johnson

Related:

DSAdd - Add object
DSMod - Modify object
DSGet - Display object
DSMove - Move object
DSQuery - Search for objects
OldCmp - Joeware utility for safely removing User and Computer accounts.

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%

An alternative is to separate with : instead of a space, this has some performance benefits.

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 using Sound Recorder or Media Player:

START/min sndrec32 /play /close %windir%\media\ding.wav

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.

“The only thing that helps me pass the time away; is knowing I'll be back at Echo Beach some day” - Martha and the Muffins

Related:

SET - Create and display environment variables
TYPE - Display the contents of a text file
BigText.cmd - Batch file to echo giant size characters
NET SEND %COMPUTERNAME%
Q177795 - Large vs Small fonts
Q901115 - Terminal Services/Citrix client makes beep sounds
Equivalent Powershell command: Write-Host
Equivalent bash command (Linux): echo - Display message on screen

ENDLOCAL

End localisation of environment changes in a batch file. Pass variables from one batch file to another.

Syntax

      ENDLOCAL

If SETLOCAL is used to make variables 'local' to one batch script, then those variables will be invisible to all other batch scripts unless explicitly passed using an ENDLOCAL & SET... command.

If SETLOCAL is used without a corresponding ENDLOCAL then local environment variables will be discarded when the batch file ends. Ending the cmd.exe session will discard all Environment Variables both local and global.

Passing variables from one routine to another

The CMD command processor always works on a line-by-line basis, so it will convert all %variables% into their text values before executing any of the commands.

By putting ENDLOCAL & SET commands on a single line you are able to SET a variable just before the localisation is ended by the ENDLOCAL command.


Examples:

::Sales.cmd

  

   @Echo off

   SETLOCAL

      Set _item="Ice Cream Maker"

      Set _price=450

   ENDLOCAL & SET _return1=%_item%& SET _return2=%_price%

::Results.cmd

   @Echo off

   SETLOCAL

   CALL Sales.cmd

   Echo [%_return1%] will cost [%_return2%]

::SubDemo.cmd

  

   @Echo off

   SETLOCAL

   CALL sub_products

   Echo [%_return1%] will cost [%_return2%]

   :sub_products

   SETLOCAL

      Set _item="Coffee Grinder"

      Set _price=150

   ENDLOCAL & SET _return1=%_item%& SET _return2=%_price%

Multiple SET commands may be added to pass multiple variables, just prefix each with an &
Be aware that any trailing spaces    will be added to the variables value.

Improving readability

The 'ENDLOCAL & SET' technique described above can become difficult to read if you have a lot of SET commands all on the same line. This can be made easier to read if you first store all the Set assignments in a single variable (_returns) as shown below (thanks to Ilya Bobyr for this technique)

Set _returns=^
  Set _return1=%_item%^&^
  Set _return2=%_price%^&^
  Set _return3=%_discount%^&^
  Set _return4=%_delivery%

Endlocal & %_returns%

In these examples we have used the variable names _return1, _return2 etc, but you can use any names for the return variables, even re-use the exact same variable name inside and outside the ENDLOCAL command (SET _price=%_price%)

"A good place to visit, but a poor place to stay" - Josh Billings

Related:

SETLOCAL - Begin localisation of environment variables in a batch file.
Equivalent bash command (Linux): readonly - Mark variables/functions as readonly

EVENTCREATE (Windows 2003/2008) Add a message to the Windows event log, requires administrator rights.

Syntax

      EVENTCREATE [/S system [/U username [/P [password]]]] /ID eventid

            [/L logname] [/SO srcname] /T type /D description



Key:

    /S system         The remote system to connect to.



    /U [domain\]user  User credentials under which to execute.



    /P [password]     Password for user, will prompt if omitted.



    /L logname        The event log to create an event in.



    /T type           The type of event to create: SUCCESS, ERROR, WARNING, INFORMATION.



    /SO source        The source to use for the event  A text string that represents the application

                      or component that is generating the event. Default='eventcreate'



    /ID id            Event ID, a number between 1 - 1000.



    /D description    Description text for the new event.



    /?                Help

Examples:

Add an ERROR to the Application log:
C:\> EVENTCREATE /T ERROR /ID 1000 /L APPLICATION /D "My application error mesaage"

Add a WARNING to the Application log for Application SS64App:
C:\> EVENTCREATE /T WARNING /ID 500 /L APPLICATION /SO SS64App /D "Running low on diskspace"

Add an ERROR to the Application log on Server401:
C:\> EVENTCREATE /S Server401 /T ERROR /ID 250 /L APPLICATION /D "Something bad happened"

Add an ERROR to the Application log on Server401:
C:\> EVENTCREATE /S Server401 /U billg /P password /ID 250 /T ERROR /L APPLICATION /D "Something bad happened"

“Ideology: a system of organizing principals, a way of seeing the world as the basis of a social or political philosophy or program” 

Related:

EVENTQUERY - Read an event log message
EVENTTRIGGERS - Display and configure Event Triggers
LOGEVENT Write text to the NT event viewer
Powershell: Get-Eventlog - Get / write eventlog data
WshShell.LogEvent - Log an item in the Event log
WMIC NTEVENTLOG - WMI access to the event log
Q131008 - Use eventlog from a batch file

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 If we get this far 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.

“Gentlemen you can't fight in here this is the war room” - President Muffley (Dr. Strangelove)

Related:

VERIFY - Provides an alternative method of raising an errorlevel without exiting
KILL - Remove a program from memory
Powershell: Exit - Exit Powershell
Equivalent bash command (Linux): break - Exit from a loop

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

Related:

ATTRIB - Display or change file attributes
COPY - Copy one or more files to another location
Equivalent bash command (Linux): gzip - Compress or decompress named file(s)

EXPAND Uncompress one or more compressed files.

Syntax

      EXTRACT [options] CAB_file [filenames]



Key

   CAB_file  : Cabinet file



   filenames : Name of the file to extract from the cabinet

               Wild cards (*.*) (.) and multiple files are valid



options

      /A       Process ALL cabinets. (where CABs are linked)



      /C       If the CAB contains one file then /C will

               copy from DMF disks



      /D       Display CAB directory



      /E       Extract all (use instead of *.* to extract all files)



      /L dir   Location to place extracted files (default is current folder)



      /Y       Overwrite files without any prompt

Related Commands:

ATTRIB - Display or change file attributes
COPY - Copy one or more files to another location
Equivalent bash command (Linux): gzip - Compress or decompress named file(s)

FC.exe Compare the contents of two files or sets of files. Display any lines which do NOT match.

Syntax

      FC /B pathname1 pathname2



      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 cmdlet, 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

# Oh lord won't you buy me a Mercedes Benz, my friends all drive Porsches, I must make amends # - Janice Joplin 

Related:

Q953929 - FC.exe command does not work correctly in Windows XP when files differ on every 128th byte
COMP - Compare two files and display any characters which do NOT match
FIND - Search for a text string in a file
FINDSTR - Search for strings in files
WinDiff - GUI to compare files
Powershell: Compare-Object - Compare the properties of objects, e.g. compare content of files.
Equivalent bash command (Linux): cmp - Compare two files

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

  Arnold Jones, 127 Scotland Street, Edinburgh

To search for "Jones" in names.txt

FIND "Jones" names.txt

---------- NAMES.TXT

Arnold Jones, 127 Scotland Street, Edinburgh

If you want to pipe a command into FIND use this syntax

TYPE names.txt | FIND "Jones"

You can also redirect like this

FIND /i "Jones" < names.txt >logfile.txt

To search a folder for files that contain a given search string:

FOR %G IN (*.txt) do (find /n /i "SearchWord" "%G")

Searching from Windows Explorer

Because the built-in Windows XP File Search does not search all files you may want to add a find script to the Send To folder. AlternativelyAgent Ransack or other search utilities will search all files.

Bugs/Limitations
Although FIND can be used to scan large files, it will not detect any string that is positioned more than 1070 characters along a single line (with no carriage return) This makes it of limited use in searching binary or XML file types.

“Instead of getting married again, I'm going to find a woman I don't like and just give her a house” - Lewis Grizzard 

Related:

FC - Compare files
FINDSTR - Search for strings in files
MUNGE - Find and Replace text within file(s)
ATTRIB - Find filename (rather than searching the file contents)
Powershell: Where-Object - Filter objects passed along the pipeline.
Equivalent bash command (Linux): awk/gawk - Find and Replace text within file(s)

FINDSTR

Search for strings in files.

Syntax

      FINDSTR [options] [/F:file] [/C:string] [/G:file]

        [/D:DirList] [/A:color_attr] [/OFF[LINE]] [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).

   /A:color_attr  Display filenames in colour (2 hex digits)

   /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

   /OFF[LINE] Do not skip files with the OffLine attribute set.

   /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.

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:

Search for "granny" OR "Smith" in MyFile.txt

FINDSTR "granny Smith" MyFile.txt

Search for "granny Smith" in MyFile.txt (effectively the same as the FIND command)

FINDSTR /C:"granny Smith" MyFile.txt

Search every file in the current folder and all subfolders for the word "Smith", regardless of upper/lower case, note that /S will only search below the current directory:

FINDSTR /s /i smith *.*

Search all the text files in the current folder for the string "fiona", display the filenames in White on Green.

FINDSTR /A:2F /C:fiona *.txt

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
Find the word "computer", but not the words "supercomputer" or "computerise":

FINDSTR "\<computer\>" MyFile.txt

Find any words that begin with the letters 'comp', such as 'computerise' or 'compete'

FINDSTR "\<comp.*" MyFile.txt

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 to search the files listed in Files.txt and then store the results in the file RESULTS.txt:

FINDSTR /g:Crit.txt /f:Files.txt> Results.txt

Errorlevel

When an item is not found FINDSTR will return an errorlevel >0

Echo 12G6 |FindStr /R "[0-9]"
If %ERRORLEVEL% EQU 0 echo The string contains one or more numeric characters

Echo 12G6 |FindStr /R "[^0-9]"
If %ERRORLEVEL% EQU 0 echo The string contains one or more non numeric characters

Bugs
In early versions of FindStr /F:file a path length of more than 80 chars will be truncated.

“Twenty years from now, you will be more disappointed by the things you didn't do than by the ones you did do. So throw off the bowlines, sail away from the safe harbour. Catch the trade winds in your sails. Explore. Dream. Discover” - Mark Twain

Related:

FIND - Search for a text string in a file.
VBScript: Find and Replace 
Powershell: Where-Object - Filter objects passed along the pipeline.
Equivalent bash command (Linux): grep - Search file(s) for lines that match a given pattern

FOR /F

Loop command: against a set of files - conditionally perform a command against each item.

Syntax

        FOR /F ["options"] %%parameter IN (filenameset) DO command

     

        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 ;

      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 a text file consists of reading the file, one line of text at a time and then breaking the line up into individual items of data called '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, this default parsing behavior can be changed by applying one or more of the "options" parameters. The option(s) must be contained within "a pair of quotes"

Within a FOR loop the visibility of FOR variables is controlled via SETLOCAL EnableDelayedExpansion

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>"

n.b. 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
The default end-of-line character is a semicolon ';' when the FOR command reads a text file (or even a character string), any line that STARTS with the eol character will be ignored. In other words it is treated as a comment.
Use eol=X to change the eol character to X.
Most often you will want to turn this feature off so that every line of your data file is processed, in theory "eol=" should turn this feature off, but in practice this fails to work correctly so instead set eol to some unusual character that you don't expect to ever be in the data file e.g. "eol=€" or"eol=¬".

Examples

Extracting data from this text file:

January,Snowy,02
February,Rainy,15
March,Sunny,25

FOR /F "tokens=1,3 delims=," %%G IN (weather.txt) DO @echo %%G %%H

The tricky part is splitting up each the line into the right tokens, in this case I'm splitting on the comma character ',' this splits the line into 3 chunks of text and we pull out the first and third items with "tokens=1,3"

token1 ,

token2 ,

token3

%%G

<ignored>

%%H

January

02

February

15

March

25

%%G is declared in the FOR statement and %%H is 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,$4500,123.4,12-AUG-09") 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 "tokens=1,2* delims=," %%G IN (C:\MyDocu~1\mytex~1.txt) DO ECHO %%G

FOR /F "usebackq tokens=1,2* delims=," %%G IN ("C:\My Documents\my textfile.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 /bcommand to create the list of filenames ~ and use this variant of the FOR command syntax.

Unicode

Many of the newer commands and utilities (e.g. WMIC) output text files in unicode format, these cannot be read by the FOR command which expects ASCII.
To convert the file format use the TYPE command.

"It's completely intuitive; it just takes a few days to learn, but then it's completely intuitive" - Terry Pratchett.

Related:

FOR - Loop commands
FOR - Loop through a set of files in one folder
FOR /R - Loop through files (recurse subfolders) 
FOR /D
 - Loop through several folders
FOR /L - Loop through a range of numbers
FOR /F - Loop through the output of a command
FORFILES - Batch process multiple files
IF - Conditionally perform a command
SETLOCAL - Control the visibility of environment variables inside a loop
Powershell: ForEach-Object - Loop for each object in the pipeline
Equivalent bash command (Linux): for - Expand words, and execute commands

FOR /F

Loop command: against the results of another command.

Syntax

      FOR /F ["options"] %%parameter IN ('command_to_process') DO command

Key

   options:

      delims=xxx   The delimiter character(s)

                   (default = a space)

      skip=n       A number of lines to skip at the beginning.

                   (default = 0)

      eol=;        Character at the start of each line to indicate a comment

                   The default is a semicolon ;

      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.

The FOR command is the answer to innumerable questions where you want to take the output of some command, store it in a variable (%%G) then do something with the result.

For example the PING command returns serveral lines including one like:

Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

To select that one line of output, you can search for the text "loss" (which is always present), then use the Tokens parameter to select the number of lost packets, here this is 0 but it will vary each time you run the command.

set _ping_cmd=ping -n 5 127.0.0.1

FOR /f "tokens=4 delims=(=" %%G IN ('%_ping_cmd% ^|find "loss"') DO echo Result is [%%G]

The tricky part is always splitting up the line of interest into the right tokens, in this case I'm splitting on the characters '=' and '('
these two characters split the line into 5 chunks of text and we pull out the fourth one with "tokens=4"

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' 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>"

n.b 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.

eol
The default end-of-line character is a semicolon ';' when the FOR command reads a text file (or even a character string), any line that STARTS with the eol character will be ignored. In other words it is treated as a comment.
Use eol=X to change the eol character to X.
Most often you will want to turn this feature off so that every line of your 
data file is processed, in theory "eol=" should turn this feature off, but in practice this fails to work correctly so instead set eol to some unusual character that you don't expect to ever be in the data file e.g. "eol=€" or"eol=¬".

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:

   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.

“History never repeats itself, Mankind always does” - Voltaire

Related:

FOR
 - Summary of FOR Loop commands
FOR - Loop through a set of files in one folder
FOR /R - Loop through files (recurse subfolders) 
FOR /D
 - Loop through several folders
FOR /L - Loop through a range of numbers
FOR /F - Loop through items in a text file
SETLOCAL - Control the visibility of variables inside a FOR loop
FORFILES - Batch process multiple files
GOTO - Direct a batch program to jump to a labelled line
IF - Conditionally perform a command
Powershell: ForEach-Object - Loop for each object in the pipeline
Equivalent bash command (Linux): for - Expand words, and execute commands

FOR

Conditionally perform a command several times.

 syntax-FOR-Files

       FOR %%parameter IN (set) DO command

  

 syntax-FOR-Files-Rooted at Path  

       FOR /R [[drive:]path] %%parameter IN (set) DO command

  

 syntax-FOR-Folders

       FOR /D %%parameter IN (folder_set) DO command

  

 syntax-FOR-List of numbers  

       FOR /L %%parameter IN (start,step,end) DO command

  

 syntax-FOR-File contents  

       FOR /F ["options"] %%parameter IN (filenameset) DO command

  

       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 "tokens=1-5" %%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

Running multiple commands in a FOR loop 
Within a FOR loop, variables are expanded at the start of the loop and don't update until the entire DO section has completed.
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 update variables within each iteration of the loop we must either use EnableDelayedExpansion or else use the CALL :subroutine mechanism as shown below:

@echo off
SET count=1
FOR /f "tokens=*" %%G IN ('dir /b') DO (call :subroutine"%%G")
GOTO :eof

:subroutine
 echo %count%:%1
 set /a count+=1
 GOTO :eof

Nested FOR commands

FOR commands can be nested FOR %%G... DO (for %%U... do ...)
when nesting commands choose a different letter for each part. you can then refer to both parameters in the final DO command.

If Command Extensions are disabled, the FOR command will only support the basic syntax with no enhanced variables:
FOR %%parameter IN (set) DO command [command-parameters]

"Those who cannot remember the past are condemned to repeat it" - George Santayana 

Related:

FOR - Loop through a set of files in one folder
FOR /R - Loop through files (recurse subfolders) 
FOR /D
 - Loop through several folders
FOR /L - Loop through a range of numbers
FOR /F - Loop through items in a text file
FOR /F - Loop through the output of a command
FORFILES - Batch process multiple files
GOTO - Direct a batch program to jump to a labelled line
IF - Conditionally perform a command
Powershell: ForEach-Object - Loop for each object in the pipeline
Equivalent bash command (Linux): for var in [list]; do - Expand list, and execute commands

FORFILES.exe (Resource Kit) Select a file (or set of files) and execute a command on each file. Batch processing.

Syntax

      FORFILES [/p Path] [/m Mask] [/s] [/c Command] [/d [+ | -] {dd/MM/yyyy | dd}]  



Key

   /p Path      The Path to search  (default=current folder)



   /s           Recurse into sub-folders



   /C command   The command to execute for each file.

                Wrap the command string in double quotes.

                Default = "cmd /c echo @file"



                The Command variables listed below can also be used in the

                command string.



   /D date      Select files with a last modified date greater than or

                equal to (+), or less than or equal to (-),

                the specified date using the "dd/MM/yyyy" format;



   /D + dd      Select files with a last modified date greater than or

                equal to the current date plus "dd" days. (in the future)



   /D - dd      Select files with a last modified date less than or

                equal to the current date minus "dd" days. (in the past)



                A valid "dd" number of days can be any number in

                the range of 0 to 32768.   (89 years)

                "+" is taken as default sign if not specified.



   Command Variables:

      @file    The name of the file.

      @fname   The file name without extension.               

      @ext     Only the extension of the file.                 

      @path    Full path of the file.

      @relpath Relative path of the file.         

      @isdir   Returns "TRUE" if a file type is a directory,

               and "FALSE" for files.

      @fsize   Size of the file in bytes.

      @fdate   Last modified date of the file.

      @ftime   Last modified time of the file.

1 comment: