Complete List of MS- DOS-Command MS-DOS HELP and COMMAND
Here you will find all LIST MS- DOS command thus ...Helping you with DOS and explaining all DOS commands and examples on how to use them as well as other computer information.There are nearly many MS-DOS commands available in MS-DOS. See a complete list of MS-DOS commands, commonly referred to as DOS commands below.All The MS-DOS commands are in Alphabetical order which will help you to understand easily.
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.
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.
The hostname command displays the host name of the Windows XP computer currently logged into.
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.
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.
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.
The nbtstat MS-DOS utility that displays protocol statistics and current TCP/IP connections using NBT.
The net command is available in MS-DOS / Windows and is used to set, view and determine network settings.
The netstat command is used to display the TCP/IP network protocol statistics and information.
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.
The route MS-DOS utility enables computers to view and modify the computer's route table.
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.
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.
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...
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.
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.
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 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 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 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.
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.
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.
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.
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.
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.
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.
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.
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...
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
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 n lines (common portion of each file.)
COMP will normally finish with a Compare more files (Y/N) prompt
to suppress this: ECHO n|COMP <options>
"Shall I compare thee to a summer's day" - William Shakespeare
Related:
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/eDirectory, Oracle Internet Directory)
Passwords
For security reasons neither of these tools will export passwords. When you import an account it is given a null password, if the domain has a password length policy, then the account will be disabled (You can re-enable accounts in bulk with a script)
Compatibility
CSVDE and LDIFDE are supplied with Windows 2000/2003 Server but can also be run on Win2000 Professional and XP Professional (i.e run remotely against the Active Directory Server.)
Examples
Export the whole domain
CSVDE -f MyDomain.csv
Export all users with a particular surname:
CSVDE -f MyUsers.csv -r (and(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
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
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 n lines (common portion of each file.)
COMP will normally finish with a Compare more files (Y/N) prompt
to suppress this: ECHO n|COMP <options>
"Shall I compare thee to a summer's day" - William Shakespeare
Related:
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/eDirectory, Oracle Internet Directory)
Passwords
For security reasons neither of these tools will export passwords. When you import an account it is given a null password, if the domain has a password length policy, then the account will be disabled (You can re-enable accounts in bulk with a script)
Compatibility
CSVDE and LDIFDE are supplied with Windows 2000/2003 Server but can also be run on Win2000 Professional and XP Professional (i.e run remotely against the Active Directory Server.)
Examples
Export the whole domain
CSVDE -f MyDomain.csv
Export all users with a particular surname:
CSVDE -f MyUsers.csv -r (and(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
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...
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.
To include special characters in the command line, use the hex code for the character in 0xHH format (ex. 0x09 is theTAB character, 0x22 is the double quote " character.) so "C:\Program Files\" becomes ^0x22C:\Program^ Files\^0x22
Internal CMD.exe commands must be preceded with "cmd /c".
If ForFiles finds one or more matches if will return %errorlevel% =0
If ForFiles finds no matches if will return %errorlevel% =1 and will print "ERROR: No files found with the specified search criteria."
The old NT4 version of ForFiles used unix style -parameters, and could only match dates newer than a specified date using the following command variables names: (which must be upper case) @FILE, @FNAME_WITHOUT_EXT, @EXT, @PATH, @RELPATH, @ISDIR, @FSIZE, @FDATE, @FTIME
The Windows 2000 version of ForFiles also used unix-style parameters but is otherwise the same as current versions.
Last modified dates set in the future are not common but can happen when your computer clock date/time is changed e.g. due to daylight savings time.
Examples:
Delete the testfile if it is is 5 days old or older:
C:\> forfiles /m testfile.txt /c "cmd /c Del testfile.txt " /d -5
Find .xls file that were last modified 30 days ago or older
C:\> FORFILES /M *.xls /C "cmd /c echo @path was changed 30 days ago" /D -30
List the size of all .doc files:
C:\> FORFILES /S /M *.doc /C "cmd /c echo @fsize"
An alternative method of dealing with files older or newer than a specified date is to use ROBOCOPY
Rule #1: Don't sweat the small stuff.
Rule #2: It's all small stuff - Dr Robert S Eliot, University of Nebraska cardiologist
Related:
Syntax - Delete files older than N days
FOR - Conditionally perform a command several times.
Powershell: ForEach-Object - Loop for each object in the pipeline
Equivalent bash command (Linux): find - Search for files that meet a desired criteria
FORMAT.com
Format a disk for use with Windows.
Syntax
FORMAT drive: [/FS:file-system] [/V:label] [/Q] [size] [/C]
Key
/FS:file-system The file system (FAT or NTFS).
The NTFS file system does not function on floppy disks.
/V:label The volume label.
/Q Quick format.
/C Compression - files added to the new disk will be compressed.
[size] may be defined either with /F:size or /A:size
/F:size size is the size of the floppy disk (720, 1.2, 1.44, 2.88, or 20.8).
/A:size Allocation unit size.
Default settings (via /F) are strongly recommended for general use.
NTFS supports 512, 1024, 2048, 4096, 8192, 16K, 32K, 64K.
FAT supports 8192, 16K, 32K, 64K, 128K, 256K.
NTFS compression is not supported for allocation units above 4096.
Example
@echo off
Echo Warning this will reformat the entire D: disk!
PAUSE
format D: /FS:NTFS /x
"The disks had a recording density of 1,100 bits per inch, and could move data out of the drive at 77 kilobytes per second" - Early hard drive specs.
Related:
Q314878 - Choosing Cluster Size when formatting a hard drive
KB955704 - WinXP support for the exFAT file system format
Q252448 - How to create an NT Bootdisk
Floppy Disks - History from Wikipedia
Equivalent bash command (Linux): mkfs, in FreeBSD & OSX: newfs, fsck_exfat
FSUTIL.exe
File and Volume specific commands, Hardlink management, Quota management, USN, Sparse file, Object ID and Reparse point management
Create a hardlink
FSUTIL hardlink create new_filename existing_filename
Eg : fsutil hardlink create c:\foo.txt c:\bar.txt
Create a new file of a specific size
FSUTIL file createnew filename
Eg : fsutil file createnew C:\testfile.txt 1000
Set the short NTFS filename for a file
FSUTIL file setshortname filename shortname
Eg : fsutil file setshortname C:\testfile.txt tes1.txt
Set the valid data length for a file
FSUTIL file setvaliddata filename datalength
Eg : fsutil file setvaliddata C:\testfile.txt 4096
Set the zero data for a file
FSUTIL file setzerodata offset=val length=val filename
offset : File offset, the start of the range to set to zeroes
length : Byte length of the zeroed range
Eg : fsutil file setzerodata offset=100 length=150 C:\Temp\sample.txt
List all drives (including mapped and Subst drives)
FSUTIL fsinfo drives
Query drive type for a drive
FSUTIL fsinfo drivetype volume pathname
Eg : fsutil fsinfo drivetype C:
ListLocalDrives.cmd - List all drives on the local computer
Query volume information
FSUTIL fsinfo volumeinfo volume pathname
Eg : fsutil fsinfo volumeinfo C:\
Query NTFS specific volume information
FSUTIL fsinfo ntfsinfo volume pathname
Eg : fsutil fsinfo ntfsinfo C:
Query file system statistics
FSUTIL fsinfo statistics volume pathname
Eg : fsutil fsinfo statistics C:
QUOTA Management
FSUTIL quota {query|disable|track|enforce } C:
FSUTIL quota violations
FSUTIL quota modify volume_pathname threshold limit user
Eg : fsutil quota modify c: 3000 5000 domain\user
Find a file by user name (if Disk Quotas are enabled)
FSUTIL file findbysid user directory
Eg : fsutil file findbysid scottb C:\users
File system options:
FSUTIL behavior query option
FSUTIL behavior set option
Where option is one of:
allowextchar {0|1} Allow extended characters in filenames
disablelastaccess {0|1} Don't generate last-access times
quotanotify NumSeconds Log quota violations, default=3600 seconds
mftzone {1|2|3|4} Set MFT Zone, multiple of 200MB
Bugcheckoncorrupt {0|1} Enable bugcheck #
disablecompression {0|1} Disable compression #
disableencryption {0|1} Disable encryption #
encryppagingfile {0|1}
memoryusage {1|2} Paged-pool memory cache, 1=default #
symlinkevaluation L2L:{0|1} Local to local symbolic links #
symlinkevaluation L2R:{0|1} Local to remote symbolic links #
symlinkevaluation R2R:{0|1} Remote to local symbolic links #
symlinkevaluation R2L:{0|1} Remote to remote symbolic links #
DisableDeleteNotify {0|1} Delete notifications for all volumes#
disable8dot3 [volumePath] sfnNum
sfnNum is between 0 and 3
0 = Create short file names (default).
1 = Don't create short file names.
2 = Set 8.3 names on a per volume basis.
3 = Disable 8.3 names on all volumes except the system volume.
1 = enable option
0 = Disable option
# = Windows7/2008 option
Eg : FSUTIL behavior query disable8dot3
FSUTIL behavior set disablelastaccess 1
FSUTIL dirty query volume pathname
FSUTIL dirty set volume pathname
Marking a disk as dirty will prompt a Chkdsk at next boot
Eg : FSUTIL dirty query C:
Query a reparse point
FSUTIL reparsepoint query filename
Eg : fsutil reparsepoint query C:\Server
Delete a reparse point
FSUTIL reparsepoint delete filename
Eg : fsutil reparsepoint delete C:\Server
Edit an object identifier
FSUTIL objectid {query | set | delete | create}
Set sparse file properties
FSUTIL sparse queryflag filename
FSUTIL sparse setflag filename
FSUTIL sparse queryrange filename
FSUTIL sparse setrange filename
Eg : fsutil sparse queryflag "C:\My Test.txt"
Query the allocated ranges for a file
FSUTIL file queryallocranges offset=val length=val filename
offset : File Offset, the start of the range to query
length : Size, in bytes, of the range
Eg : fsutil file queryallocranges offset=1024 length=64 C:\Temp\sample.txt
To run FSUTIL, you must be logged on as an administrator or a member of the Administrators group.
Sparse files provide a method of saving disk space for files that contain meaningful data as well as large sections of data composed of zeros. If an NTFS file is marked as sparse, then disk clusters are allocated only for the data explicitly specified by the application.
e.g. The Indexing Service, stores it's catalogs as sparse files.
With 8.3 filennames disabled you'll notice a performance improvement only with a large number of files (over 300,000) in relatively few folders where a lot of the filenames start with similar names. Not having 8.3 filenames available will prevent the use of old applications such as Word 2.0 and Excel 4.0
If you have a lot of small files, you may need a larger Master File Table to avoid MFT fragmentation:
FSUTIL behavior set mftzone 2 will reserve 25 % of the volume for the MFT.
1 = 12.5 %(default)
2 = 25%
3 = 37.5%
4 = 50%
This won't affect existing disk partitions, after changing the mftzone size, reboot the machine and create a new partition.
In Windows7 and Server 2008 the mft zone is allocated in blocks of 200MB:
1 = 200 MB (default)
2 = 400 MB
3 = 600 MB
4 = 800 MB
Increasing the MFT zone does not decrease the disk space available for data files.
The last access time attribute of NTFS can slow performance, if you disable it, the time set will simply be the Creation Time.
FSUTIL behavior set disablelastaccess 1
Bugs
FSUTIL outputs a NULL character (not a space) after every drive specifier, this may cause difficulty when piping the output of fsutil into other commands (particularly FOR), see this forum thread for more detail.
Some features in fsutil are reported to not work correctly under FAT or FAT32 volumes e.g. FSUTIL dirty query.
"You can tune a file system, but you can't tune a fish" - Sun man page for tunefs
Related:
CACLS - Change file permissions
CHKNTFS - Check the NTFS file system
DevCon - Device Manager Command Line Utility
DIRUSE - Display disk usage
FDISK - Disk Format and partition
SHORTCUT - Create a windows shortcut (.LNK file)
WINMSD - Windows NT Diagnostics
Q174619 - MFT How NTFS reserves space for its Master File Table
Q961095 - MFT Master File Table zone reservation in Vista and Server 2008
Q286164 - Hard Links and System Restore
Q249734 - Backup Software, RSM and file last access date
Equivalent bash command (Linux): quotactl - Set disk quotas
FTP File Transfer Protocol
Syntax
FTP [-options] [-s:filename] [-w:buffer] [host]
key
-s:filename Run a text file containing FTP commands.
host Host name or IP address of the remote host.
-g Disable filename wildcards.
-n No auto-login.
-i No interactive prompts during ftp.
-v Hide remote server responses.
-w:buffer Set buffer size to buffer
(default=4096)
-d Debug
-a Use any local interface when binding data connection.
Commands to run at the FTP: prompt
append local-file [remote-file]
Append a local file to a file on the remote computer.
ascii Set the file transfer type to ASCII, the default.
In ASCII text mode, character-set and end-of-line
characters are converted as necessary.
bell Toggle a bell to ring after each command.
By default, the bell is off.
binary Set the file transfer type to binary.
Use `Binary' for transferring executable program
files or binary data files e.g. Oracle
bye End the FTP session and exit ftp
cd Change the working directory on the remote host.
close End the FTP session and return to the cmd prompt.
debug Toggle debugging. When debug is on, FTP will display
every command.
delete remote-file
Delete file on remote host.
dir [remote-directory] [local-file]
List a remote directory's files and subdirectories.
(or save the listing to local-file)
disconnect Disconnect from the remote host, retaining the ftp prompt.
get remote-file [local-file]
Copy a remote file to the local PC.
glob Toggle the use of wildcard characters in local pathnames.
By default, globbing is on.
hash Toggle printing a hash (#) for each 2K data block transferred.
By default, hash mark printing is off.
help [command]
Display help for ftp command.
lcd [directory]
Change the working directory on the local PC.
By default, the working directory is the directory in which ftp was started.
literal argument [ ...]
Send arguments, as-is, to the remote FTP host.
ls [remote-directory] [local-file]
List a remote directory's files and folders.
(short format)
mdelete remote-files [ ...]
Delete files on remote host.
mdir remote-files [ ...] local-file
Display a list of a remote directory's files and subdirectories.
(or save the listing to local-file)
Mdir allows you to specify multiple files.
mget remote-files [ ...]
Copy multiple remote files to the local PC.
mkdir directory
Create a directory on the remote host.
mls remote-files [ ...] local-file
List a remote directory's files and folders.
(short format)
mput local-files [ ...]
Copy multiple local files to the remote host.
open computer [port]
Connects to the specified FTP server.
prompt Toggle prompting. Ftp prompts during multiple file transfers to
allow you to selectively retrieve or store files;
mget and mput transfer all files if prompting is turned off.
By default, prompting is on.
put local-file [remote-file]
Copy a local file to the remote host.
pwd Print Working Directory
(current directory on the remote host)
quit End the FTP session with the remote host and exit ftp.
quote argument [ ...]
Send arguments, as-is, to the remote FTP host.
recv remote-file [local-file]
Copy a remote file to the local PC.
remotehelp [command]
Display help for remote commands.
rename filename newfilename
Rename remote files.
rmdir directory
Delete a remote directory.
send local-file [remote-file]
Copy a local file to the remote host.
status Display the current status of FTP connections and toggles.
trace Toggles packet tracing; trace displays the route of each packet
type [type-name]
Set or display the file transfer type:
`binary' or `ASCII' (the default)
If type-name is not specified, the current type is displayed.
ASCII should be used when transferring text files.
In ASCII text mode, character-set and end-of-line
characters are converted as necessary.
Use `Binary' for transferring executable files.
user user-name [password] [account]
Specifes a user to the remote host.
verbose Toggle verbose mode. By default, verbose is on.
! command Run command on the local PC.
? [command] Display help for ftp command.
Examples
an example FTP Script to retrieve files in binary and then ascii mode:
::GetFiles.ftp
[User_id]
[ftp_password]
binary
get /usr/file1.exe
get file2.html
mget *.jpeg
ascii
mget *.txt
quit
To run the above script:
FTP -s:GetFiles.ftp [hostname]
This will connect as the user:User_id with password:ftp_password
An FTP Script to publish files in binary mode:
::PutFiles.ftp
[User_id]
[ftp_password]
binary
mput *.html
cd images
mput *.gif
quit
To run the above script:
FTP -s:PutFiles.ftp [hostname]
This will connect as the user:User_id with password:ftp_password
Using the Windows GUI for FTP
Windows Explorer (not Internet Explorer) also has a built in FTP client.
Type in the address bar:
ftp://username@ftpserver.address.com
you will be prompted for the password.
You can also do
ftp://username:password@ftpserver.address.com
This is not recommended as anyone can read the password.
Secure FTP
Standard FTP does not encrypt passwords - they are sent across the network in plain text. A more secure method is to use SecureFTP (SFTP) or SecureCopy (SCP) Freeware clients are available e.g. WinSCP
"Only wimps use tape backup: _real_ men just upload their important stuff on ftp, and let the rest of the world mirror it" - Linus Torvalds
Related commands:
COPY - Copy one or more files to another location
XCOPY - Copy files and folders
REM - Add a comment (includes commenting FTP scripts)
Q271078 - Microsoft FTP does not support passive mode (error 425)
RAW FTP - Full list of RAW FTP commands
Equivalent bash command (Linux): FTP - File Transfer Protocol
FTYPE Display or change the link between a FileType and an executable program
Syntax
FTYPE fileType=executable_path
FTYPE
FTYPE fileType
FTYPE fileType=
Key
fileType : The type of file
executable_path : The executable program including any command line parameters
More than one file extension may be associated with the same File Type.
e.g. both the extension .JPG and the extension .JPEG may be associated with the File Type "jpegfile"
File Types can be displayed in the Windows Explorer GUI under Options, File Types however the naming used is not consistent e.g. the File Type "txtfile" is displayed in the GUI as "Text Document"and "jpegfile" is displayed as "image/jpeg"
Several FileTypes can be linked to the same executable application.
FTYPE filetype will display the current executable program for that file type e.g. FTYPE jpegfile.
FTYPE without any parameters will display all FileTypes and the executable program for each.
Defining command line parameters
It is almost always necessary to supply command line parameters so that when a document is opened not only is the relevant application loaded into memory but the document itself also loaded into the application. To make this happen the filename of the document must be passed back to the application.
Command line parameters are exactly like batch file parameters, %0 is the executable program and %1 will reference the document filename
so a simple command line might be:
MyApplication.exe "%1"
If any further parameters are required by the application they can be passed as %2, %3. To pass ALL parameters to an application use %*. To pass all the remaining parameters starting with the nth parameter, use %~n where n is between 2 and 9.
The FileType should always be created before making a File Association
For example:
FTYPE htmlfile="C:\PROGRA~1\Plus!\MICROS~1\iexplore.exe" -nohome
ASSOC .html=htmlfile
FTYPE pagemill.html=C:\PROGRA~1\Adobe\PAGEMI~1.0\PageMill.exe "%1"
ASSOC .html=pagemill.html
FTYPE rtffile="C:\Program Files\Windows NT\Accessories\WORDPAD.EXE" "%1"
ASSOC .rtf=rtffile
FTYPE word.rtf.8="C:\Program Files\Microsoft Office\Office\winword.exe" /n
ASSOC .rtf=word.rtf.8
Switching a File Association between multiple applications
If you have multiple applications that use the same file extension, the ASSOC command can be used to switch the file extension between the different FileTypes.
Deleting a FileType
Specify executable_path=nothing and the FTYPE command will delete the executable_path for that FileType.
For example:
FTYPE htmlfile=
Backup your FileTypes
FTYPE >backup_types.txt
ASSOC >backup_ext.txt
Restore your FileTypes from a Backup
FOR /F "tokens=* delims=" %G IN (backup_types.txt) DO FTYPE %G
FOR /F "tokens=* delims=" %G IN (backup_ext.txt) DO ASSOC %G
This will recreate the CLASS id's in the registry at HKey_Classes_Root\.<file extension>
If you put the commands above in a batch file change the %G to be %%G
Using File associations at the command line
If you have a file association between .DOC and Word for Windows then at a command prompt you can open a document with any of the following commands:
Start "My Document.doc"
"Monthly Report.doc"
JULY.DOC
note that the file extension must be supplied for this to work
"True to type - Of a plant, or group of plants, which matches the accepted description of the cultivar to which it is assumed to belong"
Related Commands:
ASSOC - Change file extension associations
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
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.
To include special characters in the command line, use the hex code for the character in 0xHH format (ex. 0x09 is theTAB character, 0x22 is the double quote " character.) so "C:\Program Files\" becomes ^0x22C:\Program^ Files\^0x22
Internal CMD.exe commands must be preceded with "cmd /c".
If ForFiles finds one or more matches if will return %errorlevel% =0
If ForFiles finds no matches if will return %errorlevel% =1 and will print "ERROR: No files found with the specified search criteria."
The old NT4 version of ForFiles used unix style -parameters, and could only match dates newer than a specified date using the following command variables names: (which must be upper case) @FILE, @FNAME_WITHOUT_EXT, @EXT, @PATH, @RELPATH, @ISDIR, @FSIZE, @FDATE, @FTIME
The Windows 2000 version of ForFiles also used unix-style parameters but is otherwise the same as current versions.
Last modified dates set in the future are not common but can happen when your computer clock date/time is changed e.g. due to daylight savings time.
Examples:
Delete the testfile if it is is 5 days old or older:
C:\> forfiles /m testfile.txt /c "cmd /c Del testfile.txt " /d -5
Find .xls file that were last modified 30 days ago or older
C:\> FORFILES /M *.xls /C "cmd /c echo @path was changed 30 days ago" /D -30
List the size of all .doc files:
C:\> FORFILES /S /M *.doc /C "cmd /c echo @fsize"
An alternative method of dealing with files older or newer than a specified date is to use ROBOCOPY
Rule #1: Don't sweat the small stuff.
Rule #2: It's all small stuff - Dr Robert S Eliot, University of Nebraska cardiologist
Related:
Syntax - Delete files older than N days
FOR - Conditionally perform a command several times.
Powershell: ForEach-Object - Loop for each object in the pipeline
Equivalent bash command (Linux): find - Search for files that meet a desired criteria
FORMAT.com
Format a disk for use with Windows.
Syntax
FORMAT drive: [/FS:file-system] [/V:label] [/Q] [size] [/C]
Key
/FS:file-system The file system (FAT or NTFS).
The NTFS file system does not function on floppy disks.
/V:label The volume label.
/Q Quick format.
/C Compression - files added to the new disk will be compressed.
[size] may be defined either with /F:size or /A:size
/F:size size is the size of the floppy disk (720, 1.2, 1.44, 2.88, or 20.8).
/A:size Allocation unit size.
Default settings (via /F) are strongly recommended for general use.
NTFS supports 512, 1024, 2048, 4096, 8192, 16K, 32K, 64K.
FAT supports 8192, 16K, 32K, 64K, 128K, 256K.
NTFS compression is not supported for allocation units above 4096.
Example
@echo off
Echo Warning this will reformat the entire D: disk!
PAUSE
format D: /FS:NTFS /x
"The disks had a recording density of 1,100 bits per inch, and could move data out of the drive at 77 kilobytes per second" - Early hard drive specs.
Related:
Q314878 - Choosing Cluster Size when formatting a hard drive
KB955704 - WinXP support for the exFAT file system format
Q252448 - How to create an NT Bootdisk
Floppy Disks - History from Wikipedia
Equivalent bash command (Linux): mkfs, in FreeBSD & OSX: newfs, fsck_exfat
FSUTIL.exe
File and Volume specific commands, Hardlink management, Quota management, USN, Sparse file, Object ID and Reparse point management
Create a hardlink
FSUTIL hardlink create new_filename existing_filename
Eg : fsutil hardlink create c:\foo.txt c:\bar.txt
Create a new file of a specific size
FSUTIL file createnew filename
Eg : fsutil file createnew C:\testfile.txt 1000
Set the short NTFS filename for a file
FSUTIL file setshortname filename shortname
Eg : fsutil file setshortname C:\testfile.txt tes1.txt
Set the valid data length for a file
FSUTIL file setvaliddata filename datalength
Eg : fsutil file setvaliddata C:\testfile.txt 4096
Set the zero data for a file
FSUTIL file setzerodata offset=val length=val filename
offset : File offset, the start of the range to set to zeroes
length : Byte length of the zeroed range
Eg : fsutil file setzerodata offset=100 length=150 C:\Temp\sample.txt
List all drives (including mapped and Subst drives)
FSUTIL fsinfo drives
Query drive type for a drive
FSUTIL fsinfo drivetype volume pathname
Eg : fsutil fsinfo drivetype C:
ListLocalDrives.cmd - List all drives on the local computer
Query volume information
FSUTIL fsinfo volumeinfo volume pathname
Eg : fsutil fsinfo volumeinfo C:\
Query NTFS specific volume information
FSUTIL fsinfo ntfsinfo volume pathname
Eg : fsutil fsinfo ntfsinfo C:
Query file system statistics
FSUTIL fsinfo statistics volume pathname
Eg : fsutil fsinfo statistics C:
QUOTA Management
FSUTIL quota {query|disable|track|enforce } C:
FSUTIL quota violations
FSUTIL quota modify volume_pathname threshold limit user
Eg : fsutil quota modify c: 3000 5000 domain\user
Find a file by user name (if Disk Quotas are enabled)
FSUTIL file findbysid user directory
Eg : fsutil file findbysid scottb C:\users
File system options:
FSUTIL behavior query option
FSUTIL behavior set option
Where option is one of:
allowextchar {0|1} Allow extended characters in filenames
disablelastaccess {0|1} Don't generate last-access times
quotanotify NumSeconds Log quota violations, default=3600 seconds
mftzone {1|2|3|4} Set MFT Zone, multiple of 200MB
Bugcheckoncorrupt {0|1} Enable bugcheck #
disablecompression {0|1} Disable compression #
disableencryption {0|1} Disable encryption #
encryppagingfile {0|1}
memoryusage {1|2} Paged-pool memory cache, 1=default #
symlinkevaluation L2L:{0|1} Local to local symbolic links #
symlinkevaluation L2R:{0|1} Local to remote symbolic links #
symlinkevaluation R2R:{0|1} Remote to local symbolic links #
symlinkevaluation R2L:{0|1} Remote to remote symbolic links #
DisableDeleteNotify {0|1} Delete notifications for all volumes#
disable8dot3 [volumePath] sfnNum
sfnNum is between 0 and 3
0 = Create short file names (default).
1 = Don't create short file names.
2 = Set 8.3 names on a per volume basis.
3 = Disable 8.3 names on all volumes except the system volume.
1 = enable option
0 = Disable option
# = Windows7/2008 option
Eg : FSUTIL behavior query disable8dot3
FSUTIL behavior set disablelastaccess 1
FSUTIL dirty query volume pathname
FSUTIL dirty set volume pathname
Marking a disk as dirty will prompt a Chkdsk at next boot
Eg : FSUTIL dirty query C:
Query a reparse point
FSUTIL reparsepoint query filename
Eg : fsutil reparsepoint query C:\Server
Delete a reparse point
FSUTIL reparsepoint delete filename
Eg : fsutil reparsepoint delete C:\Server
Edit an object identifier
FSUTIL objectid {query | set | delete | create}
Set sparse file properties
FSUTIL sparse queryflag filename
FSUTIL sparse setflag filename
FSUTIL sparse queryrange filename
FSUTIL sparse setrange filename
Eg : fsutil sparse queryflag "C:\My Test.txt"
Query the allocated ranges for a file
FSUTIL file queryallocranges offset=val length=val filename
offset : File Offset, the start of the range to query
length : Size, in bytes, of the range
Eg : fsutil file queryallocranges offset=1024 length=64 C:\Temp\sample.txt
To run FSUTIL, you must be logged on as an administrator or a member of the Administrators group.
Sparse files provide a method of saving disk space for files that contain meaningful data as well as large sections of data composed of zeros. If an NTFS file is marked as sparse, then disk clusters are allocated only for the data explicitly specified by the application.
e.g. The Indexing Service, stores it's catalogs as sparse files.
With 8.3 filennames disabled you'll notice a performance improvement only with a large number of files (over 300,000) in relatively few folders where a lot of the filenames start with similar names. Not having 8.3 filenames available will prevent the use of old applications such as Word 2.0 and Excel 4.0
If you have a lot of small files, you may need a larger Master File Table to avoid MFT fragmentation:
FSUTIL behavior set mftzone 2 will reserve 25 % of the volume for the MFT.
1 = 12.5 %(default)
2 = 25%
3 = 37.5%
4 = 50%
This won't affect existing disk partitions, after changing the mftzone size, reboot the machine and create a new partition.
In Windows7 and Server 2008 the mft zone is allocated in blocks of 200MB:
1 = 200 MB (default)
2 = 400 MB
3 = 600 MB
4 = 800 MB
Increasing the MFT zone does not decrease the disk space available for data files.
The last access time attribute of NTFS can slow performance, if you disable it, the time set will simply be the Creation Time.
FSUTIL behavior set disablelastaccess 1
Bugs
FSUTIL outputs a NULL character (not a space) after every drive specifier, this may cause difficulty when piping the output of fsutil into other commands (particularly FOR), see this forum thread for more detail.
Some features in fsutil are reported to not work correctly under FAT or FAT32 volumes e.g. FSUTIL dirty query.
"You can tune a file system, but you can't tune a fish" - Sun man page for tunefs
Related:
CACLS - Change file permissions
CHKNTFS - Check the NTFS file system
DevCon - Device Manager Command Line Utility
DIRUSE - Display disk usage
FDISK - Disk Format and partition
SHORTCUT - Create a windows shortcut (.LNK file)
WINMSD - Windows NT Diagnostics
Q174619 - MFT How NTFS reserves space for its Master File Table
Q961095 - MFT Master File Table zone reservation in Vista and Server 2008
Q286164 - Hard Links and System Restore
Q249734 - Backup Software, RSM and file last access date
Equivalent bash command (Linux): quotactl - Set disk quotas
FTP File Transfer Protocol
Syntax
FTP [-options] [-s:filename] [-w:buffer] [host]
key
-s:filename Run a text file containing FTP commands.
host Host name or IP address of the remote host.
-g Disable filename wildcards.
-n No auto-login.
-i No interactive prompts during ftp.
-v Hide remote server responses.
-w:buffer Set buffer size to buffer
(default=4096)
-d Debug
-a Use any local interface when binding data connection.
Commands to run at the FTP: prompt
append local-file [remote-file]
Append a local file to a file on the remote computer.
ascii Set the file transfer type to ASCII, the default.
In ASCII text mode, character-set and end-of-line
characters are converted as necessary.
bell Toggle a bell to ring after each command.
By default, the bell is off.
binary Set the file transfer type to binary.
Use `Binary' for transferring executable program
files or binary data files e.g. Oracle
bye End the FTP session and exit ftp
cd Change the working directory on the remote host.
close End the FTP session and return to the cmd prompt.
debug Toggle debugging. When debug is on, FTP will display
every command.
delete remote-file
Delete file on remote host.
dir [remote-directory] [local-file]
List a remote directory's files and subdirectories.
(or save the listing to local-file)
disconnect Disconnect from the remote host, retaining the ftp prompt.
get remote-file [local-file]
Copy a remote file to the local PC.
glob Toggle the use of wildcard characters in local pathnames.
By default, globbing is on.
hash Toggle printing a hash (#) for each 2K data block transferred.
By default, hash mark printing is off.
help [command]
Display help for ftp command.
lcd [directory]
Change the working directory on the local PC.
By default, the working directory is the directory in which ftp was started.
literal argument [ ...]
Send arguments, as-is, to the remote FTP host.
ls [remote-directory] [local-file]
List a remote directory's files and folders.
(short format)
mdelete remote-files [ ...]
Delete files on remote host.
mdir remote-files [ ...] local-file
Display a list of a remote directory's files and subdirectories.
(or save the listing to local-file)
Mdir allows you to specify multiple files.
mget remote-files [ ...]
Copy multiple remote files to the local PC.
mkdir directory
Create a directory on the remote host.
mls remote-files [ ...] local-file
List a remote directory's files and folders.
(short format)
mput local-files [ ...]
Copy multiple local files to the remote host.
open computer [port]
Connects to the specified FTP server.
prompt Toggle prompting. Ftp prompts during multiple file transfers to
allow you to selectively retrieve or store files;
mget and mput transfer all files if prompting is turned off.
By default, prompting is on.
put local-file [remote-file]
Copy a local file to the remote host.
pwd Print Working Directory
(current directory on the remote host)
quit End the FTP session with the remote host and exit ftp.
quote argument [ ...]
Send arguments, as-is, to the remote FTP host.
recv remote-file [local-file]
Copy a remote file to the local PC.
remotehelp [command]
Display help for remote commands.
rename filename newfilename
Rename remote files.
rmdir directory
Delete a remote directory.
send local-file [remote-file]
Copy a local file to the remote host.
status Display the current status of FTP connections and toggles.
trace Toggles packet tracing; trace displays the route of each packet
type [type-name]
Set or display the file transfer type:
`binary' or `ASCII' (the default)
If type-name is not specified, the current type is displayed.
ASCII should be used when transferring text files.
In ASCII text mode, character-set and end-of-line
characters are converted as necessary.
Use `Binary' for transferring executable files.
user user-name [password] [account]
Specifes a user to the remote host.
verbose Toggle verbose mode. By default, verbose is on.
! command Run command on the local PC.
? [command] Display help for ftp command.
Examples
an example FTP Script to retrieve files in binary and then ascii mode:
::GetFiles.ftp
[User_id]
[ftp_password]
binary
get /usr/file1.exe
get file2.html
mget *.jpeg
ascii
mget *.txt
quit
To run the above script:
FTP -s:GetFiles.ftp [hostname]
This will connect as the user:User_id with password:ftp_password
An FTP Script to publish files in binary mode:
::PutFiles.ftp
[User_id]
[ftp_password]
binary
mput *.html
cd images
mput *.gif
quit
To run the above script:
FTP -s:PutFiles.ftp [hostname]
This will connect as the user:User_id with password:ftp_password
Using the Windows GUI for FTP
Windows Explorer (not Internet Explorer) also has a built in FTP client.
Type in the address bar:
ftp://username@ftpserver.address.com
you will be prompted for the password.
You can also do
ftp://username:password@ftpserver.address.com
This is not recommended as anyone can read the password.
Secure FTP
Standard FTP does not encrypt passwords - they are sent across the network in plain text. A more secure method is to use SecureFTP (SFTP) or SecureCopy (SCP) Freeware clients are available e.g. WinSCP
"Only wimps use tape backup: _real_ men just upload their important stuff on ftp, and let the rest of the world mirror it" - Linus Torvalds
Related commands:
COPY - Copy one or more files to another location
XCOPY - Copy files and folders
REM - Add a comment (includes commenting FTP scripts)
Q271078 - Microsoft FTP does not support passive mode (error 425)
RAW FTP - Full list of RAW FTP commands
Equivalent bash command (Linux): FTP - File Transfer Protocol
FTYPE Display or change the link between a FileType and an executable program
Syntax
FTYPE fileType=executable_path
FTYPE
FTYPE fileType
FTYPE fileType=
Key
fileType : The type of file
executable_path : The executable program including any command line parameters
More than one file extension may be associated with the same File Type.
e.g. both the extension .JPG and the extension .JPEG may be associated with the File Type "jpegfile"
File Types can be displayed in the Windows Explorer GUI under Options, File Types however the naming used is not consistent e.g. the File Type "txtfile" is displayed in the GUI as "Text Document"and "jpegfile" is displayed as "image/jpeg"
Several FileTypes can be linked to the same executable application.
FTYPE filetype will display the current executable program for that file type e.g. FTYPE jpegfile.
FTYPE without any parameters will display all FileTypes and the executable program for each.
Defining command line parameters
It is almost always necessary to supply command line parameters so that when a document is opened not only is the relevant application loaded into memory but the document itself also loaded into the application. To make this happen the filename of the document must be passed back to the application.
Command line parameters are exactly like batch file parameters, %0 is the executable program and %1 will reference the document filename
so a simple command line might be:
MyApplication.exe "%1"
If any further parameters are required by the application they can be passed as %2, %3. To pass ALL parameters to an application use %*. To pass all the remaining parameters starting with the nth parameter, use %~n where n is between 2 and 9.
The FileType should always be created before making a File Association
For example:
FTYPE htmlfile="C:\PROGRA~1\Plus!\MICROS~1\iexplore.exe" -nohome
ASSOC .html=htmlfile
FTYPE pagemill.html=C:\PROGRA~1\Adobe\PAGEMI~1.0\PageMill.exe "%1"
ASSOC .html=pagemill.html
FTYPE rtffile="C:\Program Files\Windows NT\Accessories\WORDPAD.EXE" "%1"
ASSOC .rtf=rtffile
FTYPE word.rtf.8="C:\Program Files\Microsoft Office\Office\winword.exe" /n
ASSOC .rtf=word.rtf.8
Switching a File Association between multiple applications
If you have multiple applications that use the same file extension, the ASSOC command can be used to switch the file extension between the different FileTypes.
Deleting a FileType
Specify executable_path=nothing and the FTYPE command will delete the executable_path for that FileType.
For example:
FTYPE htmlfile=
Backup your FileTypes
FTYPE >backup_types.txt
ASSOC >backup_ext.txt
Restore your FileTypes from a Backup
FOR /F "tokens=* delims=" %G IN (backup_types.txt) DO FTYPE %G
FOR /F "tokens=* delims=" %G IN (backup_ext.txt) DO ASSOC %G
This will recreate the CLASS id's in the registry at HKey_Classes_Root\.<file extension>
If you put the commands above in a batch file change the %G to be %%G
Using File associations at the command line
If you have a file association between .DOC and Word for Windows then at a command prompt you can open a document with any of the following commands:
Start "My Document.doc"
"Monthly Report.doc"
JULY.DOC
note that the file extension must be supplied for this to work
"True to type - Of a plant, or group of plants, which matches the accepted description of the cultivar to which it is assumed to belong"
Related Commands:
ASSOC - Change file extension associations
Batch file to list the application associated with a file extension
ASSOCIAT - One step file association (Resource Kit)
GLOBAL (Resource kit) Display membership of global groups on remote servers or remote domains.
Syntax
GLOBAL group_name domain_name | \\server
Key
group_name The global group.
domain_name A network domain.
\\server A network server.
Examples:
GLOBAL "Domain Users" Scotland
Displays the members of the group "Domain Users" in the Scotland domain.
GLOBAL PrintUsers \\9G_Server
Displays the members of the group PrintUsers on server 9G_Server.
"The balance of evidence suggests a discernible human influence on global climate" - IPCC
Related commands
NET GROUP - Manage network resources
NET LOCALGROUP - Manage network resources
FINDGRP - List the (global or local) security groups a user has joined (NT 4 Reskit)
LOCAL - Display membership of local groups
GetDC - Get domain controller
Cusrmgr - Console User Manager. (Win 2K ResKit)
Equivalent bash command (Linux): groups - Print group names a user is in
GOTO
Direct a batch program to jump to a labelled line.
Syntax
GOTO label
Key
label : a predefined label in the batch program. Each label must
be on a line by itself, beginning with a colon.
To exit a batch script file or exit a subroutine specify GOTO:eof this will transfer control to the end of the current batch file, or the end of the current subroutine.
Examples:
IF %1==12 GOTO MySubroutine
Echo the input was NOT 12
goto:eof
:MySubroutine
Echo the input was 12
goto:eof
Use a variable as a label
CHOICE /C:01 /m choose [Y]yes or [N]No
goto s_routine_%ERRORLEVEL%
:s_routine_0
Echo You typed Y for yes
goto:eof
:s_routine_1
Echo You typed N for no
goto:eof
Skip commands by using a variable as a :: comment (REM)
In this example the COPY command will only run if the parameter "Update" is supplied to the batch
@echo off
setlocal
IF /I NOT %1==Update SET _skip=::
%_skip% COPY x:\update.dat
%_skip% echo Update applied
...
If Command Extensions are disabled GOTO will no longer recognise the :EOF label
"GOTO... how bad can it be??..." - XKCD
Related:
IF - Conditionally perform a command
CALL - Call one batch program from another
Powershell: While (condition) {action} else {action}
Equivalent bash command: case - Conditionally perform a command
GPUPDATE.exe Update Group Policy settings.
Syntax
GPUpdate [/Force] [/Logoff] [/Boot] [/Sync]
[/Target:{Computer | User}] [/Wait:value]
Key:
/Force Apply all policy settings, not just those that have changed.
/Logoff Logoff after the Group Policy settings have been updated.
Some group policy client-side extensions are only processed when a
user logs on. (Software Install, Folder Redirection.)
/Boot Restart after the Group Policy settings are applied.
Some group policy client-side extensions are only processed at startup
(e.g. computer-targeted Software Install)
/Sync Apply the next foreground policy synchronously (in the background).
This can be applied to computer boot and/or user logon. (see /Target)
/Target: Update only User or only Computer policy settings
default = both
/Wait: The number of seconds to wait for policy processing.
default = 600 (10 minutes)
'0' = do not wait.
'-1' = wait indefinitely.
If the time limit is exceeded, the command prompt returns,
but policy processing continues.
/Logoff and /Boot will have no effect if there are no client-side extensions called that require a logoff/reboot. /Force and /Wait parameters will be ignored if /sync is specified.
GPUPDATE will apply new and changed policies, it will not remove an existing setting where the policy is set to "not configured"
Example
C:\> GPUpdate /Force
When the people are being beaten with a stick, they are not much happier if it is called "The People's Stick" - Mikhail Bakunin (Statism and Anarchy)
Related:
NTRIGHTS - Edit user account rights
HKCU\Software\Microsoft\Windows\CurrentVersion\GroupPolicy\History
HKLM\Software\Microsoft\Windows\CurrentVersion\GroupPolicy\History
HELP Online help for MS Windows - most commands will give help when run with /? or -? (COMMAND /? or COMMAND -?)
GUI Help is available from START - Help or by running the help files directly:
C:\WINDOWS\help\ntcmds.chm
C:\WINDOWS\help\ntdef.chm
C:\WINDOWS\help\ntchowto.chm
C:\WINDOWS\help\nthelp.chm
C:\WINDOWS\help\ntshared.chm
Syntax
WINHELP [options] helpfile.hlp
WINHLP32.exe [options] helpFile
In XP: C:\WINDOWS\PCHealth\HelpCtr\Binaries\HelpCtr.exe
options:
-H show help about help
-G[n] Build a .gid file and quit,
If a number is specified, it determines which extensible tab to
display by default the first time the help file is opened.
A value of 1 would be the first tab beyond the Find tab.
This command cannot be used with -S.
-S Create a .gid file without showing an animated icon.
Cannot be used with -G. (winhlp32 only)
-W window
Specify the window for displaying the topic.
This command cannot be used with -P.
-P Show the topic in a pop-up window.
This command cannot be used with -W.
You must use the -P switch in combination with the
-N (context number) or -I (topic ID) switch.
-N contextNum | -I topicID
Specify the topic to open using either a topic number,
(defined in the [MAP] section of the HPJ file.)
or a topic ID string
(# footnote in the topic).
-K keyword
Specify the topic to open using a keyword.
This command cannot be used with -N or -I.
Powershell: Get-Help - Open the help file
Equivalent bash command (Linux): man pages
iCACLS.exe (2003 sp2, Vista)
Change file and folder permissions - display or modify Access Control Lists (ACLs) for files and folders.
iCACLS resolves various issues that occur when using the older CACLS & XCACLS
Syntax (files)
ICACLS FileName [/grant[:r] User:Permission[...]]
[/deny User:Permission[...]]
[/remove[:g|:d]] User[...]]
[/t] [/c] [/l] [/q]
[/setintegritylevel Level[...]]
Syntax (Store acls for all matching names into aclfile
for later use with /restore)
ICACLS name /save aclfile [/T] [/C] [/L] [/Q]
Syntax (restore folder)
ICACLS directory [/substitute SidOld SidNew [...]]
/restore aclfile [/C] [/L] [/Q]
Syntax (Change Owner)
ICACLS name /setowner user [/T] [/C] [/L] [/Q]
Syntax (Find items with an ACL that mentions a specific SID)
ICACLS name /findsid Sid [/T] [/C] [/L] [/Q]
Syntax (Find files whose ACL is not in canonical form or
with a length inconsistent with the ACE count.)
ICACLS name /verify [/T] [/C] [/L] [/Q]
Syntax (Replace ACL with default inherited acls for all matching files)
ICACLS name /reset [/T] [/C] [/L] [/Q]
Key
/T Traverse all subfolders to match files/directories.
/C Continue on file errors (access denied) Error messages are still displayed.
/L Perform the operation on a symbolic link itself, not its target.
/Q Quiet - supress success messages.
/grant :r user:permission
Grant access rights, with :r, the permissions
will replace any previouly granted explicit permissions.
Otherwise the permissions are added.
/deny user:permission
Explicitly deny the specified user access rights.
This will also remove any explicit grant of the
same permissions to the same user.
/remove[:[g|d]] User
Remove all occurrences of User from the acl.
:g remove all granted rights to that User/Sid.
:d remove all denied rights to that User/Sid.
/setintegritylevel [(CI)(OI)]Level
Add an integrity ACE to all matching files.
level is one of L,M,H (Low Medium or High)
A Directory Inheritance option for the integrity ACE may precede the level:
/inheritance:e|d|r
e - enable inheritance
d - disable inheritance and copy the ACEs
r - remove all inherited ACEs
user A user account, Group or a SID
/restore Apply the acls stored in ACLfile to the files in directory
permission is a permission mask and can be specified in one of two forms:
a sequence of simple rights:
F - full access
M - modify access
RX - read and execute access
R - read-only access
W - write-only access
a comma-separated list in parenthesis of specific rights:
D - delete
RC - read control
WDAC - write DAC
WO - write owner
S - synchronize
AS - access system security
MA - maximum allowed
GR - generic read
GW - generic write
GE - generic execute
GA - generic all
RD - read data/list directory
WD - write data/add file
AD - append data/add subdirectory
REA - read extended attributes
WEA - write extended attributes
X - execute/traverse
DC - delete child
RA - read attributes
WA - write attributes
inheritance rights may precede either form and are applied
only to directories:
(OI) - object inherit
(CI) - container inherit
(IO) - inherit only
(NP) - don't propagate inherit
Unlike many other command-line tools, iCACLS correctly preserves the canonical ordering of ACE entries:
Explicit denials
Explicit grants
Inherited denials
Inherited grants
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.
Using iCACLS
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 also be combined as folllows:
(OI)(CI) This folder, subfolders, and files.
(OI)(CI)(IO) Subfolders and files only.
(CI)(IO) Subfolders only.
(OI) (IO) Files only.
So BUILTIN\Administrators:(OI)(CI)F means that both files and Subdirectories will inherit 'F' (Fullcontrol)
similarly (CI)R means Directories will inherit 'R' (Read folders only = List permission)
When cacls is applied to the current folder only there is no inheritance and so no output.
Bugs
You can’t break existing inheritance of permissions with icacls, for that you need XCACLS.vbs.
In Windows Server 2003 SP2 there is a bug when attempting to use the /setowner switch, which returns “Access denied”.
A limited release hotfix is available to resolve this issue (Q947870) alternatively use SUBINACL
nb this bug is NOT present on Vista SP1 or Windows Server 2008.
Examples:
To backup the ACLs of every file in a directory type:
icacls * /save Myacl_backup.txt
Restore ACLS using a previously saved acl file:
icacls /restore Myacl_backup.txt
Change the Integrity Level (IL) of a file to High:
icacls MyReport.doc /setintegritylevel H
Grant the group FileAdmins Delete and Write DAC permissions to Sales_Folder:
icacls Sales_Folder /grant FileAdmins:(D,WDAC)
Propagate a new permission to all files and subfolders, without using inheritance:
(so if any of the subfolders contain specific permissions, those won't be overwritten)
icacls * /grant accountName:(NP)(RX) /T
"Whether a pretty woman grants or withholds her favours, she always likes to be asked for them" - Ovid (Ars Amatoria)
Related:
ATTRIB - Display or change file attributes
AccessEnum - GUI to browse a tree view of user privs
CACLS - Change file permissions
DIR /Q - Display the owner for a list of files (try it for Program files)
PERMS - Show permissions for a user
FIXACLS - Restore default privs (Resource Kit supplement 2)
FSUTIL - File System Options
NTRIGHTS - Edit user account rights
SHOWACL - Show file Access Control Lists (Windows 2000)
TAKEOWN - Take ownership of shares
XCACLS - Display or modify Access Control Lists (ACLs) for files and folders
Q919240 - Icacls is available for Windows Server 2003 SP2
Q834721 - Permissions on Folder are incorrectly ordered
Q943043 - Icacls.exe does not support inheritance
Q245031 - Change Registry Permissions (RegIni)
Q220167 - Understanding Container Access Inheritance Flags
Permissions explained
ACL utils: SetACL or FileACL (free)
Equivalent bash command (Linux): chmod / chown - Change file permissions/owner and group
IF
Conditionally perform a command.
File syntax
IF [NOT] EXIST filename command
IF [NOT] EXIST filename (command) ELSE (command)
String syntax
IF [/I] [NOT] item1==item2 command
IF [/I] item1 compare-op item2 command
IF [/I] item1 compare-op item2 (command) ELSE (command)
Error Check Syntax
IF [NOT] DEFINED variable command
IF [NOT] ERRORLEVEL number command
IF CMDEXTVERSION number command
key
item May be a text string or an environment variable
a variable may be modified using either
Substring syntax or Search syntax
command The command to perform
NOT perform the command if the condition is false.
== perform the command if the two strings are equal.
/I Do a case Insensitive string comparison.
compare-op May be one of
EQU : Equal
NEQ : Not equal
LSS : Less than <
LEQ : Less than or Equal <=
GTR : Greater than >
GEQ : Greater than or equal >=
This 3 digit syntax is necessary because the > and <
symbols are recognised as redirection operators
IF ERRORLEVEL n statements should be read as IF Errorlevel >= number
i.e.
IF ERRORLEVEL 0 will return TRUE when the errorlevel is 64
An alternative and often better method of checking Errorlevels is to use the string syntax along with the %ERRORLEVEL% variable:
IF %ERRORLEVEL% GTR 0 Echo An error was found
IF %ERRORLEVEL% LSS 0 Echo An error was found
IF %ERRORLEVEL% EQU 0 Echo No error found
IF %ERRORLEVEL% EQU 0 (Echo No error found) ELSE (Echo An error was found)
IF %ERRORLEVEL% EQU 0 Echo No error found || Echo An error was found
Note some errors are negative numbers.
When working with errorlevels in a batch file it's a good idea to also use SETLOCAL so that the %ERRORLEVEL% variable is reset each time the batch file runs.
IF EXIST filename will return true if the file exists (this is not case sensitive).
Examples:
IF EXIST C:\install.log (echo complete) ELSE (echo failed)
IF DEFINED _department ECHO Got the department variable
IF DEFINED _commission SET /A _salary=%_salary% + %_commission%
IF CMDEXTVERSION 1 GOTO start_process
IF %ERRORLEVEL% EQU 2 goto sub_problem2
Does %1 exist?
To test for the existence of a command line parameter - use empty brackets like this
IF [%1]==[] ECHO Value Missing
or
IF [%1] EQU [] ECHO Value Missing
In the case of a variable that may be NULL - a null variable will remove the variable definition altogether, so testing for NULLs becomes easy:
IF NOT DEFINED _example ECHO Value Missing
IF DEFINED will return true if the variable contains any value (even if the value is just a space)
Test the existence of files and folders
IF EXIST name - will detect the existence of a file or a folder - the script empty.cmd will show if the folder is empty or not.
Brackets
You can improve the readability of a batch script by writing a complex IF...ELSE command over several lines using brackets
e.g.
IF EXIST filename (
del filename
) ELSE (
echo The file was not found.
)
The IF statement does not use any great intelligence when evaluating Brackets, so for example the command below will fail:
IF EXIST MyFile.txt (ECHO Some(more)Potatoes)
This version will work:
IF EXIST MyFile.txt (ECHO Some[more]Potatoes)
If the string being compared by an IF command includes delimiters such as [Space] or [Comma], then either the delimiters must be escaped with a caret ^ or the whole string must be "quoted".
This is so that the IF statement will treat the string as a single item and not as several separate strings.
Testing Numeric values
Do not use brackets or quotes when comparing numeric values
e.g.
IF (2) GEQ (15) echo "bigger"
or
IF "2" GEQ "15" echo "bigger"
These will perform a character comparison and will always echo "bigger"
however the command
IF 2 GEQ 15 echo "bigger"
Will perform a numeric comparison and works as expected - notice that this behaviour is exactly opposite to the SET /a command where quotes are required.
The examples here all use GEQ, but this applies equally to all the compare-op operators: EQU, NEQ, LSS, LEQ, GTR, GEQ
when comparing numbers as a string "026" > "26"
Wildcards
Wildcards are not supported by IF, so %COMPUTERNAME%==SS6* will not match SS64
A workaround is to retrieve the substring and compare just those characters:
SET _prefix=%COMPUTERNAME:~0,3%
IF %_prefix%==SS6 GOTO they_matched
Pipes
When piping commands, the expression is evaluated from left to right, so
IF... | ... is equivalent to (IF ... ) | ...
you can also use the explicit syntax IF (... | ...)
ERRORLEVEL
To deliberately raise an ERRORLEVEL in a batch script use the EXIT /B command.
It is possible (though not a good idea) to create a string variable called %ERRORLEVEL% (user variable)
if present such a variable will prevent the real ERRORLEVEL (a system variable) from being used by commands such as ECHO and IF.
To test for the existence of a user variable use SET errorlevel, or IF DEFINED ERRORLEVEL
If Command Extensions are disabled IF will only support direct comparisons: IF ==, IF EXIST, IF ERRORLEVEL
also the system variable CMDEXTVERSION will be disabled.
You see things; and you say 'Why?' But I dream things that never were; and I say 'why not?' - George Bernard Shaw
Related:
Conditional execution syntax (AND / OR)
SET - Display or Edit environment variables
ECHO - Display message on screen
EXIT - Set a specific ERRORLEVEL
IFMEMBER - NT Workgroup member (Resource kit)
SC - Is a Service running (Resource kit)
Powershell: if - Conditionally perform a command
Equivalent bash command (Linux): if - Conditionally perform a command
IFMEMBER (Resource Kit)
Find out if the current user is a member of one or more workgroups.
Syntax
IFMEMBER [options] WorkGroup [ WorkGroup2 WorkGroup3...]
Options:
/verbose or /v : print all matches.
/list or /l : print all groups user is a member of
The %ERRORLEVEL% return code shows how many of the listed workgroups the currently logged-in user is a member of.
Examples
IFMEMBER /v /l "MyDomain\Administrators"
IF ERRORLEVEL 1 echo This user is an Administrator
Notice that the syntax here is the opposite to most other commands in that an %errorlevel% of 1 = Success
A good way to utilise IFMEMBER is through conditional execution...
IFMEMBER Administrators || ECHO Error is 1 so [%Username%] is in Admin_WG
IFMEMBER Administrators && ECHO Error is 0 so [%Username%] is NOT in Admin_WG
"The euro will raise the citizens' awareness of their belonging to one Europe more than any other integration step to date" - Gerhard Schroeder
Related:
NET GROUP - Add or remove a user from a workgroup
SHOWMBRS - List the members of a Workgroup
SHOWACCS - Show access profile (Windows 2000)
Joeware.net - MemberOf.exe - Like IFMEMBER but able to handle nested AD groups
IPCONFIG Configure IP (internet protocol configuration)
Syntax
IPCONFIG /all Display full configuration information.
IPCONFIG /release [adapter]
Release the IP address for the specified adapter.
IPCONFIG /renew [adapter]
Renew the IP address for the specified adapter.
IPCONFIG /flushdns Purge the DNS Resolver cache.
IPCONFIG /registerdns Refresh all DHCP leases and re-register DNS names.
IPCONFIG /displaydns Display the contents of the DNS Resolver Cache.
IPCONFIG /showclassid adapter
Display all the DHCP class IDs allowed for adapter.
IPCONFIG /setclassid adapter [classid]
Modify the dhcp class id.
If the Adapter name contains spaces, use quotes: "Adapter Name"
wildcard characters * and ? allowed, see the examples below
The default is to display only the IP address, subnet mask and default gateway for each adapter bound to TCP/IP.
For Release and Renew, if no adapter name is specified, then the IP address leases for all adapters bound to TCP/IP will be released or renewed.
For Setclassid, if no ClassId is specified, then the ClassId is removed.
Examples:
> ipconfig ... Show information.
> ipconfig /all ... Show detailed information
> ipconfig /renew ... renew all adapters
> ipconfig /renew EL* ... renew any connection that has its
name starting with EL
> ipconfig /release *Con* ... release all matching connections,
eg. "Local Area Connection 1" or
"Local Area Connection 2"
> ipconfig /setclassid "Local Area Connection" TEST
... set the DHCP class ID for the
named adapter to = TEST
"Life is a grand adventure - or it is nothing." - Helen Keller
Related:
BROWSTAT - Get domain, browser and PDC info
NETSTAT - Display networking statistics (TCP/IP)
NETSH - Configure interfaces, routing protocols, filters, routes, RRAS
PATHPING - IP trace utility
PING - Test a network connection
Q192064 - Locate multiple preferred logon servers
Q813878 - How to block specific network protocols and ports.
Q313190 - Use IPSec IP Filter Lists
The Inq/Jon Honeyball - Routing to harden machines against attack
www.ipchicken.com
Equivalent bash command (Linux): lookupd -flushcache, ifconfig - IP configuration
Equivalent bash command (OS X): ipconfig / dscacheutil - View IP config / Query / flush the Directory Service cache
KILL (Resource kit) Remove a running process from memory.
Syntax
KILL [option] process_id
KILL [option] task_name
KILL [option] window_title
Option
-f Force process kill
Note: Kill -f basically just nukes the process from existence, potentially leaking a lot of memory and losing any data that the process hadn't committed to disk yet. It is there for worst case scenarios - when you absolutely must end the process now, and don't care whether proper cleanup gets done or not.
In WindowsXP, KILL is replaced with the superior TASKKILL - Allowing you to specify a remote computer, different user account etc - for more details run TASKKILL /?
If you're going to tell people the truth, you'd better make them laugh. Otherwise they'll kill you. - George Bernard Shaw
Related:
PsKill - Kill processes by name or process ID
PsSuspend - Suspend a processes
TSKILL - Kill process on a Terminal Server
TASKKILL - Kill a local or remote task (XP)
PsList List detailed information about processes
NET - Stop a service from running
NET FILE - Force an open file to close
RKILL - Remote Kill (Resource Kit) view or kill processes on a remote server
Powershell: Stop-Process - Stop a running process (kill)
Q171773 - Kill a background process
Q178893 - Terminate an Application "Cleanly" in Win32
Q197155 - How to Kill an Orphaned Process
Equivalent bash command (Linux): kill - Kill a process
LABEL Edit a disk label.
Syntax
LABEL [drive:][label]
The disk label is never referred to by other batch commands, it's just for human recognition.
e.g. as a reminder of which floppy disk is actually in the machine.
The maximum length is 11 characters (spaces allowed)
This is not to be confused with the drive description held in the registry.
ASSOCIAT - One step file association (Resource Kit)
GLOBAL (Resource kit) Display membership of global groups on remote servers or remote domains.
Syntax
GLOBAL group_name domain_name | \\server
Key
group_name The global group.
domain_name A network domain.
\\server A network server.
Examples:
GLOBAL "Domain Users" Scotland
Displays the members of the group "Domain Users" in the Scotland domain.
GLOBAL PrintUsers \\9G_Server
Displays the members of the group PrintUsers on server 9G_Server.
"The balance of evidence suggests a discernible human influence on global climate" - IPCC
Related commands
NET GROUP - Manage network resources
NET LOCALGROUP - Manage network resources
FINDGRP - List the (global or local) security groups a user has joined (NT 4 Reskit)
LOCAL - Display membership of local groups
GetDC - Get domain controller
Cusrmgr - Console User Manager. (Win 2K ResKit)
Equivalent bash command (Linux): groups - Print group names a user is in
GOTO
Direct a batch program to jump to a labelled line.
Syntax
GOTO label
Key
label : a predefined label in the batch program. Each label must
be on a line by itself, beginning with a colon.
To exit a batch script file or exit a subroutine specify GOTO:eof this will transfer control to the end of the current batch file, or the end of the current subroutine.
Examples:
IF %1==12 GOTO MySubroutine
Echo the input was NOT 12
goto:eof
:MySubroutine
Echo the input was 12
goto:eof
Use a variable as a label
CHOICE /C:01 /m choose [Y]yes or [N]No
goto s_routine_%ERRORLEVEL%
:s_routine_0
Echo You typed Y for yes
goto:eof
:s_routine_1
Echo You typed N for no
goto:eof
Skip commands by using a variable as a :: comment (REM)
In this example the COPY command will only run if the parameter "Update" is supplied to the batch
@echo off
setlocal
IF /I NOT %1==Update SET _skip=::
%_skip% COPY x:\update.dat
%_skip% echo Update applied
...
If Command Extensions are disabled GOTO will no longer recognise the :EOF label
"GOTO... how bad can it be??..." - XKCD
Related:
IF - Conditionally perform a command
CALL - Call one batch program from another
Powershell: While (condition) {action} else {action}
Equivalent bash command: case - Conditionally perform a command
GPUPDATE.exe Update Group Policy settings.
Syntax
GPUpdate [/Force] [/Logoff] [/Boot] [/Sync]
[/Target:{Computer | User}] [/Wait:value]
Key:
/Force Apply all policy settings, not just those that have changed.
/Logoff Logoff after the Group Policy settings have been updated.
Some group policy client-side extensions are only processed when a
user logs on. (Software Install, Folder Redirection.)
/Boot Restart after the Group Policy settings are applied.
Some group policy client-side extensions are only processed at startup
(e.g. computer-targeted Software Install)
/Sync Apply the next foreground policy synchronously (in the background).
This can be applied to computer boot and/or user logon. (see /Target)
/Target: Update only User or only Computer policy settings
default = both
/Wait: The number of seconds to wait for policy processing.
default = 600 (10 minutes)
'0' = do not wait.
'-1' = wait indefinitely.
If the time limit is exceeded, the command prompt returns,
but policy processing continues.
/Logoff and /Boot will have no effect if there are no client-side extensions called that require a logoff/reboot. /Force and /Wait parameters will be ignored if /sync is specified.
GPUPDATE will apply new and changed policies, it will not remove an existing setting where the policy is set to "not configured"
Example
C:\> GPUpdate /Force
When the people are being beaten with a stick, they are not much happier if it is called "The People's Stick" - Mikhail Bakunin (Statism and Anarchy)
Related:
NTRIGHTS - Edit user account rights
HKCU\Software\Microsoft\Windows\CurrentVersion\GroupPolicy\History
HKLM\Software\Microsoft\Windows\CurrentVersion\GroupPolicy\History
HELP Online help for MS Windows - most commands will give help when run with /? or -? (COMMAND /? or COMMAND -?)
GUI Help is available from START - Help or by running the help files directly:
C:\WINDOWS\help\ntcmds.chm
C:\WINDOWS\help\ntdef.chm
C:\WINDOWS\help\ntchowto.chm
C:\WINDOWS\help\nthelp.chm
C:\WINDOWS\help\ntshared.chm
Syntax
WINHELP [options] helpfile.hlp
WINHLP32.exe [options] helpFile
In XP: C:\WINDOWS\PCHealth\HelpCtr\Binaries\HelpCtr.exe
options:
-H show help about help
-G[n] Build a .gid file and quit,
If a number is specified, it determines which extensible tab to
display by default the first time the help file is opened.
A value of 1 would be the first tab beyond the Find tab.
This command cannot be used with -S.
-S Create a .gid file without showing an animated icon.
Cannot be used with -G. (winhlp32 only)
-W window
Specify the window for displaying the topic.
This command cannot be used with -P.
-P Show the topic in a pop-up window.
This command cannot be used with -W.
You must use the -P switch in combination with the
-N (context number) or -I (topic ID) switch.
-N contextNum | -I topicID
Specify the topic to open using either a topic number,
(defined in the [MAP] section of the HPJ file.)
or a topic ID string
(# footnote in the topic).
-K keyword
Specify the topic to open using a keyword.
This command cannot be used with -N or -I.
Powershell: Get-Help - Open the help file
Equivalent bash command (Linux): man pages
iCACLS.exe (2003 sp2, Vista)
Change file and folder permissions - display or modify Access Control Lists (ACLs) for files and folders.
iCACLS resolves various issues that occur when using the older CACLS & XCACLS
Syntax (files)
ICACLS FileName [/grant[:r] User:Permission[...]]
[/deny User:Permission[...]]
[/remove[:g|:d]] User[...]]
[/t] [/c] [/l] [/q]
[/setintegritylevel Level[...]]
Syntax (Store acls for all matching names into aclfile
for later use with /restore)
ICACLS name /save aclfile [/T] [/C] [/L] [/Q]
Syntax (restore folder)
ICACLS directory [/substitute SidOld SidNew [...]]
/restore aclfile [/C] [/L] [/Q]
Syntax (Change Owner)
ICACLS name /setowner user [/T] [/C] [/L] [/Q]
Syntax (Find items with an ACL that mentions a specific SID)
ICACLS name /findsid Sid [/T] [/C] [/L] [/Q]
Syntax (Find files whose ACL is not in canonical form or
with a length inconsistent with the ACE count.)
ICACLS name /verify [/T] [/C] [/L] [/Q]
Syntax (Replace ACL with default inherited acls for all matching files)
ICACLS name /reset [/T] [/C] [/L] [/Q]
Key
/T Traverse all subfolders to match files/directories.
/C Continue on file errors (access denied) Error messages are still displayed.
/L Perform the operation on a symbolic link itself, not its target.
/Q Quiet - supress success messages.
/grant :r user:permission
Grant access rights, with :r, the permissions
will replace any previouly granted explicit permissions.
Otherwise the permissions are added.
/deny user:permission
Explicitly deny the specified user access rights.
This will also remove any explicit grant of the
same permissions to the same user.
/remove[:[g|d]] User
Remove all occurrences of User from the acl.
:g remove all granted rights to that User/Sid.
:d remove all denied rights to that User/Sid.
/setintegritylevel [(CI)(OI)]Level
Add an integrity ACE to all matching files.
level is one of L,M,H (Low Medium or High)
A Directory Inheritance option for the integrity ACE may precede the level:
/inheritance:e|d|r
e - enable inheritance
d - disable inheritance and copy the ACEs
r - remove all inherited ACEs
user A user account, Group or a SID
/restore Apply the acls stored in ACLfile to the files in directory
permission is a permission mask and can be specified in one of two forms:
a sequence of simple rights:
F - full access
M - modify access
RX - read and execute access
R - read-only access
W - write-only access
a comma-separated list in parenthesis of specific rights:
D - delete
RC - read control
WDAC - write DAC
WO - write owner
S - synchronize
AS - access system security
MA - maximum allowed
GR - generic read
GW - generic write
GE - generic execute
GA - generic all
RD - read data/list directory
WD - write data/add file
AD - append data/add subdirectory
REA - read extended attributes
WEA - write extended attributes
X - execute/traverse
DC - delete child
RA - read attributes
WA - write attributes
inheritance rights may precede either form and are applied
only to directories:
(OI) - object inherit
(CI) - container inherit
(IO) - inherit only
(NP) - don't propagate inherit
Unlike many other command-line tools, iCACLS correctly preserves the canonical ordering of ACE entries:
Explicit denials
Explicit grants
Inherited denials
Inherited grants
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.
Using iCACLS
- To edit a file you must already have the "Change" ACL (or be the file's owner)
- To use the iCACLS command to change the permissions of a file requires "FULL Control" (or be the file's owner)
- File "Ownership" will always override all ACL's - you always have Full Control over files that you create.
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 also be combined as folllows:
(OI)(CI) This folder, subfolders, and files.
(OI)(CI)(IO) Subfolders and files only.
(CI)(IO) Subfolders only.
(OI) (IO) Files only.
So BUILTIN\Administrators:(OI)(CI)F means that both files and Subdirectories will inherit 'F' (Fullcontrol)
similarly (CI)R means Directories will inherit 'R' (Read folders only = List permission)
When cacls is applied to the current folder only there is no inheritance and so no output.
Bugs
You can’t break existing inheritance of permissions with icacls, for that you need XCACLS.vbs.
In Windows Server 2003 SP2 there is a bug when attempting to use the /setowner switch, which returns “Access denied”.
A limited release hotfix is available to resolve this issue (Q947870) alternatively use SUBINACL
nb this bug is NOT present on Vista SP1 or Windows Server 2008.
Examples:
To backup the ACLs of every file in a directory type:
icacls * /save Myacl_backup.txt
Restore ACLS using a previously saved acl file:
icacls /restore Myacl_backup.txt
Change the Integrity Level (IL) of a file to High:
icacls MyReport.doc /setintegritylevel H
Grant the group FileAdmins Delete and Write DAC permissions to Sales_Folder:
icacls Sales_Folder /grant FileAdmins:(D,WDAC)
Propagate a new permission to all files and subfolders, without using inheritance:
(so if any of the subfolders contain specific permissions, those won't be overwritten)
icacls * /grant accountName:(NP)(RX) /T
"Whether a pretty woman grants or withholds her favours, she always likes to be asked for them" - Ovid (Ars Amatoria)
Related:
ATTRIB - Display or change file attributes
AccessEnum - GUI to browse a tree view of user privs
CACLS - Change file permissions
DIR /Q - Display the owner for a list of files (try it for Program files)
PERMS - Show permissions for a user
FIXACLS - Restore default privs (Resource Kit supplement 2)
FSUTIL - File System Options
NTRIGHTS - Edit user account rights
SHOWACL - Show file Access Control Lists (Windows 2000)
TAKEOWN - Take ownership of shares
XCACLS - Display or modify Access Control Lists (ACLs) for files and folders
Q919240 - Icacls is available for Windows Server 2003 SP2
Q834721 - Permissions on Folder are incorrectly ordered
Q943043 - Icacls.exe does not support inheritance
Q245031 - Change Registry Permissions (RegIni)
Q220167 - Understanding Container Access Inheritance Flags
Permissions explained
ACL utils: SetACL or FileACL (free)
Equivalent bash command (Linux): chmod / chown - Change file permissions/owner and group
IF
Conditionally perform a command.
File syntax
IF [NOT] EXIST filename command
IF [NOT] EXIST filename (command) ELSE (command)
String syntax
IF [/I] [NOT] item1==item2 command
IF [/I] item1 compare-op item2 command
IF [/I] item1 compare-op item2 (command) ELSE (command)
Error Check Syntax
IF [NOT] DEFINED variable command
IF [NOT] ERRORLEVEL number command
IF CMDEXTVERSION number command
key
item May be a text string or an environment variable
a variable may be modified using either
Substring syntax or Search syntax
command The command to perform
NOT perform the command if the condition is false.
== perform the command if the two strings are equal.
/I Do a case Insensitive string comparison.
compare-op May be one of
EQU : Equal
NEQ : Not equal
LSS : Less than <
LEQ : Less than or Equal <=
GTR : Greater than >
GEQ : Greater than or equal >=
This 3 digit syntax is necessary because the > and <
symbols are recognised as redirection operators
IF ERRORLEVEL n statements should be read as IF Errorlevel >= number
i.e.
IF ERRORLEVEL 0 will return TRUE when the errorlevel is 64
An alternative and often better method of checking Errorlevels is to use the string syntax along with the %ERRORLEVEL% variable:
IF %ERRORLEVEL% GTR 0 Echo An error was found
IF %ERRORLEVEL% LSS 0 Echo An error was found
IF %ERRORLEVEL% EQU 0 Echo No error found
IF %ERRORLEVEL% EQU 0 (Echo No error found) ELSE (Echo An error was found)
IF %ERRORLEVEL% EQU 0 Echo No error found || Echo An error was found
Note some errors are negative numbers.
When working with errorlevels in a batch file it's a good idea to also use SETLOCAL so that the %ERRORLEVEL% variable is reset each time the batch file runs.
IF EXIST filename will return true if the file exists (this is not case sensitive).
Examples:
IF EXIST C:\install.log (echo complete) ELSE (echo failed)
IF DEFINED _department ECHO Got the department variable
IF DEFINED _commission SET /A _salary=%_salary% + %_commission%
IF CMDEXTVERSION 1 GOTO start_process
IF %ERRORLEVEL% EQU 2 goto sub_problem2
Does %1 exist?
To test for the existence of a command line parameter - use empty brackets like this
IF [%1]==[] ECHO Value Missing
or
IF [%1] EQU [] ECHO Value Missing
In the case of a variable that may be NULL - a null variable will remove the variable definition altogether, so testing for NULLs becomes easy:
IF NOT DEFINED _example ECHO Value Missing
IF DEFINED will return true if the variable contains any value (even if the value is just a space)
Test the existence of files and folders
IF EXIST name - will detect the existence of a file or a folder - the script empty.cmd will show if the folder is empty or not.
Brackets
You can improve the readability of a batch script by writing a complex IF...ELSE command over several lines using brackets
e.g.
IF EXIST filename (
del filename
) ELSE (
echo The file was not found.
)
The IF statement does not use any great intelligence when evaluating Brackets, so for example the command below will fail:
IF EXIST MyFile.txt (ECHO Some(more)Potatoes)
This version will work:
IF EXIST MyFile.txt (ECHO Some[more]Potatoes)
If the string being compared by an IF command includes delimiters such as [Space] or [Comma], then either the delimiters must be escaped with a caret ^ or the whole string must be "quoted".
This is so that the IF statement will treat the string as a single item and not as several separate strings.
Testing Numeric values
Do not use brackets or quotes when comparing numeric values
e.g.
IF (2) GEQ (15) echo "bigger"
or
IF "2" GEQ "15" echo "bigger"
These will perform a character comparison and will always echo "bigger"
however the command
IF 2 GEQ 15 echo "bigger"
Will perform a numeric comparison and works as expected - notice that this behaviour is exactly opposite to the SET /a command where quotes are required.
The examples here all use GEQ, but this applies equally to all the compare-op operators: EQU, NEQ, LSS, LEQ, GTR, GEQ
when comparing numbers as a string "026" > "26"
Wildcards
Wildcards are not supported by IF, so %COMPUTERNAME%==SS6* will not match SS64
A workaround is to retrieve the substring and compare just those characters:
SET _prefix=%COMPUTERNAME:~0,3%
IF %_prefix%==SS6 GOTO they_matched
Pipes
When piping commands, the expression is evaluated from left to right, so
IF... | ... is equivalent to (IF ... ) | ...
you can also use the explicit syntax IF (... | ...)
ERRORLEVEL
To deliberately raise an ERRORLEVEL in a batch script use the EXIT /B command.
It is possible (though not a good idea) to create a string variable called %ERRORLEVEL% (user variable)
if present such a variable will prevent the real ERRORLEVEL (a system variable) from being used by commands such as ECHO and IF.
To test for the existence of a user variable use SET errorlevel, or IF DEFINED ERRORLEVEL
If Command Extensions are disabled IF will only support direct comparisons: IF ==, IF EXIST, IF ERRORLEVEL
also the system variable CMDEXTVERSION will be disabled.
You see things; and you say 'Why?' But I dream things that never were; and I say 'why not?' - George Bernard Shaw
Related:
Conditional execution syntax (AND / OR)
SET - Display or Edit environment variables
ECHO - Display message on screen
EXIT - Set a specific ERRORLEVEL
IFMEMBER - NT Workgroup member (Resource kit)
SC - Is a Service running (Resource kit)
Powershell: if - Conditionally perform a command
Equivalent bash command (Linux): if - Conditionally perform a command
IFMEMBER (Resource Kit)
Find out if the current user is a member of one or more workgroups.
Syntax
IFMEMBER [options] WorkGroup [ WorkGroup2 WorkGroup3...]
Options:
/verbose or /v : print all matches.
/list or /l : print all groups user is a member of
The %ERRORLEVEL% return code shows how many of the listed workgroups the currently logged-in user is a member of.
Examples
IFMEMBER /v /l "MyDomain\Administrators"
IF ERRORLEVEL 1 echo This user is an Administrator
Notice that the syntax here is the opposite to most other commands in that an %errorlevel% of 1 = Success
A good way to utilise IFMEMBER is through conditional execution...
IFMEMBER Administrators || ECHO Error is 1 so [%Username%] is in Admin_WG
IFMEMBER Administrators && ECHO Error is 0 so [%Username%] is NOT in Admin_WG
"The euro will raise the citizens' awareness of their belonging to one Europe more than any other integration step to date" - Gerhard Schroeder
Related:
NET GROUP - Add or remove a user from a workgroup
SHOWMBRS - List the members of a Workgroup
SHOWACCS - Show access profile (Windows 2000)
Joeware.net - MemberOf.exe - Like IFMEMBER but able to handle nested AD groups
IPCONFIG Configure IP (internet protocol configuration)
Syntax
IPCONFIG /all Display full configuration information.
IPCONFIG /release [adapter]
Release the IP address for the specified adapter.
IPCONFIG /renew [adapter]
Renew the IP address for the specified adapter.
IPCONFIG /flushdns Purge the DNS Resolver cache.
IPCONFIG /registerdns Refresh all DHCP leases and re-register DNS names.
IPCONFIG /displaydns Display the contents of the DNS Resolver Cache.
IPCONFIG /showclassid adapter
Display all the DHCP class IDs allowed for adapter.
IPCONFIG /setclassid adapter [classid]
Modify the dhcp class id.
If the Adapter name contains spaces, use quotes: "Adapter Name"
wildcard characters * and ? allowed, see the examples below
The default is to display only the IP address, subnet mask and default gateway for each adapter bound to TCP/IP.
For Release and Renew, if no adapter name is specified, then the IP address leases for all adapters bound to TCP/IP will be released or renewed.
For Setclassid, if no ClassId is specified, then the ClassId is removed.
Examples:
> ipconfig ... Show information.
> ipconfig /all ... Show detailed information
> ipconfig /renew ... renew all adapters
> ipconfig /renew EL* ... renew any connection that has its
name starting with EL
> ipconfig /release *Con* ... release all matching connections,
eg. "Local Area Connection 1" or
"Local Area Connection 2"
> ipconfig /setclassid "Local Area Connection" TEST
... set the DHCP class ID for the
named adapter to = TEST
"Life is a grand adventure - or it is nothing." - Helen Keller
Related:
BROWSTAT - Get domain, browser and PDC info
NETSTAT - Display networking statistics (TCP/IP)
NETSH - Configure interfaces, routing protocols, filters, routes, RRAS
PATHPING - IP trace utility
PING - Test a network connection
Q192064 - Locate multiple preferred logon servers
Q813878 - How to block specific network protocols and ports.
Q313190 - Use IPSec IP Filter Lists
The Inq/Jon Honeyball - Routing to harden machines against attack
www.ipchicken.com
Equivalent bash command (Linux): lookupd -flushcache, ifconfig - IP configuration
Equivalent bash command (OS X): ipconfig / dscacheutil - View IP config / Query / flush the Directory Service cache
KILL (Resource kit) Remove a running process from memory.
Syntax
KILL [option] process_id
KILL [option] task_name
KILL [option] window_title
Option
-f Force process kill
Note: Kill -f basically just nukes the process from existence, potentially leaking a lot of memory and losing any data that the process hadn't committed to disk yet. It is there for worst case scenarios - when you absolutely must end the process now, and don't care whether proper cleanup gets done or not.
In WindowsXP, KILL is replaced with the superior TASKKILL - Allowing you to specify a remote computer, different user account etc - for more details run TASKKILL /?
If you're going to tell people the truth, you'd better make them laugh. Otherwise they'll kill you. - George Bernard Shaw
Related:
PsKill - Kill processes by name or process ID
PsSuspend - Suspend a processes
TSKILL - Kill process on a Terminal Server
TASKKILL - Kill a local or remote task (XP)
PsList List detailed information about processes
NET - Stop a service from running
NET FILE - Force an open file to close
RKILL - Remote Kill (Resource Kit) view or kill processes on a remote server
Powershell: Stop-Process - Stop a running process (kill)
Q171773 - Kill a background process
Q178893 - Terminate an Application "Cleanly" in Win32
Q197155 - How to Kill an Orphaned Process
Equivalent bash command (Linux): kill - Kill a process
LABEL Edit a disk label.
Syntax
LABEL [drive:][label]
The disk label is never referred to by other batch commands, it's just for human recognition.
e.g. as a reminder of which floppy disk is actually in the machine.
The maximum length is 11 characters (spaces allowed)
This is not to be confused with the drive description held in the registry.
On the Windows XP CD, under \SUPPORT\TOOLS you'll find MSRDPCLI.exe. This is the setup for use with 9.x/2000 machines.
"Ignorance is preferable to error; and he is less remote from the truth who believes nothing, than he who believes what is wrong" - Thomas Jefferson
Related Commands:
Q216783 - Keep-Alive Disconnected TS Connections
MAPISEND - Send email from the command line
RMTSHARE - Share a folder or printer
SHORTCUT - Create a windows shortcut
SHUTDOWN - Shutdown the computer/Log off a user
Equivalent bash command (Linux): vncconnect - Connect to a VNC server
MV.exe (Resource Kit)
Move File - Copy a file to another location even if the file is in use (Locked)
Syntax
MV /x /d source destination
Key
The first file name is the file to be copied and the second
the destination pathname.
/d : does not copy the file until reboot time
allows in-use files to be replaced
/x : Prevents the default action that will otherwise create a
folder called "deleted" containing a copy of the
original file.
Note that you must use a FULL pathname to each file.
The NT resource kit contains 2 versions of MV.EXE - a posix version and a Windows NT version - they are not the same!
The /d option is not available with the posix version of mv, but if you prefer, you can do a file replace at boot time by manually updating the registry (which is all MV.exe does)
Start the registry editor (regedt32.exe not regedit.exe)
Move to HKLM\SYSTEM\CurrentControlSet\Control\Session Manager
Double click on
PendingFileRenameOperations
(if it does not exist - create of type multi_str )
On the first line is the name of the new file with \??\ in front,
e.g.
\??\d:\temp\ntfs.sys
On the second line is the file to replaced with !\??\ in front,
e.g.
!\??\c:\winnt\system32\drivers\ntfs.sys
Click OK
So the complete Multi-String Data would appear like:
\??\d:\temp\ntfs.sys
!\??\c:\winnt\system32\drivers\ntfs.sys
Once the reboot is complete and the file replaced the PendingFileRenameOperations value will be deleted from the registry
"Anyone who has been to an english public school will always feel comparitively at home in prison" - Evelyn Waugh
Related:
INUSE - updated file replacement utility (may not preserve file permissions)
COPY - Copy one or more files to another location
MOVE - Move a file from one folder to another
Cachemov - Offline Files Cache Mover. (Win 2K ResKit)
Powershell: Move-Item - Move an item from one location to another (move/mv/mi)
Equivalent bash command (Linux): mv - Move or rename files or directories
NET.exe The NET Command is used to manage network resources as follows:
Manage Services
NET START, STOP, PAUSE, CONTINUE
Connect to a file/print Share (Drive Map)
NET USE
Manage file and printer shares
NET SHARE, VIEW
Manage open files and user sessions
NET FILE, SESSIONS
Manage Network Time
NET TIME
Manage Network Print jobs
NET PRINT
Security
NET ACCOUNTS, USER, GROUP, LOCALGROUP
Network Messaging
NET NAME, SEND
Help
NET HELP, HELPMSG
Network configuration
NET COMPUTER, CONFIG_WORKSTATION, CONFIG_SERVER, STATISTICS_WORKSTATION, STATISTICS_SERVER
When you use NET commands in a batch file, you can use the Y or N switch to unconditionally answer Yes or No to questions returned by the Net command
"The white man knows how to make everything but he does not know how to distribute it" - Sitting Bull
Related:
CON2PRT - Connect or disconnect a Printer
GLOBAL - Display membership of global groups
LOCAL - Display membership of local groups
MODE - Configure a system device
NETDOM - Domain Manager
OPENFILES - Query or display open files
SC - Service Control
Q149427 - Change Password from the CMD prompt
Equivalent bash commands (Linux): groups - group names a user is in, users - login names of users currently logged in
NETDOM.exe (Windows Server 2003/2008) Domain Manager - Manage Machine Accounts and Passwords. NetDom is available as part of the RSAT feature on a Windows 7 / 2008 R2 server (or by default, with the AD DS or AD LDS server roles.)
Syntax
NETDOM ADD Add a workstation or server account to the domain
NETDOM COMPUTERNAME Manage computer names
NETDOM HELP
NETDOM JOIN Join a workstation or member server to the domain
NETDOM MoveNT4BDC Rename an NT4 backup domain controller
NETDOM MOVE Move a workstation or member server to a new domain
NETDOM QUERY Query the domain for information
NETDOM TRUST Manage or verify the trust relationship between domains
NETDOM REMOVE Remove a workstation or server from the domain.
NETDOM RENAMECOMPUTER Rename a computer.
NETDOM RESETPWD Reset the machine account password for a domain controller
NETDOM RESET Reset the secure connection between a workstation and a DC
NETDOM VERIFY Verify the secure connection between a workstation and a DC
Only use the version of netdom supplied for your operating system, an older version of the NETDOM utility is included with the Windows XP Support Tools.
“Technology is ruled by two types of people: those who manage what they do not understand, and those who understand what they do not manage” - Mike Trout
Related:
Q216393 - Resetting computer accounts in Windows
NETSH (Network Shell) Configure Network Interfaces, Windows Firewall, Routing & remote access.
Syntax
NETSH [Context] [sub-Context] command
Key
The contexts and commands available vary by platform, the list below is for Windows 2008.
Use interactive mode/help (described below) to check the commands available on your machine.
= add - Add a configuration entry to a list of entries.
netsh add helper - Install the specified helper DLL
= advfirewall - Change the 'netsh advfirewall' context.
netsh advfirewall consec ? - Display a list of commands.
netsh advfirewall consec add - Add a new connection security rule.
netsh advfirewall consec delete - Delete all matching connection security rules.
netsh advfirewall consec dump - Display a configuration script.
netsh advfirewall consec set - Set new values for properties of an existing rule.
netsh advfirewall consec show - Display a specified connection security rule.
netsh advfirewall dump Create a script that contains the current configuration.
If saved to a file, this can be used to restore the configuration settings.
netsh advfirewall export path\filename - Export the current policy to the specified file.
netsh advfirewall import path\filename - Import policy from the specified file.
netsh advfirewall firewall add - Add a new inbound or outbound firewall rule.
netsh advfirewall firewall delete - Delete all matching inbound rules.
netsh advfirewall firewall dump - Display a configuration script.
netsh advfirewall firewall set - Set new values for properties of a existing rule.
netsh advfirewall firewall show - Display a specified firewall rule.
netsh advfirewall monitor delete - Delete all matching security associations.
netsh advfirewall monitor dump - Display a configuration script.
netsh advfirewall monitor show - Show all matching security associations.
netsh advfirewall reset - Reset to factory settings (Firewall=ON)
netsh advfirewall set allprofiles - Set properties in all profiles.
netsh advfirewall set currentprofile - Set properties in the active profile.
netsh advfirewall set domainprofile - Set properties in the domain profile.
netsh advfirewall set global - Set the global properties.
netsh advfirewall set privateprofile - Set properties in the private profile.
netsh advfirewall set publicprofile - Set properties in the public profile.
netsh advfirewall show allprofiles - Display properties for all profiles.
netsh advfirewall show currentprofile - Display properties for the active profile.
netsh advfirewall show domainprofile - Display properties for the domain properties.
netsh advfirewall show global - Display the global properties.
netsh advfirewall show privateprofile - Display properties for the private profile.
netsh advfirewall show publicprofile - Display properties for the public profile.
netsh advfirewall show store - Display the policy store for the current interactive session.
=bridge - Change to the 'netsh bridge' context.
netsh bridge dump - Display a configuration script.
netsh bridge install - Install the component corresponding to the current context.
netsh bridge set - Set configuration information.
netsh bridge show - Display information.
netsh bridge uninstall - Remove the component corresponding to the current context.
=delete - Delete a configuration entry from a list of entries.
netsh delete helper Remove the specified helper DLL from netsh.
Note that after a helper is removed, it is no longer supported by netsh.
=dhcpclient - Change to the 'netsh dhcpclient' context.
netsh dhcpclient list - List all the commands available.
netsh dhcpclient trace enable - Enable tracing for DHCP client and DHCP QEC.
netsh dhcpclient trace disable - Disable tracing for DHCP client and DHCP QEC.
=dump - Display a configuration script.
netsh dump - Create a script that contains the current configuration.
If saved to a file, this can be used to restore the configuration settings.
=exec - Run a script file.
exec - Load a script file and run it.
=firewall - Change to the 'netsh firewall' context.
netsh firewall add - Add firewall configuration.
netsh firewall delete - Delete firewall configuration.
netsh firewall dump - Display a configuration script.
netsh firewall reset - Reset firewall configuration to default.
netsh firewall set allowedprogram - Set firewall allowed program configuration.
netsh firewall set icmpsetting - Set firewall ICMP configuration.
netsh firewall set logging - Set firewall logging configuration.
netsh firewall set multicastbroadcastresponse - Set firewall multicast/broadcast response configuration.
netsh firewall set notifications - Set firewall notification configuration.
netsh firewall set opmode - Set firewall operational configuration.
netsh firewall set portopening - Set firewall port configuration.
netsh firewall set service - Set firewall service configuration.
netsh firewall show allowedprogram - Show firewall allowed program configuration.
netsh firewall show config - Show firewall configuration.
netsh firewall show currentprofile - Show current firewall profile.
netsh firewall show icmpsetting - Show firewall ICMP configuration.
netsh firewall show logging - Show firewall logging configuration.
netsh firewall show multicastbroadcastresponse - Show firewall multicast/broadcast response configuration.
netsh firewall show notifications - Show firewall notification configuration.
netsh firewall show opmode - Show firewall operational configuration.
netsh firewall show portopening - Show firewall port configuration.
netsh firewall show service - Show firewall service configuration.
netsh firewall show state - Show current firewall state.
=help - Display a list of netsh commands.
netsh help
=http - Change to the 'netsh http' context.
netsh http add - Add a configuration entry to a table.
netsh http delete - Delete a configuration entry from a table.
netsh http dump - Display a configuration script.
netsh http flush - Flushe internal data.
netsh http show - Display information.
=interface - Change to the 'netsh interface' context.
netsh interface 6to4 + Change to the 'netsh interface 6to4' context.
netsh interface add - Add a configuration entry to a table.
netsh interface delete - Delete a configuration entry from a table.
netsh interface dump - Display a configuration script.
netsh interface ipv4 + Change to the 'netsh interface ipv4' context.
netsh interface ipv6 + Change to the 'netsh interface ipv6' context.
netsh interface isatap + Change to the 'netsh interface isatap' context.
netsh interface portproxy + Change to the 'netsh interface portproxy' context.
netsh interface reset - Reset information.
netsh interface set - Set configuration information.
netsh interface show - Display information.
netsh interface tcp + Change to the 'netsh interface tcp' context.
netsh interface teredo + Change to the 'netsh interface teredo' context.
The following sub-contexts are available:
6to4 ipv4 ipv6 isatap portproxy tcp teredo
=ipsec - Change to the 'netsh ipsec' context.
netsh ipsec dump - Display a configuration script.
netsh ipsec dynamic add - Add policy, filter, and actions to SPD.
netsh ipsec dynamic delete - Delete policy, filter, and actions from SPD.
netsh ipsec dynamic dump - Display a configuration script.
netsh ipsec dynamic set - Modifiy policy, filter, and actions in SPD.
netsh ipsec dynamic show - Display policy, filter, and actions from SPD.
netsh ipsec static add - Create new policies and related information.
netsh ipsec static delete - Delete policies and related information.
netsh ipsec static dump - Display a configuration script.
netsh ipsec static exportpolicy - Export all the policies from the policy store.
netsh ipsec static importpolicy - Import the policies from a file to the policy store.
netsh ipsec static set - Modify existing policies and related information.
netsh ipsec static show - Display details of policies and related information.
=lan - Change to the 'netsh lan' context.
netsh lan add - Add a configuration entry to a table.
netsh lan delete - Delete a configuration entry from a table.
netsh lan dump - Display a configuration script.
netsh lan export - Save LAN profiles to XML files.
netsh lan reconnect - Reconnect on an interface.
netsh lan set - Configure settings on interfaces.
netsh lan show - Display information.
=nap - Change to the 'netsh nap' context.
netsh nap client + Change to the 'netsh nap client' context.
netsh nap dump - Display a configuration script.
netsh nap hra + Change to the 'netsh nap hra' context.
netsh nap reset - Reset configuration.
netsh nap show - Show configuration and state information.
=netio - Change to the 'netsh netio' context.
netsh netio add - Add a configuration entry to a table.
netsh netio delete - Delete a configuration entry from a table.
netsh netio dump - Display a configuration script.
netsh netio show - Display information.
=ras - Change to the 'netsh ras' context. (Remote Access Server)
netsh ras aaaa - Change to the 'netsh ras aaaa' context.
netsh ras add - Add items to a table.
netsh ras delete - Remove items from a table.
netsh ras diagnostics - Change to the 'netsh ras diagnostics' context.
netsh ras dump - Display a configuration script.
netsh ras ip - Change to the 'netsh ras ip' context.
netsh ras ipv6 - Change to the 'netsh ras ipv6' context.
netsh ras set - Set configuration information.
netsh ras show - Display information.
=rpc - Change to the 'netsh rpc' context. (RPC firewall filter)
netsh rpc add - Create an Add list of subnets.
netsh rpc delete - Create a Delete list of subnets.
netsh rpc dump - Display a configuration script.
netsh rpc filter - Change to the 'netsh rpc filter' context.
netsh rpc reset - Reset the selective binding settings to 'none' (listen on all interfaces).
netsh rpc show - Display the selective binding state for each subnet on the system.
=set - Update configuration settings on a remote machine.
netsh set machine [name=] [user=][[DomainName\]UserName] [pwd=][Password | *]
If a machine name is not specified, the local machine is used.
A username and password cannot be used to connect to the local machine.
=show - Display information.
netsh show alias - List all defined aliases.
netsh show helper - List all the top-level helpers.
=winhttp - Change to the 'netsh winhttp' context.
netsh winhttp dump - Display a configuration script.
netsh winhttp import - Import WinHTTP proxy settings.
netsh winhttp reset - Reset WinHTTP settings.
netsh winhttp set - Configure WinHTTP settings.
netsh winhttp show - Display currents settings.
=winsock - Change to the 'netsh winsock' context.
netsh winsock audit - Display a list of Winsock LSPs that have been installed and removed.
netsh winsock dump - Display a configuration script.
netsh winsock remove - Remove a Winsock LSP from the system.
netsh winsock reset - Reset the Winsock Catalog to a clean state.
netsh winsock show - Display information.
netsh - Interactive mode
In interactive mode, switch context by typing any context name: advfirewall, bridge, firewall, http, interface, ipsec.. etc
list commands with ? exit interactive mode with Quit or Exit.
To view help for any command, type the command, followed by a space and ?
The syntax on this page is based on Windows 2008, for backwards compatibility with XP dns is an alias for dnsserver, ip is an alias for ipv4
Examples:
Install ipmontr.dll:
C:\> netsh advfirewall net add helper ipmontr.dll
Export the fiewall policy:
C:\> netsh advfirewall export "c:\advfirewallpolicy.wfw"
Show TCP/IP settings
C:\> netsh interface ip show config
Set a static IP address (e.g. for a laptop)
C:\> Netsh interface ip set address name="Local Area Connection" source=static addr=192.168.0.10 mask=255.255.255.0 gateway=192.168.0.1 gwmetric=1
Set a dynamic IP address with DHCP
C:\> Netsh interface ip set address name="Local Area Connection" source=dhcp
Add multiple DNS servers:
C:\> Netsh interface ipv4 add dns "Local Area Connection" 10.0.0.1
C:\> Netsh interface ipv4 add dns "Local Area Connection" 10.0.0.3 index=2
index=2 adds the IP as a secondary dns server.
Set a static DNS server address:
C:\> Netsh interface ip set dns name="Local Area Connection" source=static addr=192.168.0.2 register=none
Set a dynamic DNS server address with DHCP:
C:\> netsh interface ip set dns name="Local Area Connection" source=dhcp
Set a static address for the WINS server:
C:\> Netsh interface ip set wins name="Local Area Connection" source=static addr=192.168.100.3
To configure WINS from DHCP:
C:\> Netsh interface ip set wins name="Local Area Connection" source=dhcp
Backup the local DHCP server configuration to a file:
C:\> netsh dump dhcp > C:\backupDHCPconfig.dat
You can use this backup file to recreate the DHCP server with Netsh .
Work against a remote machine:
C:\> netsh set machine server64
Backup the current network interface configuration to a file:
C:\> netsh dump interface > c:\backupInterfaceConfig.dat
Restore network interface configuration from a file:
C:\> netsh exec c:\backupInterfaceConfig.dat
Run Netsh from Powershell (returns a Text object you can manipulate)
PS C:\> $myFWstate=netsh firewall show state
PS C:\> $myFWstate -match "disable"
Disable Network auto-tuning (certain routers and networking devices perform better with this off.)
PS C:\> netsh interface tcp set global autotuning=disabled
Enable Network auto-tuning (certain routers and networking devices perform better with this on.)
PS C:\> netsh interface tcp set global autotuning=normal
"Once you eliminate your #1 problem, #2 gets a promotion" - Gerald Weinberg, "The Secrets of Consulting"
Related:
Netsh 2008 Technical Reference - Microsoft.com
Netsh command reference - Microsoft.com
Q242468 - How to Use the Netsh.exe Tool
Q257748 - Change from Static IP Address to DHCP with NETSH
Q140859 - Win NT TCP/IP Routing Basics
ROUTE - Manipulate network routing tables
Equivalent bash command (Linux):
NETSVC.exe (Windows 2000 Resource Kit) Command-line Service Controller. Start, Stop or Query running services.
Syntax
NETSVC \\server command servicename
Key
server The workstation or server where the service is running
servicename The Name of the service, unlike the SC command this will
accept either the DisplayName or the service name
commands:
/list Lists installed services. Omit servicename with this command.
/query Query the status of a service.
/start Start the specified service.
/stop Stop the specified service.
/pause Pause the specified service.
/continue Restart a paused service.
Arguments can be specified in any order:
NETSVC /query \\Server299 "DHCP Client"
NETSVC "DHCP Client" \\Server299 /query
Related:
SC - Service Control - Create, Create remotely, Start, Stop, Query, Delete.
NET - manage network resources
SCLIST - Display NT Services
START /HIGH - Start a specified program or command.
Svcmon - Monitor services and raise an alert if they stop. (Win 2K ResKit)
Q251192 - Create a Windows service with SC
NBTSTAT.exe Display protocol statistics and current TCP/IP connections using NBT (NetBIOS over TCP/IP).
Syntax
By Name
NBTSTAT -a Remote_host_Name [options] [interval]
By IP address
NBTSTAT -A IP_address [options] [interval]
Key
-a (adapter status) List the remote machine's name table given its name
-A (Adapter status) List the remote machine's name table given its IP address
-c (cache) List NBT's cache of remote [machine] names
and their IP addresses
-n (names) List local NetBIOS names.
-r (resolved) List names resolved by broadcast and via WINS
-R (Reload) Purge and reloads the remote cache name table
-S (Sessions) List sessions table with the destination IP addresses
-s (sessions) List sessions table converting destination IP
addresses to computer NETBIOS names.
-RR (ReleaseRefresh) Send Name Release packets to WINS and then, starts Refresh
interval Redisplay selected statistics, pausing interval seconds
between each display. Press Ctrl+C to stop redisplaying
statistics.
"I could prove God statistically" - George Gallup
Related:
IPCONFIG - IP Configuration
NETSTAT - Display networking statistics (TCP/IP)
PING - Test a network connection
TRACERT - Trace route to a remote host
Q163409 - The 16th character is a NetBIOS suffix
Q119493 - NetBIOS over TCP/IP Name Resolution
Q314053 - TCP/IP and NBT Configuration Parameters
Equivalent bash command (Linux): trace - Find the IP address of a remote host
NETSTAT.exe Display current TCP/IP network connections and protocol statistics.
Syntax
NETSTAT [options] [-p protocol] [interval]
Key
-a Display All connections and listening ports.
-e Display Ethernet statistics. (may be combined with -s)
-n Display addresses and port numbers in Numerical form.
-r Display the Routing table.
-o Display the Owning process ID associated with each connection.
-b Display the exe involved in creating each connection or listening port.*
-v Verbose - use in conjunction with -b, to display the sequence of
components involved for all executables.
-p protocol
Show only connections for the protocol specified;
may be any of: TCP, UDP, TCPv6 or UDPv6.
If used with the -s option then the following protocols
may also be specified: IP, IPv6, ICMP,or ICMPv6.
-s Display per-protocol statistics. By default, statistics are
shown for IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, and UDPv6;
(The v6 protocols are not available under 2k and NT4)
The -p option may be used to display just a subset of these.
interval Redisplay statistics, pausing interval seconds between
each display. (default=once only) Press CTRL+C to stop.
* Where available this will display the sequence of components involved in creating the connection or listening port. (Typically well-known executables which host multiple independent components.) This option will display the executable name in [ ] at the bottom, with the component it called on top, repeated until TCP/IP is reached. The -b option can be time-consuming and will fail unless you have sufficient permissions.
"Once you're on the network, you can do a command called NetStat - Network Status - and it lists all the connections to that machine. There were hackers from Denmark, Italy, Germany, Turkey, Thailand ..." - Gary McKinnon
Related Commands:
Dommon.exe - GUI Domain Monitor (W2K but works with NT)
BROWSTAT - Get domain, browser and PDC info
ROUTE - Manipulate network routing tables.
PATHPING - IP trace utility
PING - Test a network connection
Equivalent bash command (Linux): trace - Find the IP address of a remote host
NOW.exe (Resource Kit)
Display Message with current Date and Time
Syntax
NOW [message to be printed with time-stamp]
Typical output:
Mon Mar 06 14:58:48 2000 your message here
Related:
ECHO %date% - %time% - Display current the date/time on screen
DATE /t - Display or set the date
LOGTIME - Log the date and time in a file
Powershell: [DateTime]::Now or Get-Date
Timethis - Time how long it takes the system to run a command. (Win 2K ResKit)
Uptime - Time since last reboot. (Win 2K ResKit)
Equivalent bash command (Linux): date - Display or change the date & time
NSLOOKUP (TCP/IP) Lookup IP addresses on a NameServer.
Syntax
Lookup the ip address of MyHost:
NSLOOKUP [-option] MyHost
Lookup ip address of MyHost on MyNameServer:
NSLOOKUP [-option] MyHost MyNameServer
Enter "command mode":
NSLOOKUP
Command Mode options:
help or ? - print a list of Command Mode options
exit or ^C - exit "command mode"
set all - print options, current server and host
finger [USER] - finger the optional NAME at the current default host
MyHost - print ip address of MyHost
MyHost MyNameServer - print ip address of MyHost on MyNameServer
set [no]debug - print debugging info
set [no]d2 - print exhaustive debugging info
set domain=NAME - set default domain name to NAME
set root=NAME - set root server to NAME
root - set current default server to the root
server NAME - set default server to NAME, using current default server
lserver NAME - set default server to NAME, using initial server
set srchlist=N1[/N2/.../N6] - set domain to N1 and search list to N1, N2,...
set retry=X - set number of retries to X
set timeout=X - set initial time-out interval to X seconds
set [no]defname - append domain name to each query
set [no]recurse - ask for recursive answer to query
set [no]search - use domain search list
set [no]vc - always use a virtual circuit
set - set query class (for example, IN (Internet), ANY)
set [no]msxfr - use MS fast zone transfer
set ixfrver=X - current version to use in IXFR transfer request
set - set query type
set query - set query type
(e.g. A, ANY, CNAME, MX, NS, PTR, SOA, SRV)
ls [opt] DOMAIN [> FILE] - list addresses in DOMAIN
(and optionally output to FILE)
-d - list all records
-t TYPE - list records of the given Type (for example, A, CNAME,
MX, NS, PTR, and so on)
-a - list Aliases and canonical names.
view FILE - sort an 'ls' output file and view it with pg
Example:
C:\> nslookup -query -timeout=10 porttest.dns-oarc.net
Related:
NBTSTAT - Display networking statistics (NetBIOS over TCP/IP)
NETSTAT - Display networking statistics (TCP/IP)
TRACERT - Trace route to a remote host
Powershell: Get-DNS (snapin)
Q200525 - Using nslookup
network-tools.com - nslookup
NTBACKUP Backup to tape: drives, folders and the systemstate.
Syntax:
NTBACKUP backup [systemstate] "@bks file name"
/J {"job name"} [options] [/SNAP:{on|off}] [/um]
Options:
systemstate
Back up the System State data.
This will also force the backup type to normal or copy.
@bks file name
The name of the backup selection file (.bks file).
In WinXP the at (@) character must precede this name.
A backup selection file contains information on the files and folders
to be backed up.
You have to create the file using the GUI version of NT Backup.
/J {"job name"}
The job name to be used in the log file
Describe the files and folders and the backup date-time.
/P {"pool name"}
The media pool from which you want to use media.
Usually a subpool of the Backup media pool, such as 4mm DDS.
If you select this you cannot use /A, /G, /F, or /T
/G {"guid name"}
Overwrite or append to this tape.
Don't use with a media Pool (/P).
/T {"tape name"}
Overwrite or append to this tape.
Don't use with a media Pool (/P).
/A
Perform an append operation.
Either "guid name" (/G) or "tape name" (/T) must be specified with this switch.
Don't use with a media Pool (/P).
/N {"media name"}
The new tape name. Don't use with Append (/A).
/F {"file name"}
Backup to a file - logical disk path and file name.
Do not use with the switches: /P /G /T.
/D {"set description"}
Label for each backup set
/DS {"server name"}
Back up the directory service file for MS Exchange 5.5 server.
This is not needed/does not work with Exchange 2000 since Exchange 2000
uses Active Directory.
/IS {"server name"}
Back up the Information Store file for an MS Exchange 5.5 Server.
/V:{yes|no}
Verify the data after the backup is complete.
/R:{yes|no}
Restrict access to this tape to the Owner/AdministratorS
/L:{f|s|n}
The type of log file: f=full, s=summary, n=none
/M {backup type}
The backup type. One of: normal, copy, differential, incremental, or daily
/RS:{yes|no}
Backs up the migrated data files located in Remote Storage.
The /RS command-line option is not required to back up the local Removable
Storage database (that contains the Remote Storage placeholder files).
When you backup the %systemroot% folder, Backup automatically backs up the
Removable Storage database as well.
/HC:{on|off}
Use hardware compression, if available, on the tape drive.
/SNAP:{on|off}
Copy open/locked files, requires XP or 2003,
creates a temporary snapshot for the volume shadow copy.
/um (Windows 2000 only)
Find the first available media, format it, and use for the current backup.
Use with the /p switch to scan for available media pools.
This command is only for standalone tape devices (not tape loaders.)
The /UM switch must be at the end of the command line.
NTBackup has a reputation for being clumsy and unreliable, Microsoft Data Protection Manager is a more robust solution for Windows backup and recovery. Third party and cross platform tools are also available: List of backup software
NT Backup was discontinued in Windows Vista/Windows 7.
Mick Jagger sang backup vocals for "You're so Vain" by Carly Simon
Related:
Microsoft utility to restore NT Backups for Windows Vista/Server 2008
BackupAssist - 3rd party backup software for small and medium businesses
NTBackup.us - articles about NT Backup
Q814583 /Q821730 - NT Backup in Windows Server 2003
Q237310 - Manually Edit Ntbackup.exe Selection Script Files
Equivalent Linux bash command: tar - Tape ARchiver
NTRIGHTS.exe (Resource Kit, 2000/2003)
Edit user account Privileges.
Syntax
NTRIGHTS +r Right -u UserOrGroup [-m \\Computer] [-e Entry]
NTRIGHTS -r Right -u UserOrGroup [-m \\Computer] [-e Entry]
Key:
+/-r Right Grant or revoke one of the rights listed below.
-u UserOrGroup Who the rights are to be granted or revoked to.
-m \\Computer The computer (machine) on which to perform the operation.
The default is the local computer.
-e Entry Add a text string 'Entry' to the computer's event log.
Below are the Privileges that can be granted or revoked, all are Case-Sensitive.
Logon Privileges:
Log on as a batch job SeBatchLogonRight
Deny logon as a batch job SeDenyBatchLogonRight
Log on locally SeInteractiveLogonRight
Deny local logon SeDenyInteractiveLogonRight
Logon as a service SeServiceLogonRight
Deny logon as a service SeDenyServiceLogonRight
Access this Computer from the Network SeNetworkLogonRight
Deny Access to this computer from the network SeDenyNetworkLogonRight
Allow logon through Terminal Services SeRemoteInteractiveLogonRight (Not supported on Win 2000)
Deny logon through Terminal Services SeDenyRemoteInteractiveLogonRight (Not supported on Win 2000)
System Admin Privileges:
Generate security audits SeAuditPrivilege
Manage auditing and security log SeSecurityPrivilege
Backup files and directories SeBackupPrivilege
Add workstations to the domain SeMachineAccountPrivilege
Shut down the system SeShutdownPrivilege
Force shutdown from a remote system SeRemoteShutdownPrivilege
Create a pagefile SeCreatePagefilePrivilege
Increase quotas SeIncreaseQuotaPrivilege
Restore files and directories SeRestorePrivilege
Change the system time SeSystemTimePrivilege
Manage the files on a volume SeManageVolumePrivilege (Win XP only)
Take ownership of files/objects SeTakeOwnershipPrivilege
Enable computer/user accounts
to be trusted for delegation SeEnableDelegationPrivilege
Remove computer from docking station SeUndockPrivilege
Service Privileges:
Create permanent shared objects SeCreatePermanentPrivilege
Create a token object SeCreateTokenPrivilege
Replace a process-level token SeAssignPrimaryTokenPrivilege
Impersonate a client after authentication SeImpersonatePrivilege (Not supported on WinXP or earlier)
Increase scheduling priority SeIncreaseBasePriorityPrivilege
Act as part of the operating system SeTcbPrivilege
Profile a single process SeProfileSingleProcessPrivilege
Load and unload device drivers SeLoadDriverPrivilege
Lock pages in memory SeLockMemoryPrivilege
Create global objects SeCreateGlobalPrivilege (Not supported on Windows XP or earlier)
Misc Privileges:
Debug programs SeDebugPrivilege
Bypass traverse checking SeChangeNotifyPrivilege
Synch directory service data SeSyncAgentPrivilege
Edit firmware environment values SeSystemEnvironmentPrivilege
Profile system performance SeSystemProfilePrivilege
Obsolete and unused SeUnsolicitedInputPrivilege (has no effect)
To run ntrights you need to be an administrator, to change privileges remotely (-m option) you need to have administrator rights on the machine being changed.
To change permissions for a large number of users, add them to a domain workgroup and grant the privileges to the group.
The group policy editor can be used to view these privileges in a GUI.
On a Windows 2008 Server (or Vista), allowing logon through Terminal Services (SeRemoteInteractiveLogonRight) requires an extra step: Control Panel > System > 'Remote Settings' > 'Select Users' button, and then add users/groups.
Examples:
Allow all members of the local 'Users' group to logon locally
ntrights -u Users +r SeInteractiveLogonRight
Allow all members of the 'Admin_RDP' group to logon remotely via RDP to "server64", also log this security change in the event log:
ntrights -u MyDom\Admin_RDP +r SeRemoteInteractiveLogonRight -m \\server64 -e "Added RDP rights for Admin_RDP"
Allow all members of the domain group 'Admin_General' to shutdown this computer.
ntrights -u MyDom\Admin_General +r SeShutdownPrivilege
Allow the domain user 'JDoe' to shutdown the machine 'Server64'
ntrights -u MyDom\JDoe +r SeShutdownPrivilege -m \\Server64
Specifically deny local logon rights to Henry:
ntrights -u Henry +r SeDenyInteractiveLogonRight
"What distinguishes the majority of men from the few is their inability to act according to their beliefs." - Henry Miller
Related:
CACLS - Change file permissions
Q267553 - Reset User Rights in Group Policy
Q315276 - Set Logon User Rights by Using the NTRights
OPENFILES.exe
Query or display open files, disconnect files opened by network users.
Syntax
Openfiles.exe /query [/s Computer [/u Domain\User [/p Password]]]
[/fo {TABLE|LIST|CSV}] [/nh] [/v]
Openfiles.exe /disconnect [/s Computer [/u Domain\User [/p Password]]]
{[/id OpenFileID]|[/a UserName]|[/o OpenMode]} [/se SessionName] [/op OpenFileName]
Key
/s The name or IP address of a remote computer. (Do not use backslashes.) default=local computer.
/u Run the command with the account permissions of user. Default=current logged on user.
/p The password of the user account specified with /u.
/fo The format to use for the query output. Valid values are TABLE, LIST, and CSV. Default=TABLE.
/nh No column headers in the output. Valid only when /fo = TABLE or CSV.
/id Disconnect the file opened with the specified numeric OpenFileID on computer
Use openfiles.exe /query to learn the file ID.
The wildcard (*) can be used to disconnect all open files on computer.
/a Disconnect all open files that were accessed by user on computer.
The wildcard (*) can be used to disconnect all open files on computer.
/o Disconnect all open files with the specified OpenMode on the computer specified by the /s parameter.
The OpenMode parameter includes the Read/Write and Read modes.
The wildcard (*) can be used to disconnect all open files on computer.
/se Disconnect all open files that were created by the specified session on computer.
Wildcards (*) may be used. (the /se option is not available under Windows 7)
/op Disconnect the open file that was created with the specified OpenFileName on computer
The wildcard (*) can be used to disconnect all open files on computer.
/v Display verbose information in the output.
/? Help.
Administrator privileges are required to run the OPENFILES command. This can be used to detect if the current user is an Admin OPENFILES > nul will set %ERRORLEVEL% = 1 if the user is not an administrator - see this forum thread.
Running openfiles.exe from within powershell allows the output to be assigned to a variable.
Examples
PS C:\> openfiles /query
PS C:\> openfiles /query /fo table /nh
PS C:\> $file_list = openfiles /query /s Server64 /fo CSV /v /nh
C:\> openfiles /query /fo list /v
C:\> openfiles /query /s Server64 /u SS64Dom\FileAdmin /p password1
PS C:\> openfiles /disconnect /id 1
PS C:\> openfiles /disconnect /a mike
C:\> openfiles /disconnect /o read/write
C:\> openfiles /disconnect /op "c:\work\finance.xls"
C:\> openfiles /disconnect /s Server64 /u SS64Dom\FileAdmin /id 5
C:\> openfiles /disconnect /s Server64 /u SS64Dom\FileAdmin /p password1 /id *
“Love is a sudden revelation: a kiss is always a discovery” - Anon
Related:
NET FILE - Force an open file to close
PsFile - Show files opened remotely, or close an open file
PsList - List detailed information about processes
TASKLIST - List running applications and services
Equivalent bash command (Linux): inotify - file-monitoring mechanism
PATH
Display or set a search path for executable files
Syntax
PATH pathname [;pathname] [;pathname] [;pathname]...
PATH
PATH ;
Key
pathname : drive letter and/or folder
; : the command 'PATH ;' will clear the path
PATH without parameters will display the current path.
The %PATH% environment variable contains a list of folders. When a command is issued at the CMD prompt, the operating system will first look for an executable file in the current folder, if not found it will scan %PATH% to find it.
Use the PATH command to display or change the list of folders stored in the %PATH% environment variable.
To view each item on a single line use this:
for %G in ("%path:;=" "%") do @echo %G
Or in a batch file:
for %%G in ("%path:;=" "%") do @echo %%G
To add items to the current path, include %PATH% in your new setting.
For Example:
PATH=%PATH%;C:\Program Files\My Application
Note you do not need to surround each part of the path with double quotes, PATH will always treat spaces as part of the filename.
Permanent Changes
Changes made using the PATH command are NOT permanent, they apply to the current CMD prompt only and remain only until the CMD window is closed.
T o permanently change the PATH use
Control Panel, System, Environment, System Variables
Control Panel, System, Environment, User Variables
The %PATH% variable is set as both a system and user variable, the 2 values are combined to give the PATH for the currently logged in user. This is explained in full by MS Product Support Article Q100843
Be wary of using commands like SETX to modify the PATH - the User path can be edited, but the System path remains read-only for most users. If you try to delete an old value and add a new one it is very common for the 'delete' to fail and the 'add' to succeed, resulting in duplicate values being added to the path.
If you are trying to modify the path to add settings for a single application, a reasonably safe method is to use a second variable:
e.g.
SetX MYAPP "C:\Program Files\My App" -m
Now include your new variable in the path like so ...C:\Windows\system32;%MYAPP%
You can now easily change that one variable %MYAPP% at any time in the future and the PATH will reflect the new value.
For a file stored as:
C:\Program Files\Adobe\Acrobat.exe
The Drive is:
C:
The Filename is:
Acrobat.exe
The Path is:
\Program Files\Adobe\
The Pathname is:
\Program Files\Adobe\Acrobat.exe
The Full Pathname is
C:\Program Files\Adobe\Acrobat.exe
"If you do not love your job, change it. Instead of pushing paper, push ideas. Instead of sitting down, stand up and be heard. Instead of complaining, contribute. Don't get stuck in a job description" - Microsoft job advert
Related:
SET - Display, set, or remove environment variables.
PATHMAN - Resource Kit utility - modify system and user paths. Pathman can resolve duplicate characters, and can improve performance by removing duplicate paths. For details see Pathman.wri in the resource kit.
DLL Search order - SafeDllSearchMode (Win XP)
Fix Path - Bill Stewart's path utility
Powershell: DIR Env: or "$Env:path"
Equivalent bash command (Linux): env - Display, set, or remove environment variables - PATH/CDPATH/MAILPATH
PATHPING Trace route and provide network latency and packet loss for each router and link in the path. Combines the functionality of PING and TRACERT.
Syntax
PATHPING [-n] [-h max_hops] [-g host_list] [-p period]
[-q num_queries] [-w timeout] [-i IPAddress] [-4 ] [-6 ][TargetName]
Key
-g host_list - Loose source route along host-list.
-h max_hops - Maximum number of hops to search for target.
-i address - Use the specified source address.
-n - Do not resolve addresses to hostnames.
-p period - Wait period milliseconds between pings.
-q num_queries - Number of queries per hop.
-w timeout - Wait timeout milliseconds for each reply.
-P - Test for RSVP PATH connectivity.
-R - Test if each hop is RSVP aware.
-T - Test connectivity to each hop with Layer-2 priority tags.
-4 - Force using IPv4.
-6 - Force using IPv6.
Pathping is invaluable for determining which routers or subnets may be having network problems - it displays the degree of packet loss at any given router or link.
Pathping sends multiple Echo Request messages to each router between a source and destination over a period of time and computes aggregate results based on the packets returned from each router.
Pathping performs the equivalent of the tracert command by identifying which routers are on the path.
To avoid network congestion and to minimize the effect of burst losses, pings should be sent at a sufficiently slow pace (not too frequently.)
When -p is specified, pings are sent individually to each intermediate hop. When -w is specified, multiple pings can be sent in parallel. It's therefore possible to choose a Timeout parameter that is less than the wait Period * Number of hops.
Firewalls
Like tracert PathPing uses Internet Control Message Protocol (ICMP) over TCP/IP. Many firewalls will block ICMP traffic by default. If an attacker is able to forge ICMP redirect packets, he or she can alter the routing tables on the host and possibly subvert the security of the host by causing traffic to flow via a path you didn't intend.
"The path changes, so too must the traveler" - Tarek Verena
Related:
BROWSTAT - Get domain, browser and PDC info
IPCONFIG - IP Configuration
NETSTAT - Display networking statistics (TCP/IP)
PING - Test a network connection
TRACERT - Trace route to a remote host
Equivalent bash command (Linux): mtr - Network diagnostics (traceroute/ping)
PAUSE Pause the execution of a batch file
Syntax
PAUSE
Displays the message "Press any key to continue . . ."
To suppress the message use PAUSE >nul
"Advertising may be described as the science of arresting the human intelligence long enough to get money from it." - Stephen Leacock
Related:
SLEEP - Wait for x seconds
TIMEOUT - Delay that allows the user to press a key and continue immediately.
Powershell: Pause function
Equivalent bash command (Linux): read -p "press any key to continue"
PERMS.exe (Windows 2000) Display a user’s ACL access permissions for a file. Output from PERMS may be misleading in cases where a user has inherited permission through membership of a workgroup.
Syntax
PERMS [account] [path] options
Key
account : username or [domain\|computer\]username
path : name of a file or folder in any legal format
including UNC names
Wildcards are permitted.
/i : interactively logged on to the computer
where the path resides.
(rather than being connected via the network)
/s : include subfolders
Access Description
R Read file/folder.
W Write file/folder.
X Execute file.
D Delete file or folder. May be inherited from the parent folder
via 'Delete Subfolder and Files' permission.
P Change Permission.
O Take Ownership.
A General All
- No Access
* The specified user is the owner of the file or folder.
# A group the user is a member of owns the file or folder.
? Permisssions cannot be determined.
"Microsoft allowed us to change our startup screen, but we don't think we should have to ask permission every time we want to make some minor software modification. Windows is an operating system, not a religion" - Ted Waitt, Gateway Chairman
Related:
NTRIGHTS - Edit user account rights
CACLS - Display or modify Access Control Lists (ACLs) for files and folders
SHOWACL - Show file Access Control Lists (win 2000)
SUBINACL - Change an ACL's user/domain (use when the file owner has moved to a new domain)
XCACLS - Display or modify Access Control Lists (ACLs) for files and folders
Powershell Set-Acl - Set permissions
Equivalent bash command (Linux): chmod - Change access permissions
TypePerf.exe Write performance data to the command window or to a log file.To stop Typeperf, press CTRL+C.
Syntax
typeperf counter [counter ...] [options]
typeperf -cf filename [options]
typeperf -q [object] [options]
typeperf -qx [object] [options]
Key
counter The Performance counters to monitor.
-f {CSV|TSV|BIN|SQL} Output file format. Default is CSV.
-cf filename File containing performance counters to monitor, one per line.
-si [[hh:]mm:]ss Time between samples. Default is 1 second.
-o filename Path of output file or SQL database.
Default is STDOUT.
-q [object] List installed counters (no instances).
To list counters for one object,
include the object name, such as Processor.
-qx [object] List installed counters with instances.
To list counters for one object,
include the object name, such as Processor.
-sc samples Number of samples to collect. Default is
to sample until CTRL+C.
-config filename Settings file containing command options.
-s computer_name Server to monitor if no server is specified in the counter path.
-y Answer yes to all questions without prompting.
-? Display context sensitive help.
Counter is the full name of a performance counter in the format:"\\Computer\Object(Instance)\Counter"
e.g. "\\Server1\Processor(0)\% User Time".
Examples
Display % Processor time until interrupted:
C:\> typeperf "\Processor(_Total)\% Processor Time"
Gather 600 samples of % Processor time on the local computer (this will take 10 minutes):
C:\> typeperf "\processor(_Total)\% Processor Time" -O C:\SS64demo1.csv -SC 600
Gather samples of all the counters listed in counters.txt :
C:\> typeperf -cf counters.txt -si 5 -sc 50 -o C:\SS64demo2.csv
“Weekends don't count unless you spend them doing something completely pointless” - Bill Watterson
Related:
LOGMAN - Manage Performance Monitor
Powershell: New-Object System.Diagnostics.PerformanceCounter
Powershell: Get-WmiObject Win32_Process -Filter "Name='System idle process'" | Format-List Name, KernelModeTime
PING Test a network connection - if successful, ping returns the ip address.
Syntax
PING [options] destination_host
Options
-w timeout Timeout in milliseconds to wait for each reply.
-i TTL Time To Live.
-v TOS Type Of Service.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-t Ping the destination host until interrupted.
To see statistics and continue type Control-Break;
To stop type Control-C.
-l size Send buffer size.
-f Set Don't Fragment flag in packet (IPv4-only).
-r count Record route for count hops (IPv4-only).
"Ignorance is preferable to error; and he is less remote from the truth who believes nothing, than he who believes what is wrong" - Thomas Jefferson
Related Commands:
Q216783 - Keep-Alive Disconnected TS Connections
MAPISEND - Send email from the command line
RMTSHARE - Share a folder or printer
SHORTCUT - Create a windows shortcut
SHUTDOWN - Shutdown the computer/Log off a user
Equivalent bash command (Linux): vncconnect - Connect to a VNC server
MV.exe (Resource Kit)
Move File - Copy a file to another location even if the file is in use (Locked)
Syntax
MV /x /d source destination
Key
The first file name is the file to be copied and the second
the destination pathname.
/d : does not copy the file until reboot time
allows in-use files to be replaced
/x : Prevents the default action that will otherwise create a
folder called "deleted" containing a copy of the
original file.
Note that you must use a FULL pathname to each file.
The NT resource kit contains 2 versions of MV.EXE - a posix version and a Windows NT version - they are not the same!
The /d option is not available with the posix version of mv, but if you prefer, you can do a file replace at boot time by manually updating the registry (which is all MV.exe does)
Start the registry editor (regedt32.exe not regedit.exe)
Move to HKLM\SYSTEM\CurrentControlSet\Control\Session Manager
Double click on
PendingFileRenameOperations
(if it does not exist - create of type multi_str )
On the first line is the name of the new file with \??\ in front,
e.g.
\??\d:\temp\ntfs.sys
On the second line is the file to replaced with !\??\ in front,
e.g.
!\??\c:\winnt\system32\drivers\ntfs.sys
Click OK
So the complete Multi-String Data would appear like:
\??\d:\temp\ntfs.sys
!\??\c:\winnt\system32\drivers\ntfs.sys
Once the reboot is complete and the file replaced the PendingFileRenameOperations value will be deleted from the registry
"Anyone who has been to an english public school will always feel comparitively at home in prison" - Evelyn Waugh
Related:
INUSE - updated file replacement utility (may not preserve file permissions)
COPY - Copy one or more files to another location
MOVE - Move a file from one folder to another
Cachemov - Offline Files Cache Mover. (Win 2K ResKit)
Powershell: Move-Item - Move an item from one location to another (move/mv/mi)
Equivalent bash command (Linux): mv - Move or rename files or directories
NET.exe The NET Command is used to manage network resources as follows:
Manage Services
NET START, STOP, PAUSE, CONTINUE
Connect to a file/print Share (Drive Map)
NET USE
Manage file and printer shares
NET SHARE, VIEW
Manage open files and user sessions
NET FILE, SESSIONS
Manage Network Time
NET TIME
Manage Network Print jobs
NET PRINT
Security
NET ACCOUNTS, USER, GROUP, LOCALGROUP
Network Messaging
NET NAME, SEND
Help
NET HELP, HELPMSG
Network configuration
NET COMPUTER, CONFIG_WORKSTATION, CONFIG_SERVER, STATISTICS_WORKSTATION, STATISTICS_SERVER
When you use NET commands in a batch file, you can use the Y or N switch to unconditionally answer Yes or No to questions returned by the Net command
"The white man knows how to make everything but he does not know how to distribute it" - Sitting Bull
Related:
CON2PRT - Connect or disconnect a Printer
GLOBAL - Display membership of global groups
LOCAL - Display membership of local groups
MODE - Configure a system device
NETDOM - Domain Manager
OPENFILES - Query or display open files
SC - Service Control
Q149427 - Change Password from the CMD prompt
Equivalent bash commands (Linux): groups - group names a user is in, users - login names of users currently logged in
NETDOM.exe (Windows Server 2003/2008) Domain Manager - Manage Machine Accounts and Passwords. NetDom is available as part of the RSAT feature on a Windows 7 / 2008 R2 server (or by default, with the AD DS or AD LDS server roles.)
Syntax
NETDOM ADD Add a workstation or server account to the domain
NETDOM COMPUTERNAME Manage computer names
NETDOM HELP
NETDOM JOIN Join a workstation or member server to the domain
NETDOM MoveNT4BDC Rename an NT4 backup domain controller
NETDOM MOVE Move a workstation or member server to a new domain
NETDOM QUERY Query the domain for information
NETDOM TRUST Manage or verify the trust relationship between domains
NETDOM REMOVE Remove a workstation or server from the domain.
NETDOM RENAMECOMPUTER Rename a computer.
NETDOM RESETPWD Reset the machine account password for a domain controller
NETDOM RESET Reset the secure connection between a workstation and a DC
NETDOM VERIFY Verify the secure connection between a workstation and a DC
Only use the version of netdom supplied for your operating system, an older version of the NETDOM utility is included with the Windows XP Support Tools.
“Technology is ruled by two types of people: those who manage what they do not understand, and those who understand what they do not manage” - Mike Trout
Related:
Q216393 - Resetting computer accounts in Windows
NETSH (Network Shell) Configure Network Interfaces, Windows Firewall, Routing & remote access.
Syntax
NETSH [Context] [sub-Context] command
Key
The contexts and commands available vary by platform, the list below is for Windows 2008.
Use interactive mode/help (described below) to check the commands available on your machine.
= add - Add a configuration entry to a list of entries.
netsh add helper - Install the specified helper DLL
= advfirewall - Change the 'netsh advfirewall' context.
netsh advfirewall consec ? - Display a list of commands.
netsh advfirewall consec add - Add a new connection security rule.
netsh advfirewall consec delete - Delete all matching connection security rules.
netsh advfirewall consec dump - Display a configuration script.
netsh advfirewall consec set - Set new values for properties of an existing rule.
netsh advfirewall consec show - Display a specified connection security rule.
netsh advfirewall dump Create a script that contains the current configuration.
If saved to a file, this can be used to restore the configuration settings.
netsh advfirewall export path\filename - Export the current policy to the specified file.
netsh advfirewall import path\filename - Import policy from the specified file.
netsh advfirewall firewall add - Add a new inbound or outbound firewall rule.
netsh advfirewall firewall delete - Delete all matching inbound rules.
netsh advfirewall firewall dump - Display a configuration script.
netsh advfirewall firewall set - Set new values for properties of a existing rule.
netsh advfirewall firewall show - Display a specified firewall rule.
netsh advfirewall monitor delete - Delete all matching security associations.
netsh advfirewall monitor dump - Display a configuration script.
netsh advfirewall monitor show - Show all matching security associations.
netsh advfirewall reset - Reset to factory settings (Firewall=ON)
netsh advfirewall set allprofiles - Set properties in all profiles.
netsh advfirewall set currentprofile - Set properties in the active profile.
netsh advfirewall set domainprofile - Set properties in the domain profile.
netsh advfirewall set global - Set the global properties.
netsh advfirewall set privateprofile - Set properties in the private profile.
netsh advfirewall set publicprofile - Set properties in the public profile.
netsh advfirewall show allprofiles - Display properties for all profiles.
netsh advfirewall show currentprofile - Display properties for the active profile.
netsh advfirewall show domainprofile - Display properties for the domain properties.
netsh advfirewall show global - Display the global properties.
netsh advfirewall show privateprofile - Display properties for the private profile.
netsh advfirewall show publicprofile - Display properties for the public profile.
netsh advfirewall show store - Display the policy store for the current interactive session.
=bridge - Change to the 'netsh bridge' context.
netsh bridge dump - Display a configuration script.
netsh bridge install - Install the component corresponding to the current context.
netsh bridge set - Set configuration information.
netsh bridge show - Display information.
netsh bridge uninstall - Remove the component corresponding to the current context.
=delete - Delete a configuration entry from a list of entries.
netsh delete helper Remove the specified helper DLL from netsh.
Note that after a helper is removed, it is no longer supported by netsh.
=dhcpclient - Change to the 'netsh dhcpclient' context.
netsh dhcpclient list - List all the commands available.
netsh dhcpclient trace enable - Enable tracing for DHCP client and DHCP QEC.
netsh dhcpclient trace disable - Disable tracing for DHCP client and DHCP QEC.
=dump - Display a configuration script.
netsh dump - Create a script that contains the current configuration.
If saved to a file, this can be used to restore the configuration settings.
=exec - Run a script file.
exec - Load a script file and run it.
=firewall - Change to the 'netsh firewall' context.
netsh firewall add - Add firewall configuration.
netsh firewall delete - Delete firewall configuration.
netsh firewall dump - Display a configuration script.
netsh firewall reset - Reset firewall configuration to default.
netsh firewall set allowedprogram - Set firewall allowed program configuration.
netsh firewall set icmpsetting - Set firewall ICMP configuration.
netsh firewall set logging - Set firewall logging configuration.
netsh firewall set multicastbroadcastresponse - Set firewall multicast/broadcast response configuration.
netsh firewall set notifications - Set firewall notification configuration.
netsh firewall set opmode - Set firewall operational configuration.
netsh firewall set portopening - Set firewall port configuration.
netsh firewall set service - Set firewall service configuration.
netsh firewall show allowedprogram - Show firewall allowed program configuration.
netsh firewall show config - Show firewall configuration.
netsh firewall show currentprofile - Show current firewall profile.
netsh firewall show icmpsetting - Show firewall ICMP configuration.
netsh firewall show logging - Show firewall logging configuration.
netsh firewall show multicastbroadcastresponse - Show firewall multicast/broadcast response configuration.
netsh firewall show notifications - Show firewall notification configuration.
netsh firewall show opmode - Show firewall operational configuration.
netsh firewall show portopening - Show firewall port configuration.
netsh firewall show service - Show firewall service configuration.
netsh firewall show state - Show current firewall state.
=help - Display a list of netsh commands.
netsh help
=http - Change to the 'netsh http' context.
netsh http add - Add a configuration entry to a table.
netsh http delete - Delete a configuration entry from a table.
netsh http dump - Display a configuration script.
netsh http flush - Flushe internal data.
netsh http show - Display information.
=interface - Change to the 'netsh interface' context.
netsh interface 6to4 + Change to the 'netsh interface 6to4' context.
netsh interface add - Add a configuration entry to a table.
netsh interface delete - Delete a configuration entry from a table.
netsh interface dump - Display a configuration script.
netsh interface ipv4 + Change to the 'netsh interface ipv4' context.
netsh interface ipv6 + Change to the 'netsh interface ipv6' context.
netsh interface isatap + Change to the 'netsh interface isatap' context.
netsh interface portproxy + Change to the 'netsh interface portproxy' context.
netsh interface reset - Reset information.
netsh interface set - Set configuration information.
netsh interface show - Display information.
netsh interface tcp + Change to the 'netsh interface tcp' context.
netsh interface teredo + Change to the 'netsh interface teredo' context.
The following sub-contexts are available:
6to4 ipv4 ipv6 isatap portproxy tcp teredo
=ipsec - Change to the 'netsh ipsec' context.
netsh ipsec dump - Display a configuration script.
netsh ipsec dynamic add - Add policy, filter, and actions to SPD.
netsh ipsec dynamic delete - Delete policy, filter, and actions from SPD.
netsh ipsec dynamic dump - Display a configuration script.
netsh ipsec dynamic set - Modifiy policy, filter, and actions in SPD.
netsh ipsec dynamic show - Display policy, filter, and actions from SPD.
netsh ipsec static add - Create new policies and related information.
netsh ipsec static delete - Delete policies and related information.
netsh ipsec static dump - Display a configuration script.
netsh ipsec static exportpolicy - Export all the policies from the policy store.
netsh ipsec static importpolicy - Import the policies from a file to the policy store.
netsh ipsec static set - Modify existing policies and related information.
netsh ipsec static show - Display details of policies and related information.
=lan - Change to the 'netsh lan' context.
netsh lan add - Add a configuration entry to a table.
netsh lan delete - Delete a configuration entry from a table.
netsh lan dump - Display a configuration script.
netsh lan export - Save LAN profiles to XML files.
netsh lan reconnect - Reconnect on an interface.
netsh lan set - Configure settings on interfaces.
netsh lan show - Display information.
=nap - Change to the 'netsh nap' context.
netsh nap client + Change to the 'netsh nap client' context.
netsh nap dump - Display a configuration script.
netsh nap hra + Change to the 'netsh nap hra' context.
netsh nap reset - Reset configuration.
netsh nap show - Show configuration and state information.
=netio - Change to the 'netsh netio' context.
netsh netio add - Add a configuration entry to a table.
netsh netio delete - Delete a configuration entry from a table.
netsh netio dump - Display a configuration script.
netsh netio show - Display information.
=ras - Change to the 'netsh ras' context. (Remote Access Server)
netsh ras aaaa - Change to the 'netsh ras aaaa' context.
netsh ras add - Add items to a table.
netsh ras delete - Remove items from a table.
netsh ras diagnostics - Change to the 'netsh ras diagnostics' context.
netsh ras dump - Display a configuration script.
netsh ras ip - Change to the 'netsh ras ip' context.
netsh ras ipv6 - Change to the 'netsh ras ipv6' context.
netsh ras set - Set configuration information.
netsh ras show - Display information.
=rpc - Change to the 'netsh rpc' context. (RPC firewall filter)
netsh rpc add - Create an Add list of subnets.
netsh rpc delete - Create a Delete list of subnets.
netsh rpc dump - Display a configuration script.
netsh rpc filter - Change to the 'netsh rpc filter' context.
netsh rpc reset - Reset the selective binding settings to 'none' (listen on all interfaces).
netsh rpc show - Display the selective binding state for each subnet on the system.
=set - Update configuration settings on a remote machine.
netsh set machine [name=] [user=][[DomainName\]UserName] [pwd=][Password | *]
If a machine name is not specified, the local machine is used.
A username and password cannot be used to connect to the local machine.
=show - Display information.
netsh show alias - List all defined aliases.
netsh show helper - List all the top-level helpers.
=winhttp - Change to the 'netsh winhttp' context.
netsh winhttp dump - Display a configuration script.
netsh winhttp import - Import WinHTTP proxy settings.
netsh winhttp reset - Reset WinHTTP settings.
netsh winhttp set - Configure WinHTTP settings.
netsh winhttp show - Display currents settings.
=winsock - Change to the 'netsh winsock' context.
netsh winsock audit - Display a list of Winsock LSPs that have been installed and removed.
netsh winsock dump - Display a configuration script.
netsh winsock remove - Remove a Winsock LSP from the system.
netsh winsock reset - Reset the Winsock Catalog to a clean state.
netsh winsock show - Display information.
netsh - Interactive mode
In interactive mode, switch context by typing any context name: advfirewall, bridge, firewall, http, interface, ipsec.. etc
list commands with ? exit interactive mode with Quit or Exit.
To view help for any command, type the command, followed by a space and ?
The syntax on this page is based on Windows 2008, for backwards compatibility with XP dns is an alias for dnsserver, ip is an alias for ipv4
Examples:
Install ipmontr.dll:
C:\> netsh advfirewall net add helper ipmontr.dll
Export the fiewall policy:
C:\> netsh advfirewall export "c:\advfirewallpolicy.wfw"
Show TCP/IP settings
C:\> netsh interface ip show config
Set a static IP address (e.g. for a laptop)
C:\> Netsh interface ip set address name="Local Area Connection" source=static addr=192.168.0.10 mask=255.255.255.0 gateway=192.168.0.1 gwmetric=1
Set a dynamic IP address with DHCP
C:\> Netsh interface ip set address name="Local Area Connection" source=dhcp
Add multiple DNS servers:
C:\> Netsh interface ipv4 add dns "Local Area Connection" 10.0.0.1
C:\> Netsh interface ipv4 add dns "Local Area Connection" 10.0.0.3 index=2
index=2 adds the IP as a secondary dns server.
Set a static DNS server address:
C:\> Netsh interface ip set dns name="Local Area Connection" source=static addr=192.168.0.2 register=none
Set a dynamic DNS server address with DHCP:
C:\> netsh interface ip set dns name="Local Area Connection" source=dhcp
Set a static address for the WINS server:
C:\> Netsh interface ip set wins name="Local Area Connection" source=static addr=192.168.100.3
To configure WINS from DHCP:
C:\> Netsh interface ip set wins name="Local Area Connection" source=dhcp
Backup the local DHCP server configuration to a file:
C:\> netsh dump dhcp > C:\backupDHCPconfig.dat
You can use this backup file to recreate the DHCP server with Netsh .
Work against a remote machine:
C:\> netsh set machine server64
Backup the current network interface configuration to a file:
C:\> netsh dump interface > c:\backupInterfaceConfig.dat
Restore network interface configuration from a file:
C:\> netsh exec c:\backupInterfaceConfig.dat
Run Netsh from Powershell (returns a Text object you can manipulate)
PS C:\> $myFWstate=netsh firewall show state
PS C:\> $myFWstate -match "disable"
Disable Network auto-tuning (certain routers and networking devices perform better with this off.)
PS C:\> netsh interface tcp set global autotuning=disabled
Enable Network auto-tuning (certain routers and networking devices perform better with this on.)
PS C:\> netsh interface tcp set global autotuning=normal
"Once you eliminate your #1 problem, #2 gets a promotion" - Gerald Weinberg, "The Secrets of Consulting"
Related:
Netsh 2008 Technical Reference - Microsoft.com
Netsh command reference - Microsoft.com
Q242468 - How to Use the Netsh.exe Tool
Q257748 - Change from Static IP Address to DHCP with NETSH
Q140859 - Win NT TCP/IP Routing Basics
ROUTE - Manipulate network routing tables
Equivalent bash command (Linux):
NETSVC.exe (Windows 2000 Resource Kit) Command-line Service Controller. Start, Stop or Query running services.
Syntax
NETSVC \\server command servicename
Key
server The workstation or server where the service is running
servicename The Name of the service, unlike the SC command this will
accept either the DisplayName or the service name
commands:
/list Lists installed services. Omit servicename with this command.
/query Query the status of a service.
/start Start the specified service.
/stop Stop the specified service.
/pause Pause the specified service.
/continue Restart a paused service.
Arguments can be specified in any order:
NETSVC /query \\Server299 "DHCP Client"
NETSVC "DHCP Client" \\Server299 /query
Related:
SC - Service Control - Create, Create remotely, Start, Stop, Query, Delete.
NET - manage network resources
SCLIST - Display NT Services
START /HIGH - Start a specified program or command.
Svcmon - Monitor services and raise an alert if they stop. (Win 2K ResKit)
Q251192 - Create a Windows service with SC
NBTSTAT.exe Display protocol statistics and current TCP/IP connections using NBT (NetBIOS over TCP/IP).
Syntax
By Name
NBTSTAT -a Remote_host_Name [options] [interval]
By IP address
NBTSTAT -A IP_address [options] [interval]
Key
-a (adapter status) List the remote machine's name table given its name
-A (Adapter status) List the remote machine's name table given its IP address
-c (cache) List NBT's cache of remote [machine] names
and their IP addresses
-n (names) List local NetBIOS names.
-r (resolved) List names resolved by broadcast and via WINS
-R (Reload) Purge and reloads the remote cache name table
-S (Sessions) List sessions table with the destination IP addresses
-s (sessions) List sessions table converting destination IP
addresses to computer NETBIOS names.
-RR (ReleaseRefresh) Send Name Release packets to WINS and then, starts Refresh
interval Redisplay selected statistics, pausing interval seconds
between each display. Press Ctrl+C to stop redisplaying
statistics.
"I could prove God statistically" - George Gallup
Related:
IPCONFIG - IP Configuration
NETSTAT - Display networking statistics (TCP/IP)
PING - Test a network connection
TRACERT - Trace route to a remote host
Q163409 - The 16th character is a NetBIOS suffix
Q119493 - NetBIOS over TCP/IP Name Resolution
Q314053 - TCP/IP and NBT Configuration Parameters
Equivalent bash command (Linux): trace - Find the IP address of a remote host
NETSTAT.exe Display current TCP/IP network connections and protocol statistics.
Syntax
NETSTAT [options] [-p protocol] [interval]
Key
-a Display All connections and listening ports.
-e Display Ethernet statistics. (may be combined with -s)
-n Display addresses and port numbers in Numerical form.
-r Display the Routing table.
-o Display the Owning process ID associated with each connection.
-b Display the exe involved in creating each connection or listening port.*
-v Verbose - use in conjunction with -b, to display the sequence of
components involved for all executables.
-p protocol
Show only connections for the protocol specified;
may be any of: TCP, UDP, TCPv6 or UDPv6.
If used with the -s option then the following protocols
may also be specified: IP, IPv6, ICMP,or ICMPv6.
-s Display per-protocol statistics. By default, statistics are
shown for IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, and UDPv6;
(The v6 protocols are not available under 2k and NT4)
The -p option may be used to display just a subset of these.
interval Redisplay statistics, pausing interval seconds between
each display. (default=once only) Press CTRL+C to stop.
* Where available this will display the sequence of components involved in creating the connection or listening port. (Typically well-known executables which host multiple independent components.) This option will display the executable name in [ ] at the bottom, with the component it called on top, repeated until TCP/IP is reached. The -b option can be time-consuming and will fail unless you have sufficient permissions.
"Once you're on the network, you can do a command called NetStat - Network Status - and it lists all the connections to that machine. There were hackers from Denmark, Italy, Germany, Turkey, Thailand ..." - Gary McKinnon
Related Commands:
Dommon.exe - GUI Domain Monitor (W2K but works with NT)
BROWSTAT - Get domain, browser and PDC info
ROUTE - Manipulate network routing tables.
PATHPING - IP trace utility
PING - Test a network connection
Equivalent bash command (Linux): trace - Find the IP address of a remote host
NOW.exe (Resource Kit)
Display Message with current Date and Time
Syntax
NOW [message to be printed with time-stamp]
Typical output:
Mon Mar 06 14:58:48 2000 your message here
Related:
ECHO %date% - %time% - Display current the date/time on screen
DATE /t - Display or set the date
LOGTIME - Log the date and time in a file
Powershell: [DateTime]::Now or Get-Date
Timethis - Time how long it takes the system to run a command. (Win 2K ResKit)
Uptime - Time since last reboot. (Win 2K ResKit)
Equivalent bash command (Linux): date - Display or change the date & time
NSLOOKUP (TCP/IP) Lookup IP addresses on a NameServer.
Syntax
Lookup the ip address of MyHost:
NSLOOKUP [-option] MyHost
Lookup ip address of MyHost on MyNameServer:
NSLOOKUP [-option] MyHost MyNameServer
Enter "command mode":
NSLOOKUP
Command Mode options:
help or ? - print a list of Command Mode options
exit or ^C - exit "command mode"
set all - print options, current server and host
finger [USER] - finger the optional NAME at the current default host
MyHost - print ip address of MyHost
MyHost MyNameServer - print ip address of MyHost on MyNameServer
set [no]debug - print debugging info
set [no]d2 - print exhaustive debugging info
set domain=NAME - set default domain name to NAME
set root=NAME - set root server to NAME
root - set current default server to the root
server NAME - set default server to NAME, using current default server
lserver NAME - set default server to NAME, using initial server
set srchlist=N1[/N2/.../N6] - set domain to N1 and search list to N1, N2,...
set retry=X - set number of retries to X
set timeout=X - set initial time-out interval to X seconds
set [no]defname - append domain name to each query
set [no]recurse - ask for recursive answer to query
set [no]search - use domain search list
set [no]vc - always use a virtual circuit
set - set query class (for example, IN (Internet), ANY)
set [no]msxfr - use MS fast zone transfer
set ixfrver=X - current version to use in IXFR transfer request
set - set query type
set query - set query type
(e.g. A, ANY, CNAME, MX, NS, PTR, SOA, SRV)
ls [opt] DOMAIN [> FILE] - list addresses in DOMAIN
(and optionally output to FILE)
-d - list all records
-t TYPE - list records of the given Type (for example, A, CNAME,
MX, NS, PTR, and so on)
-a - list Aliases and canonical names.
view FILE - sort an 'ls' output file and view it with pg
Example:
C:\> nslookup -query -timeout=10 porttest.dns-oarc.net
Related:
NBTSTAT - Display networking statistics (NetBIOS over TCP/IP)
NETSTAT - Display networking statistics (TCP/IP)
TRACERT - Trace route to a remote host
Powershell: Get-DNS (snapin)
Q200525 - Using nslookup
network-tools.com - nslookup
NTBACKUP Backup to tape: drives, folders and the systemstate.
Syntax:
NTBACKUP backup [systemstate] "@bks file name"
/J {"job name"} [options] [/SNAP:{on|off}] [/um]
Options:
systemstate
Back up the System State data.
This will also force the backup type to normal or copy.
@bks file name
The name of the backup selection file (.bks file).
In WinXP the at (@) character must precede this name.
A backup selection file contains information on the files and folders
to be backed up.
You have to create the file using the GUI version of NT Backup.
/J {"job name"}
The job name to be used in the log file
Describe the files and folders and the backup date-time.
/P {"pool name"}
The media pool from which you want to use media.
Usually a subpool of the Backup media pool, such as 4mm DDS.
If you select this you cannot use /A, /G, /F, or /T
/G {"guid name"}
Overwrite or append to this tape.
Don't use with a media Pool (/P).
/T {"tape name"}
Overwrite or append to this tape.
Don't use with a media Pool (/P).
/A
Perform an append operation.
Either "guid name" (/G) or "tape name" (/T) must be specified with this switch.
Don't use with a media Pool (/P).
/N {"media name"}
The new tape name. Don't use with Append (/A).
/F {"file name"}
Backup to a file - logical disk path and file name.
Do not use with the switches: /P /G /T.
/D {"set description"}
Label for each backup set
/DS {"server name"}
Back up the directory service file for MS Exchange 5.5 server.
This is not needed/does not work with Exchange 2000 since Exchange 2000
uses Active Directory.
/IS {"server name"}
Back up the Information Store file for an MS Exchange 5.5 Server.
/V:{yes|no}
Verify the data after the backup is complete.
/R:{yes|no}
Restrict access to this tape to the Owner/AdministratorS
/L:{f|s|n}
The type of log file: f=full, s=summary, n=none
/M {backup type}
The backup type. One of: normal, copy, differential, incremental, or daily
/RS:{yes|no}
Backs up the migrated data files located in Remote Storage.
The /RS command-line option is not required to back up the local Removable
Storage database (that contains the Remote Storage placeholder files).
When you backup the %systemroot% folder, Backup automatically backs up the
Removable Storage database as well.
/HC:{on|off}
Use hardware compression, if available, on the tape drive.
/SNAP:{on|off}
Copy open/locked files, requires XP or 2003,
creates a temporary snapshot for the volume shadow copy.
/um (Windows 2000 only)
Find the first available media, format it, and use for the current backup.
Use with the /p switch to scan for available media pools.
This command is only for standalone tape devices (not tape loaders.)
The /UM switch must be at the end of the command line.
NTBackup has a reputation for being clumsy and unreliable, Microsoft Data Protection Manager is a more robust solution for Windows backup and recovery. Third party and cross platform tools are also available: List of backup software
NT Backup was discontinued in Windows Vista/Windows 7.
Mick Jagger sang backup vocals for "You're so Vain" by Carly Simon
Related:
Microsoft utility to restore NT Backups for Windows Vista/Server 2008
BackupAssist - 3rd party backup software for small and medium businesses
NTBackup.us - articles about NT Backup
Q814583 /Q821730 - NT Backup in Windows Server 2003
Q237310 - Manually Edit Ntbackup.exe Selection Script Files
Equivalent Linux bash command: tar - Tape ARchiver
NTRIGHTS.exe (Resource Kit, 2000/2003)
Edit user account Privileges.
Syntax
NTRIGHTS +r Right -u UserOrGroup [-m \\Computer] [-e Entry]
NTRIGHTS -r Right -u UserOrGroup [-m \\Computer] [-e Entry]
Key:
+/-r Right Grant or revoke one of the rights listed below.
-u UserOrGroup Who the rights are to be granted or revoked to.
-m \\Computer The computer (machine) on which to perform the operation.
The default is the local computer.
-e Entry Add a text string 'Entry' to the computer's event log.
Below are the Privileges that can be granted or revoked, all are Case-Sensitive.
Logon Privileges:
Log on as a batch job SeBatchLogonRight
Deny logon as a batch job SeDenyBatchLogonRight
Log on locally SeInteractiveLogonRight
Deny local logon SeDenyInteractiveLogonRight
Logon as a service SeServiceLogonRight
Deny logon as a service SeDenyServiceLogonRight
Access this Computer from the Network SeNetworkLogonRight
Deny Access to this computer from the network SeDenyNetworkLogonRight
Allow logon through Terminal Services SeRemoteInteractiveLogonRight (Not supported on Win 2000)
Deny logon through Terminal Services SeDenyRemoteInteractiveLogonRight (Not supported on Win 2000)
System Admin Privileges:
Generate security audits SeAuditPrivilege
Manage auditing and security log SeSecurityPrivilege
Backup files and directories SeBackupPrivilege
Add workstations to the domain SeMachineAccountPrivilege
Shut down the system SeShutdownPrivilege
Force shutdown from a remote system SeRemoteShutdownPrivilege
Create a pagefile SeCreatePagefilePrivilege
Increase quotas SeIncreaseQuotaPrivilege
Restore files and directories SeRestorePrivilege
Change the system time SeSystemTimePrivilege
Manage the files on a volume SeManageVolumePrivilege (Win XP only)
Take ownership of files/objects SeTakeOwnershipPrivilege
Enable computer/user accounts
to be trusted for delegation SeEnableDelegationPrivilege
Remove computer from docking station SeUndockPrivilege
Service Privileges:
Create permanent shared objects SeCreatePermanentPrivilege
Create a token object SeCreateTokenPrivilege
Replace a process-level token SeAssignPrimaryTokenPrivilege
Impersonate a client after authentication SeImpersonatePrivilege (Not supported on WinXP or earlier)
Increase scheduling priority SeIncreaseBasePriorityPrivilege
Act as part of the operating system SeTcbPrivilege
Profile a single process SeProfileSingleProcessPrivilege
Load and unload device drivers SeLoadDriverPrivilege
Lock pages in memory SeLockMemoryPrivilege
Create global objects SeCreateGlobalPrivilege (Not supported on Windows XP or earlier)
Misc Privileges:
Debug programs SeDebugPrivilege
Bypass traverse checking SeChangeNotifyPrivilege
Synch directory service data SeSyncAgentPrivilege
Edit firmware environment values SeSystemEnvironmentPrivilege
Profile system performance SeSystemProfilePrivilege
Obsolete and unused SeUnsolicitedInputPrivilege (has no effect)
To run ntrights you need to be an administrator, to change privileges remotely (-m option) you need to have administrator rights on the machine being changed.
To change permissions for a large number of users, add them to a domain workgroup and grant the privileges to the group.
The group policy editor can be used to view these privileges in a GUI.
On a Windows 2008 Server (or Vista), allowing logon through Terminal Services (SeRemoteInteractiveLogonRight) requires an extra step: Control Panel > System > 'Remote Settings' > 'Select Users' button, and then add users/groups.
Examples:
Allow all members of the local 'Users' group to logon locally
ntrights -u Users +r SeInteractiveLogonRight
Allow all members of the 'Admin_RDP' group to logon remotely via RDP to "server64", also log this security change in the event log:
ntrights -u MyDom\Admin_RDP +r SeRemoteInteractiveLogonRight -m \\server64 -e "Added RDP rights for Admin_RDP"
Allow all members of the domain group 'Admin_General' to shutdown this computer.
ntrights -u MyDom\Admin_General +r SeShutdownPrivilege
Allow the domain user 'JDoe' to shutdown the machine 'Server64'
ntrights -u MyDom\JDoe +r SeShutdownPrivilege -m \\Server64
Specifically deny local logon rights to Henry:
ntrights -u Henry +r SeDenyInteractiveLogonRight
"What distinguishes the majority of men from the few is their inability to act according to their beliefs." - Henry Miller
Related:
CACLS - Change file permissions
Q267553 - Reset User Rights in Group Policy
Q315276 - Set Logon User Rights by Using the NTRights
OPENFILES.exe
Query or display open files, disconnect files opened by network users.
Syntax
Openfiles.exe /query [/s Computer [/u Domain\User [/p Password]]]
[/fo {TABLE|LIST|CSV}] [/nh] [/v]
Openfiles.exe /disconnect [/s Computer [/u Domain\User [/p Password]]]
{[/id OpenFileID]|[/a UserName]|[/o OpenMode]} [/se SessionName] [/op OpenFileName]
Key
/s The name or IP address of a remote computer. (Do not use backslashes.) default=local computer.
/u Run the command with the account permissions of user. Default=current logged on user.
/p The password of the user account specified with /u.
/fo The format to use for the query output. Valid values are TABLE, LIST, and CSV. Default=TABLE.
/nh No column headers in the output. Valid only when /fo = TABLE or CSV.
/id Disconnect the file opened with the specified numeric OpenFileID on computer
Use openfiles.exe /query to learn the file ID.
The wildcard (*) can be used to disconnect all open files on computer.
/a Disconnect all open files that were accessed by user on computer.
The wildcard (*) can be used to disconnect all open files on computer.
/o Disconnect all open files with the specified OpenMode on the computer specified by the /s parameter.
The OpenMode parameter includes the Read/Write and Read modes.
The wildcard (*) can be used to disconnect all open files on computer.
/se Disconnect all open files that were created by the specified session on computer.
Wildcards (*) may be used. (the /se option is not available under Windows 7)
/op Disconnect the open file that was created with the specified OpenFileName on computer
The wildcard (*) can be used to disconnect all open files on computer.
/v Display verbose information in the output.
/? Help.
Administrator privileges are required to run the OPENFILES command. This can be used to detect if the current user is an Admin OPENFILES > nul will set %ERRORLEVEL% = 1 if the user is not an administrator - see this forum thread.
Running openfiles.exe from within powershell allows the output to be assigned to a variable.
Examples
PS C:\> openfiles /query
PS C:\> openfiles /query /fo table /nh
PS C:\> $file_list = openfiles /query /s Server64 /fo CSV /v /nh
C:\> openfiles /query /fo list /v
C:\> openfiles /query /s Server64 /u SS64Dom\FileAdmin /p password1
PS C:\> openfiles /disconnect /id 1
PS C:\> openfiles /disconnect /a mike
C:\> openfiles /disconnect /o read/write
C:\> openfiles /disconnect /op "c:\work\finance.xls"
C:\> openfiles /disconnect /s Server64 /u SS64Dom\FileAdmin /id 5
C:\> openfiles /disconnect /s Server64 /u SS64Dom\FileAdmin /p password1 /id *
“Love is a sudden revelation: a kiss is always a discovery” - Anon
Related:
NET FILE - Force an open file to close
PsFile - Show files opened remotely, or close an open file
PsList - List detailed information about processes
TASKLIST - List running applications and services
Equivalent bash command (Linux): inotify - file-monitoring mechanism
PATH
Display or set a search path for executable files
Syntax
PATH pathname [;pathname] [;pathname] [;pathname]...
PATH
PATH ;
Key
pathname : drive letter and/or folder
; : the command 'PATH ;' will clear the path
PATH without parameters will display the current path.
The %PATH% environment variable contains a list of folders. When a command is issued at the CMD prompt, the operating system will first look for an executable file in the current folder, if not found it will scan %PATH% to find it.
Use the PATH command to display or change the list of folders stored in the %PATH% environment variable.
To view each item on a single line use this:
for %G in ("%path:;=" "%") do @echo %G
Or in a batch file:
for %%G in ("%path:;=" "%") do @echo %%G
To add items to the current path, include %PATH% in your new setting.
For Example:
PATH=%PATH%;C:\Program Files\My Application
Note you do not need to surround each part of the path with double quotes, PATH will always treat spaces as part of the filename.
Permanent Changes
Changes made using the PATH command are NOT permanent, they apply to the current CMD prompt only and remain only until the CMD window is closed.
T o permanently change the PATH use
Control Panel, System, Environment, System Variables
Control Panel, System, Environment, User Variables
The %PATH% variable is set as both a system and user variable, the 2 values are combined to give the PATH for the currently logged in user. This is explained in full by MS Product Support Article Q100843
Be wary of using commands like SETX to modify the PATH - the User path can be edited, but the System path remains read-only for most users. If you try to delete an old value and add a new one it is very common for the 'delete' to fail and the 'add' to succeed, resulting in duplicate values being added to the path.
If you are trying to modify the path to add settings for a single application, a reasonably safe method is to use a second variable:
e.g.
SetX MYAPP "C:\Program Files\My App" -m
Now include your new variable in the path like so ...C:\Windows\system32;%MYAPP%
You can now easily change that one variable %MYAPP% at any time in the future and the PATH will reflect the new value.
- Changing a variable in the Control Panel will not affect any CMD prompt that is already open, only new CMD prompts will get the new setting.
- To change a system variable you must have administrator rights
- If your system has an AUTOEXEC.BAT file then any PATH setting in AUTOEXEC.BAT will also be appended to the %PATH% environment variable. This is to provide compatibility with old installation routines which need to set the PATH. All other commands in AUTOEXEC.BAT are ignored.
For a file stored as:
C:\Program Files\Adobe\Acrobat.exe
The Drive is:
C:
The Filename is:
Acrobat.exe
The Path is:
\Program Files\Adobe\
The Pathname is:
\Program Files\Adobe\Acrobat.exe
The Full Pathname is
C:\Program Files\Adobe\Acrobat.exe
"If you do not love your job, change it. Instead of pushing paper, push ideas. Instead of sitting down, stand up and be heard. Instead of complaining, contribute. Don't get stuck in a job description" - Microsoft job advert
Related:
SET - Display, set, or remove environment variables.
PATHMAN - Resource Kit utility - modify system and user paths. Pathman can resolve duplicate characters, and can improve performance by removing duplicate paths. For details see Pathman.wri in the resource kit.
DLL Search order - SafeDllSearchMode (Win XP)
Fix Path - Bill Stewart's path utility
Powershell: DIR Env: or "$Env:path"
Equivalent bash command (Linux): env - Display, set, or remove environment variables - PATH/CDPATH/MAILPATH
PATHPING Trace route and provide network latency and packet loss for each router and link in the path. Combines the functionality of PING and TRACERT.
Syntax
PATHPING [-n] [-h max_hops] [-g host_list] [-p period]
[-q num_queries] [-w timeout] [-i IPAddress] [-4 ] [-6 ][TargetName]
Key
-g host_list - Loose source route along host-list.
-h max_hops - Maximum number of hops to search for target.
-i address - Use the specified source address.
-n - Do not resolve addresses to hostnames.
-p period - Wait period milliseconds between pings.
-q num_queries - Number of queries per hop.
-w timeout - Wait timeout milliseconds for each reply.
-P - Test for RSVP PATH connectivity.
-R - Test if each hop is RSVP aware.
-T - Test connectivity to each hop with Layer-2 priority tags.
-4 - Force using IPv4.
-6 - Force using IPv6.
Pathping is invaluable for determining which routers or subnets may be having network problems - it displays the degree of packet loss at any given router or link.
Pathping sends multiple Echo Request messages to each router between a source and destination over a period of time and computes aggregate results based on the packets returned from each router.
Pathping performs the equivalent of the tracert command by identifying which routers are on the path.
To avoid network congestion and to minimize the effect of burst losses, pings should be sent at a sufficiently slow pace (not too frequently.)
When -p is specified, pings are sent individually to each intermediate hop. When -w is specified, multiple pings can be sent in parallel. It's therefore possible to choose a Timeout parameter that is less than the wait Period * Number of hops.
Firewalls
Like tracert PathPing uses Internet Control Message Protocol (ICMP) over TCP/IP. Many firewalls will block ICMP traffic by default. If an attacker is able to forge ICMP redirect packets, he or she can alter the routing tables on the host and possibly subvert the security of the host by causing traffic to flow via a path you didn't intend.
"The path changes, so too must the traveler" - Tarek Verena
Related:
BROWSTAT - Get domain, browser and PDC info
IPCONFIG - IP Configuration
NETSTAT - Display networking statistics (TCP/IP)
PING - Test a network connection
TRACERT - Trace route to a remote host
Equivalent bash command (Linux): mtr - Network diagnostics (traceroute/ping)
PAUSE Pause the execution of a batch file
Syntax
PAUSE
Displays the message "Press any key to continue . . ."
To suppress the message use PAUSE >nul
"Advertising may be described as the science of arresting the human intelligence long enough to get money from it." - Stephen Leacock
Related:
SLEEP - Wait for x seconds
TIMEOUT - Delay that allows the user to press a key and continue immediately.
Powershell: Pause function
Equivalent bash command (Linux): read -p "press any key to continue"
PERMS.exe (Windows 2000) Display a user’s ACL access permissions for a file. Output from PERMS may be misleading in cases where a user has inherited permission through membership of a workgroup.
Syntax
PERMS [account] [path] options
Key
account : username or [domain\|computer\]username
path : name of a file or folder in any legal format
including UNC names
Wildcards are permitted.
/i : interactively logged on to the computer
where the path resides.
(rather than being connected via the network)
/s : include subfolders
Access Description
R Read file/folder.
W Write file/folder.
X Execute file.
D Delete file or folder. May be inherited from the parent folder
via 'Delete Subfolder and Files' permission.
P Change Permission.
O Take Ownership.
A General All
- No Access
* The specified user is the owner of the file or folder.
# A group the user is a member of owns the file or folder.
? Permisssions cannot be determined.
"Microsoft allowed us to change our startup screen, but we don't think we should have to ask permission every time we want to make some minor software modification. Windows is an operating system, not a religion" - Ted Waitt, Gateway Chairman
Related:
NTRIGHTS - Edit user account rights
CACLS - Display or modify Access Control Lists (ACLs) for files and folders
SHOWACL - Show file Access Control Lists (win 2000)
SUBINACL - Change an ACL's user/domain (use when the file owner has moved to a new domain)
XCACLS - Display or modify Access Control Lists (ACLs) for files and folders
Powershell Set-Acl - Set permissions
Equivalent bash command (Linux): chmod - Change access permissions
TypePerf.exe Write performance data to the command window or to a log file.To stop Typeperf, press CTRL+C.
Syntax
typeperf counter [counter ...] [options]
typeperf -cf filename [options]
typeperf -q [object] [options]
typeperf -qx [object] [options]
Key
counter The Performance counters to monitor.
-f {CSV|TSV|BIN|SQL} Output file format. Default is CSV.
-cf filename File containing performance counters to monitor, one per line.
-si [[hh:]mm:]ss Time between samples. Default is 1 second.
-o filename Path of output file or SQL database.
Default is STDOUT.
-q [object] List installed counters (no instances).
To list counters for one object,
include the object name, such as Processor.
-qx [object] List installed counters with instances.
To list counters for one object,
include the object name, such as Processor.
-sc samples Number of samples to collect. Default is
to sample until CTRL+C.
-config filename Settings file containing command options.
-s computer_name Server to monitor if no server is specified in the counter path.
-y Answer yes to all questions without prompting.
-? Display context sensitive help.
Counter is the full name of a performance counter in the format:"\\Computer\Object(Instance)\Counter"
e.g. "\\Server1\Processor(0)\% User Time".
Examples
Display % Processor time until interrupted:
C:\> typeperf "\Processor(_Total)\% Processor Time"
Gather 600 samples of % Processor time on the local computer (this will take 10 minutes):
C:\> typeperf "\processor(_Total)\% Processor Time" -O C:\SS64demo1.csv -SC 600
Gather samples of all the counters listed in counters.txt :
C:\> typeperf -cf counters.txt -si 5 -sc 50 -o C:\SS64demo2.csv
“Weekends don't count unless you spend them doing something completely pointless” - Bill Watterson
Related:
LOGMAN - Manage Performance Monitor
Powershell: New-Object System.Diagnostics.PerformanceCounter
Powershell: Get-WmiObject Win32_Process -Filter "Name='System idle process'" | Format-List Name, KernelModeTime
PING Test a network connection - if successful, ping returns the ip address.
Syntax
PING [options] destination_host
Options
-w timeout Timeout in milliseconds to wait for each reply.
-i TTL Time To Live.
-v TOS Type Of Service.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-t Ping the destination host until interrupted.
To see statistics and continue type Control-Break;
To stop type Control-C.
-l size Send buffer size.
-f Set Don't Fragment flag in packet (IPv4-only).
-r count Record route for count hops (IPv4-only).
-s count Timestamp for count hops (IPv4-only).
-j host_list Loose source route along host_list (IPv4-only).
-k host_list Strict source route along host_list (IPv4-only).
destination_host The name of the remote host
-R Use routing header to test reverse route also (IPv6-only).
-S srcaddr Source address to use.
-4 Force using IPv4.
-6 Force using IPv6.
A response of "Request timed out" means there was no response to the ping attempt in the default time period of one second.
If the latency of the response is more than one second. Use the -w option on the ping command to increase the time-out. For example, to allow responses within five seconds, use ping -w 5000.
The IPv6 options are only available on versions of Windows that support IPv6, e.g. Windows 7 /2008
A successful PING does NOT always return an %errorlevel% == 0
Therefore to reliably detect a successful ping - pipe the output into FIND and look for the text "TTL"
Note that "Reply" in the output of PING does not always indicate a positive response. You may receive a message from a router such as: Reply from 192.168.1.254: Destination Net Unreachable.
Four steps to test an IP connection with ping:
1) Ping the loopback address to verify that TCP/IP is installed and configured correctly on the local computer.
PING 127.0.0.1
2) Ping the IP address of the local computer to verify that it was added to the network correctly.
PING IP_address_of_local_host
3) Ping the IP address of the default gateway to verify that the default gateway is functioning and that you can communicate with a local host on the local network.
PING IP_address_of_default_gateway
4) Ping the IP address of a remote host to verify that you can communicate through a router.
PING IP_address_of_remote_host
Examples
Ping a server just once:
PING -n 1 Server64
Check if a host is reachable:
PING Server64 |find "TTL=" && ECHO MyHost found
Check if a host is not reachable:
PING Server64 |find "TTL=" || ECHO MyHost not found
Test which iSCSI IP on a specific NIC is functioning or if a specific teamed NIC is operating as it should:
Ping –S (Source IP: XXX.XXX.XXX.XXX) (Destination IP: XXX.XXX.XXX.XXX)
Ping –S 10.5.7.64 10.5.7.1
Ping a website 5 times:
PING -n 5 -w 7500 www.microsoft.com
Script to monitor your connection to a website (example.com) every 15 seconds:
@Echo off
Echo Logging ping responses, press CTRL-C to stop
:start
Ping -n 1 example.com | find "TTL=" >>c:\pingtest.txt
Echo .
Ping -n 16 127.0.0.1>nul
goto start
The script above can be used to test an Internet connection, just replace example.com with your ISP's Default Gateway IP address. This represents the first physical device on the ISP's side of your connection. You can find the Default Gateway on your router status screen.
Note: some ISP’s or network admins may not appreciate you performing frequent or continual pings to their server, try not to overdo it!
PING is named after the sound that a sonar makes.
Ping response times below 10 milliseconds often have low accuracy. A time of 10 milliseconds is roughly equal to a distance of 930 Miles, travelling a straight line route at the speed of light.
“And now I see with eye serene
The very pulse of the machine.” - William Wordsworth, (She Was a Phantom of Delight)
Related:
TRACERT - Trace route to a remote host
IPCONFIG - IP Configuration
PATHPING - Route Tracing tool (Windows 2000)
Q115388 - Resolving IP Address with Leading Zero
FreePing - Freeware Windows GUI Ping
Network-Tools - Ping from any web browser
Powershell equivalent: Test-Connection - Ping one or more computers
Equivalent bash command (Linux): ping - Test a network connection
POPD Change directory back to the path/folder most recently stored by the PUSHD command.
POPD will also remove any temporary drive maps created by PUSHD
Syntax
POPD
Example
c:\Program Files> PUSHD c:\utils
c:\utils> PUSHD c:\WINNT
c:\Winnt>
c:\Winnt> POPD
c:\utils>
c:\utils> POPD
c:\Program Files>
If Command Extensions are disabled PUSHD and POPD will not create temporary drive letters.
"It's amazing how low you go to get high" - John Lennon
Related:
PUSHD - Change the current directory/folder and store the previous folder/path
CD - Change Directory, select a Folder (and drive)
Powershell: Pop-Location - Set the current working location from the stack (popd)
Equivalent bash command (Linux): popd - Remove the top entry from the directory stack
PORTQRY (Download) Port Query - Display the status of TCP and UDP ports, troubleshoot TCP/IP connectivity and security, return LDAP base query info, SMTP, POP3, IMAP4 status, enumerate SQL Server instances (UDP port 1434), Local ports, local services running (and the DLL modules loaded by each).
Portqry.exe can query a single port, a list of several ports, or a sequential range of port numbers.
Syntax
The 3 modes are listed below: Command line, Local and Interactive mode.
Command line mode:
portqry -n name_to_query [-p protocol]
[-e | -r | -o endpoint(s)]
[other options]
Command line mode options:
-n [name_to_query] IP address or name of system to query
-p [protocol] TCP or UDP or BOTH (default is TCP)
-e [endpoint] Single Port to query (valid range: 1-65535)
-r [end point range] Range of ports to query (start:end)
-o [end point order] Range of ports to query in an order (x,y,z)
-l [logfile] Output a log file
-y Overwrite existing log file without prompting
-sp [source port] Initial source port to use for query
-sl 'slow link delay' Wait longer for UDP replies from remote systems
-nr By-pass default IP address-to-name resolution
ignored unless an IP address is specified after -n
-cn Specify SNMP community name for query
ignored unless querying an SNMP port
must be delimited with !
-q 'Quiet' operation runs with no output
returns 0 if port is listening
returns 1 if port is not listening
returns 2 if port is listening or filtered
Local Mode:
Local Mode gives detailed data on local system's ports
portqry -local [-wt seconds] [-l logfile] [-v]
portqry -wpid pid [-wt seconds] [-l logfile] [-v]
portqry -wport port [-wt seconds] [-l logfile] [-v]
Local mode options:
-local Enumerate local port usage, port to process mapping,
service port usage, and list loaded modules
-wport [port_number] Watch the specified port
report when the port's connection status changes
-wpid [process_ID] Watch the specified process ID (PID)
report when the PID's connection status changes
-wt [seconds] Watch time option
specify how often to check for status changes
valid range: 1 - 1200 seconds (default = 60 secs)
-l [logfile] Log file to create
-v Verbose output
Interactive Mode:
An alternative to command line mode
portqry -i [-options]
For help with -i run portqry.exe and then type 'help' <enter>
Examples
portqry -local
portqry -local -l MyLogFile.txt -v
portqry -wpid 1272 -wt 5 -l MyLogFile.txt -y -v
portqry -wport 53 -l dnslog.txt
portqry -n myserver.com -e 25
portqry -n 10.0.0.1 -e 53 -p UDP -i
portqry -n host1.dev.reskit.com -r 21:445
portqry -n 10.0.0.1 -o 25,445,1024 -p both -sp 53
portqry -n host2 -cn !my community name! -e 161 -p udp
Notes
PortQry runs on Windows 2000 and later systems For best results run local commands in the context of local administrator.
Port to process mapping may not be available on all systems.
Defaults: TCP, port 80, no log file, slow link delay off
Hit Ctrl-C to terminate prematurely.
Related:
nslookup - Lookup IP addresses on a NameServer
PortRptr - Port Reporter, logging service for TCP/IP port usage
NETSH diag - Connect to TCP port
WMIC PORTCONNECTOR - Access Physical port
Q310099 - Description of PortQry
Q832919 - PortQry Version2
Q310456 - Use PortQry to Troubleshoot Active Directory Connectivity
Q310298 - Use PortQry to Troubleshoot MS Exchange
PowerCFG (Vista/Windows7/Server 2008)
Control power settings, configure Hibernate/Standby modes. See also the Windows XP SP2 version of PowerCfg.
Syntax
powercfg [Options]
Options
-l
-list
List the current user's power schemes (GUIDs)
-query [Scheme_GUID] [Sub_GUID]
-q [Scheme_GUID] [Sub_GUID]
Display the contents of a power scheme.
-change settingvalue
-x setting value
Modify one of the following settings in the current power scheme:
-monitor-timeout-ac minutes
-monitor-timeout-dc minutes
-disk-timeout-ac minutes
-disk-timeout-dc minutes
-standby-timeout-ac minutes
-standby-timeout-dc minutes
-hibernate-timeout-ac minutes
-hibernate-timeout-dc minutes
Setting any value to 0 will set the timeout=Never
AC settings are used when the system is on AC power. DC settings on battery power.
-changename GUID PowerSchemeName [scheme_description]
Modify the name of a power scheme and, optionally, the scheme description.
-duplicatescheme GUID [DestinationGUID]
Duplicate a power scheme. The GUID of the new scheme will be displayed.
If DestinationGUID is omitted, then a new GUID will be created for the duplicated scheme.
-delete GUID
-d GUID
Delete the power scheme with the specified GUID.
-deletesetting Sub_GUID Setting_GUID
Delete a power setting.
-setactive Scheme_GUID
-s Scheme_GUID
Make the specified power scheme active on the computer.
-getactivescheme
Retrieve the currently active power scheme.
-setacvalueindex Scheme_GUID Sub_GUID Setting_GUID SettingIndex
Set a value associated with a specified power setting while the
computer is powered by AC power. Use the -l and -q options to discover the GUIDs
SettingIndex Specifies which value in the list to set, so 3 = 3rd in the list
-setdcvalueindex Scheme_GUID Sub_GUID Setting_GUID SettingIndex
Set a value associated with a specified power setting while the
computer is powered by DC power.
SettingIndex Specifies which value in the list to set, so 3 = 3rd in the list
-hibernate [on|off]
-h [on|off]
Enable or disable the hibernate feature. Hibernate timeout is not supported on all computers.
-availablesleepstates
-a
Report the sleep states available on the computer.
Will also attempt to report reasons why sleep states are unavailable.
-devicequery query_flags
Return a list of devices that meet the specified flags:
wake_from_S1_supported – Waking the computer from a light sleep state.
wake_from_S2_supported – Waking the computer from a deeper sleep state.
wake_from_S3_supported – Waking the computer from the deepest sleep state.
wake_from_any – Support waking the computer from any sleep state.
S1_supported – Light sleep.
S2_supported – Deeper sleep.
S3_supported – Deepest sleep.
S4_supported – Hibernation.
wake_programmable – User-configurable to wake the computer from a sleep state.
wake_armed – Currently configured to wake the computer from any sleep state.
all_devices – Present in the computer.
all_devices_verbose – Verbose list of devices.
-deviceEnableWake devicename
Enable the device to wake the computer from a sleep state.
-deviceDisableWake devicename
Disable the device from waking the computer from a sleep state.
-import filename [GUID]
Import all power settings from the specified file.
filename is the path to a file generated with powercfg -export
-export filename GUID
Export a power scheme, represented by GUID, into filename.
-lastwake
Report information about the last event that woke the computer.
-energy
Create energy-report.html in the current directory, Windows7 only.
-help
-?
Display help
-aliases
Display all aliases and their corresponding GUIDs.
These may be used in place of a GUID at the command prompt
-setsecruitydescriptor [GUID|Action] SDDL
Set a security descriptor associated with a specified power setting, power scheme, or action.
Action Is one of: ActionSetActive, ActionCreate, ActionDefault
SDDL is a valid security descriptor string in SDD format.
Call powercfg -getsecuritydescriptor to see an example SDDL STRING.
-getsecuritydescriptor [GUID|Action]
Get a security descriptor associated with a specified power setting, power scheme, or action.
Action is one of: ActionSetActive, ActionCreate, ActionDefault
Powercfg must be run from an elevated command prompt.
The most common cause of problems with power saving/hibernation is an incompatible device driver, diagnose this by disabling each device in turn (with -deviceDisableWake)
When activating Power Saving across an organisation, it is important to ensure that software updates (security patches and antivirus) are not disrupted.
WSUS can be configured to install updates when workstations are available and Scheduled Tasks can be set to Wake the machine when needed.
Power scheme GUIDs
The use of GUIDs avoids any problems with internationalisation when applying Power Saving to non-english versions of Windows. The three built-in power schemes have the GUIDs listed below:
SCHEME_MAX = Power saver (Max power saving)
SCHEME_BALANCED = Balanced (Typical)
SCHEME_MIN = High performance (Min power saving)
Examples
List all Aliases:
C:\> powercfg -aliases
a1841308-3541-4fab-bc81-f71556f20b4a SCHEME_MAX
8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c SCHEME_MIN
381b4222-f694-41f0-9685-ff5bb260df2e SCHEME_BALANCED
fea3413e-7e05-4911-9a71-700331f1c294 SUB_NONE
238c9fa8-0aad-41ed-83f4-97be242c8f20 SUB_SLEEP
29f6c1db-86da-48c5-9fdb-f2b67b1f44da STANDBYIDLE
9d7815a6-7ee4-497e-8888-515a05f02364 HIBERNATEIDLE
94ac6d29-73ce-41a6-809f-6363ba21b47e HYBRIDSLEEP
d4c1d4c8-d5cc-43d3-b83e-fc51215cb04d REMOTEFILESLEEP
7516b95f-f776-4464-8c53-06167f40cc99 SUB_VIDEO
Retrieve the currently active power scheme
C:\> Powercfg -getactivescheme
Set the Monitor and disc timeouts for the current Power saver scheme
C:\> Powercfg -Change -monitor-timeout-ac 20
C:\> Powercfg -Change -disk-timeout-ac 30
Enable the mouse to wake from sleep
C:\> Powercfg -deviceEnableWake "Microsoft USB IntelliMouse Explorer"
Set the 'Power saver' scheme
C:\> Powercfg -SETACTIVE SCHEME_MAX
Create a Custom Power scheme and set it as active
Set _Custom_Power=B1234567-SS64-SS64-SS64-F00000111AAA
Powercfg -DUPLICATESCHEME SCHEME_MAX %_Custom_Power%
Powercfg -CHANGENAME %_Custom_Power% "SS64 Power Scheme "
Powercfg -SETACTIVE %_Custom_Power%
Disable the sleep button (for the users current power scheme)
For /f "tokens=2 delims=:(" %%G in ('powercfg -getActiveScheme') do (
Powercfg -setAcValueIndex %%G sub_buttons sButtonAction 0
Powercfg -setActive %%G
)
Disable the sleep button (for all available power schemes):
For /f "skip=2 tokens=2,4 delims=:()" %%G in ('powercfg -list') do (
Powercfg -setAcValueIndex %%G sub_buttons sButtonAction 0
if "%%H" == " *" Powercfg -setActive %%G
)
“The fact that you have to choose between nine different ways of turning off your computer... produces just a little bit of unhappiness every time” - Joel on Software
Related:
PowerCfg for Windows XP SP2
Q915160 - Create a Group Policy object for power schemes
Q324347 - How to use Powercfg.exe in Windows Server 2003
3rd party Power Management tools - EnergyStar.gov
PRINT
Print a file or files to a local or network printer.
Syntax
PRINT [/D:device] [pathname(s)]
Key
device : either a local printer (LPTx, COMx )
or a network printer by its sharename (\\servername\print_share)
pathname : The file or files to be printed
The default device is PRN. The values PRN and LPT1 refer to the same parallel port.
To delete a print job:
Use Control Panel, Printers (GUI) or use
NET PRINT job# /DELETE
It is possible to delete the spool .spl and .shd files from %SystemRoot%\system32\spool\PRINTERS but this should be a last resort, you may need to stop the spooler service first.
Status Messages
Most modern laser printers have a status display panel, the 'Ready' message can be changed using HP Job Language (PCL/PJL) like this:
Echo @PJL RDYMSG DISPLAY ="Ready Message" >\\server\printQ
e.g.
Echo @PJL RDYMSG DISPLAY ="Ready Printer64" >\\printserv1\printer64
It's not essential to include the word "Ready" in the ready message, but the status display has 16 characters, which is usually enough space for "Ready" plus the printer Name/Number. e.g. "Ready Printer123", "Ready Prn1234567", "Ready #123-45678" etc
Note that when a printer error or jam occurs the status message will change, so adding a printer identifier to the status display does not replace the need for a physical label. It can still be very useful when the physical label is wrong or missing.
Get a list of all printer share names for a print server: net view \\printserv1
Printing requires the Spooler service to be running
Related:
NET PRINT - View and Delete print jobs
Print to File - Configure a printer to always print to a file.
Defptr - Default Printer. (Win 2K ResKit)
PRNCNFG - Display, configure or rename a printer
WMIC PRINTER - Set printing options through WMI.
PRINTBRM - Printer Backup/Recovery/Migration
Q246868 - New TCP/IP Printing Options in the Windows Standard Port Monitor
Q234270 - Group Policies to Control Printers
HP PCL 5 Printer Language Technical Reference Manual - Full PCL Manual
Resource Kit: prncnfg.vbs, prndrvr.vbs, prnjobs.vbs, prnmngr.vbs, prnport.vbs, prnqctl.vbs, pubprn.vbs
Powershell: Out-Printer - Send the output to a printer (lp)
Equivalent bash command (Linux): printf - Format and print data
PRINTBRM.exe Print queue Backup/Recovery/Migration.
Syntax
PRINTBRM -b -s \\server_name -f file_name options
PRINTBRM -r -s \\server_name -f file_name options
PRINTBRM -q options
Key
-s server_name The unc path to the print server.
-b Back up the server to the specified file.
-r Restore the configuration in the file to the server.
-q Query the server or the backup file.
-f file_name The backup file.
-d directory Unpack the backup file to the directory (with -r),
or repack a backup file from the directory (with -b).
-o force Forces overwriting of existing objects.
-p all Publish all printers in the directory, or
-p org Publish the printers that were originally published.
-nobin Omit binary files from the backup.
-lpr2tcp Convert LPR ports to standard TCP/IP ports on restore.
-c file_name Use the specified configuration file.
-noacl Remove ACLs from print queues on restore.
In Windows 2008 PrintBRM replaces the old Win 2003 PrintMig utility, it is backwards compatible with 2003.
Get a list of all printer share names for a print server: net view \\printserv1
“Lots of people want to ride with you in the limo, but what you want is someone who will take the bus with you when the limo breaks down” - Oprah Winfrey
Related:
NET PRINT - View and Delete print jobs
PRINT - Print a text file
Q938923 - Back up and restore printers from Win Server 2003 to Win Server 2008
Equivalent bash command (Linux): printf - Format and print data
PRNCNFG.VBS (XP and .Net) Display, configure or rename a printer.
To display configuration information about a printer:
cscript prncnfg.vbs -g [-s RemoteComputer]
-p PrinterName
[-u UserName -w Password]
To configure a printer:
cscript prncnfg.vbs -t [-s RemoteComputer]
-p PrinterName [-r PortName] [-l Location]
[-m Comment] [-h ShareName] [-f SeparatorText]
[-y DataType] [-st StartTime] [-ut EndTime] [-o Priority]
[-i DefaultPriority] [{+ | -}shared] [{+ | -}direct]
[{+ | -}published] [{+ | -}hidden] [{+ | -}rawonly]
[{+ | -}queued] [{+ | -}keepprintedjobs]
[{+ | -}workoffline] [{+ | -}enabledevq]
[{+ | -}docompletefirst][{+ | -}enablebidi]
To change the name of a printer
cscript prncnfg.vbs -x [-s RemoteComputer]
-p PrinterName -z NewPrinterName
[-u UserName -w Password]
Parameters
-s RemoteComputer
The name of the remote computer that manages the printer.
-p PrinterName
The name of the printer.
-u UserName -w Password
An account with permission to connect WMI services to the computer
that hosts the printer. e.g. A member of the Administrators group.
-r PortName
The port to which the printer is connected.
If this is a parallel or a serial port, then use the ID of the port
(for example, LPT1 or COM1). If this is a TCP/IP port, then use the
port name that was specified when the port was added.
-l Location
The printer location, such as "Copier Room."
-m Comment
A comment string.
-h ShareName
The share name.
-f SeparatorText
A file that contains the text that appears on the separator page.
-y DataType
Data types that the printer can accept.
-st StartTime
Specify a time of the day after which the printer is available.
If you send a document to a printer when it is unavailable, the
document is held (spooled) until the printer becomes available.
Specify time as a 24-hour clock. e.g. 2300
-ut EndTime
Specify a time of the day after which the printer is no longer available.
-o Priority
A priority that the spooler uses to route print jobs.
A print queue with a higher priority receives all its
jobs before any queue with a lower priority.
-i DefaultPriority
The default priority assigned to each print job.
{+ | -}shared
Is this printer is shared on the network.
{+ | -}direct
Is the document to be sent directly to the printer without being spooled.
{+ | -}published
Is this printer to be published in Active Directory.
If you publish a printer, other users can search for it based on its location
and capabilities, such as color printing and stapling.
{+ | -}hidden
Reserved function.
{+ | -}rawonly
Are only raw data print jobs to be spooled on this queue.
{+ | -}queued
Do not begin to print until after the last page of the document is spooled.
The printing program is unavailable until the document has finished printing.
This option ensures that the whole document is available to the printer.
{+ | -}keepprintedjobs
Retain documents after they are printed.
Allows a user to resubmit a document to the printer from the print queue.
{+ | -}workoffline
Allow sending print jobs when computer is not connected to the network.
{+ | -}enabledevq
Print jobs that do not match the printer setup (for example, PostScript files
spooled to non-PostScript printers) should be held in the queue rather than
being printed.
{+ | -}docompletefirst
Allocate jobs to a printer as soon as thay are spooled.
If this option is disabled, the spooler always sends higher priority
jobs to their respective queues first.
You should enable this option if you want to maximize printer efficiency
at the cost of job priority.
{+ | -}enablebidi
Send bi-directional status information to the spooler.
To get online help for this .VBS Script change to the directory (CD) where
it's installed (\windows\system32) and run PRNCNFG -?
Related:
PRINT - Print a text file
CON2PRT - Connect or disconnect a Printer
NET VIEW - to view a list of printers
NET PRINT - View and Delete print jobs
PRNDRVR - Add, delete or list printer drivers.
PRNJOBS - Pause, resume, cancel, or list print jobs
PRNMNGR - Add, delete, or list printers / connections, set the default printer.
PRNPORT/PRNQCTL - Manage printer ports & printer queues.
RUNDLL32 - Install/Remove Printers (plus advanced options)
WMIC PRINTER - Set printing options through WMI.
Q246868 - New TCP/IP Printing Options in the Windows Standard Port Monitor
Add printer - .AddPrinterConnection
Add Network printer - .AddWindowsPrinterConnection
List printers - .EnumPrinterConnections
Set default printer - .SetDefaultPrinter
Equivalent bash command (Linux): lpc - Line printer control program
PRNMNGR (XP and above)
Display, add, remove or set default printer.
Syntax
PRNMNGR [-options] [-s server][-p printer_name][-m driver model]
[-r port][-u user_name][-w password]
Options
-l list printers
-a add local printer
-ac add printer connection
-g get the default printer
-t set the default printer
-d delete printer
-x delete all printers
Examples
prnmngr -a -p "printer" -m "driver" -r "lpt1:"
prnmngr -d -p "printer" -s server
prnmngr -ac -p "\\server\printer"
prnmngr -d -p "\\server\printer"
prnmngr -x -s server
prnmngr -l -s server
prnmngr -l |find "Printer name"
prnmngr -g
prnmngr -t -p "\\server\printer"
Related:
CON2PRT - Connect or disconnect a Printer
NET VIEW \\Printserver - to view a list of available printers
NET PRINT - View and Delete print jobs
PRNCNFG - Add, delete, or list printers / connections, set the default printer.
PRNDRVR - Add, delete or list printer drivers.
PRNJOBS - Pause, resume, cancel, or list print jobs
PRNPORT - Create, delete, or list TCP/IP printer ports, change port configuration.
PRNQCTL - Print a test page, pause or resume a printer, clear a printer queue.
PRINT - Print a text file
RUNDLL32 - Install/Remove Printers (plus advanced options)
WMIC PRINTER - Set printing options through WMI.
Q246868 - New TCP/IP Printing Options in the Windows Standard Port Monitor
Add printer - .AddPrinterConnection
Add Network printer - .AddWindowsPrinterConnection
List printers - .EnumPrinterConnections
Set default printer - .SetDefaultPrinter
Equivalent bash command (Linux): lpc - Line printer control program
PROMPT Change the cmd.exe command prompt.
Syntax
PROMPT [text]
Key
text : a text string.
The prompt text can be made up of normal characters and the following special codes:
$A & (Ampersand)
$B | (pipe)
$C ( (Left parenthesis)
$D Current date
$E Escape code (ASCII code 27)
$F ) (Right parenthesis)
$G > (greater-than sign)
$H Backspace (erases previous character)
$L < (less-than sign)
$M Display the remote name for Network drives
$N Current drive
$P Current drive and path
$Q = (equal sign)
$S (space)
$T Current time
$V Windows NT version number
$_ Carriage return and linefeed
$$ $ (dollar sign)
$+ Will display plus signs (+) one for each level of the PUSHD directory stack
Examples
Display the UNC path whenever you are using a network drive (mapped with NET USE)
PROMPT $M$_$P$G
Simulate an HP-UX style prompt with the computername and the current folder on separate lines:
PROMPT=$p$_%username%@%computername%:.
Restore the default prompt:
PROMPT $P$G
PROMPT is implemented as a hidden* environment variable called PROMPT: ECHO %prompt%
Knowing this you can force an over-ride of the CMD prompt for all sessions by setting a permanent environment variable with the appropriate prompt text. e.g.
SETX PROMPT $M$_$P$G
You can also create a shortcut to the command prompt like this:
CMD /K PROMPT $M$_$P$G
* In fact the prompt variable is a property of the CMD console, it's not available to Windows Explorer or any other applications, so strictly speaking is not an environment variable.
If Command Extensions are disabled the commands $M and $+ are not supported.
Related:
SETX - Set an environment variable permanently.
Powershell: Create a function called Prompt (save in Profile.ps1 to make permanent)
Equivalent bash command (Linux): variable $PROMPT_COMMAND
PsExec (part of PsTools - download PsExec) Execute a command-line process on a remote machine.
Syntax
psexec \\computer[,computer[,..] [options] command [arguments]
psexec @run_file [options] command [arguments]
Options:
computer The computer on which psexec will run command. Default = local system
To run against all computers in the current domain enter "\\*"
@run_file Run command on every computer listed in the text file specified.
command Name of the program to execute
arguments Arguments to pass (file paths must be absolute paths on the target system)
-a n,n,... Set processor affinity to n. Processors are numbered as 1,2,3,4 etc
so to run the application on CPU 2 and CPU 4, enter: "-a 2,4"
-c Copy the program (command)to the remote system for execution.
-c -f Copy even if the file already exists on the remote system.
-c -v Copy only if the file is a higher version or is newer than the remote copy.
If you omit the -c option then the application must be in the system path on the remote system.
-d Don't wait for the application to terminate.
Only use for non-interactive applications.
-e Load the user account's profile, don't use with the system account (-s)
-i Interactive - Run the program so that it interacts with the desktop on the remote system.
-l Limited - Run process as limited user. Only allow privs assigned to the Users group.
-n s Specify a timeout s seconds for connecting to the remote computer.
-p psswd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-s Run remote process in the System account.
-u user Specify a user name for login to remote computer(optional).
-w directory Set the working directory of the process (relative to the remote computer).
-x Display the UI on the Winlogon desktop (local system only).
-low, -belownormal, -abovenormal, -high or -realtime
These options will run the process at a different priority.
Psexec can also be used to start GUI applications, but in that case the GUI will appear on the remote machine.
Input is passed to the remote system when you press the enter key - typing Ctrl-C will terminate the remote process.
When you specify a username the remote process will execute in that account, and will have access to that account's network resources.
If you omit username the remote process will run in the same account from which you execute PsExec, but because the remote process is impersonating it will not have access to network resources on the remote system.
If you do specify an alternative username/password, then PsExec will send the password in clear text. This may be a security risk if unauthorized network sniffers could intercept traffic between the local and remote system.
PsExec does not require you to be an administrator of the local filesystem this can allow UserA to run commands as UserB - a Runasreplacement.
Surround any long filenames "with quotation marks"
Examples:
Launch an interactive command prompt on \\workstation64, the CMD prompt window will appear locally:
psexec \\workstation64 cmd
Execute IpConfig on the remote system, and display the output locally:
psexec \\workstation64 ipconfig /all
Copy the program test.exe to the remote system and execute it interactively:
psexec \\workstation64 -c test.exe
Execute a program that is already installed on the remote system:
psexec \\workstation64 "c:\Program Files\test.exe"
-j host_list Loose source route along host_list (IPv4-only).
-k host_list Strict source route along host_list (IPv4-only).
destination_host The name of the remote host
-R Use routing header to test reverse route also (IPv6-only).
-S srcaddr Source address to use.
-4 Force using IPv4.
-6 Force using IPv6.
A response of "Request timed out" means there was no response to the ping attempt in the default time period of one second.
If the latency of the response is more than one second. Use the -w option on the ping command to increase the time-out. For example, to allow responses within five seconds, use ping -w 5000.
The IPv6 options are only available on versions of Windows that support IPv6, e.g. Windows 7 /2008
A successful PING does NOT always return an %errorlevel% == 0
Therefore to reliably detect a successful ping - pipe the output into FIND and look for the text "TTL"
Note that "Reply" in the output of PING does not always indicate a positive response. You may receive a message from a router such as: Reply from 192.168.1.254: Destination Net Unreachable.
Four steps to test an IP connection with ping:
1) Ping the loopback address to verify that TCP/IP is installed and configured correctly on the local computer.
PING 127.0.0.1
2) Ping the IP address of the local computer to verify that it was added to the network correctly.
PING IP_address_of_local_host
3) Ping the IP address of the default gateway to verify that the default gateway is functioning and that you can communicate with a local host on the local network.
PING IP_address_of_default_gateway
4) Ping the IP address of a remote host to verify that you can communicate through a router.
PING IP_address_of_remote_host
Examples
Ping a server just once:
PING -n 1 Server64
Check if a host is reachable:
PING Server64 |find "TTL=" && ECHO MyHost found
Check if a host is not reachable:
PING Server64 |find "TTL=" || ECHO MyHost not found
Test which iSCSI IP on a specific NIC is functioning or if a specific teamed NIC is operating as it should:
Ping –S (Source IP: XXX.XXX.XXX.XXX) (Destination IP: XXX.XXX.XXX.XXX)
Ping –S 10.5.7.64 10.5.7.1
Ping a website 5 times:
PING -n 5 -w 7500 www.microsoft.com
Script to monitor your connection to a website (example.com) every 15 seconds:
@Echo off
Echo Logging ping responses, press CTRL-C to stop
:start
Ping -n 1 example.com | find "TTL=" >>c:\pingtest.txt
Echo .
Ping -n 16 127.0.0.1>nul
goto start
The script above can be used to test an Internet connection, just replace example.com with your ISP's Default Gateway IP address. This represents the first physical device on the ISP's side of your connection. You can find the Default Gateway on your router status screen.
Note: some ISP’s or network admins may not appreciate you performing frequent or continual pings to their server, try not to overdo it!
PING is named after the sound that a sonar makes.
Ping response times below 10 milliseconds often have low accuracy. A time of 10 milliseconds is roughly equal to a distance of 930 Miles, travelling a straight line route at the speed of light.
“And now I see with eye serene
The very pulse of the machine.” - William Wordsworth, (She Was a Phantom of Delight)
Related:
TRACERT - Trace route to a remote host
IPCONFIG - IP Configuration
PATHPING - Route Tracing tool (Windows 2000)
Q115388 - Resolving IP Address with Leading Zero
FreePing - Freeware Windows GUI Ping
Network-Tools - Ping from any web browser
Powershell equivalent: Test-Connection - Ping one or more computers
Equivalent bash command (Linux): ping - Test a network connection
POPD Change directory back to the path/folder most recently stored by the PUSHD command.
POPD will also remove any temporary drive maps created by PUSHD
Syntax
POPD
Example
c:\Program Files> PUSHD c:\utils
c:\utils> PUSHD c:\WINNT
c:\Winnt>
c:\Winnt> POPD
c:\utils>
c:\utils> POPD
c:\Program Files>
If Command Extensions are disabled PUSHD and POPD will not create temporary drive letters.
"It's amazing how low you go to get high" - John Lennon
Related:
PUSHD - Change the current directory/folder and store the previous folder/path
CD - Change Directory, select a Folder (and drive)
Powershell: Pop-Location - Set the current working location from the stack (popd)
Equivalent bash command (Linux): popd - Remove the top entry from the directory stack
PORTQRY (Download) Port Query - Display the status of TCP and UDP ports, troubleshoot TCP/IP connectivity and security, return LDAP base query info, SMTP, POP3, IMAP4 status, enumerate SQL Server instances (UDP port 1434), Local ports, local services running (and the DLL modules loaded by each).
Portqry.exe can query a single port, a list of several ports, or a sequential range of port numbers.
Syntax
The 3 modes are listed below: Command line, Local and Interactive mode.
Command line mode:
portqry -n name_to_query [-p protocol]
[-e | -r | -o endpoint(s)]
[other options]
Command line mode options:
-n [name_to_query] IP address or name of system to query
-p [protocol] TCP or UDP or BOTH (default is TCP)
-e [endpoint] Single Port to query (valid range: 1-65535)
-r [end point range] Range of ports to query (start:end)
-o [end point order] Range of ports to query in an order (x,y,z)
-l [logfile] Output a log file
-y Overwrite existing log file without prompting
-sp [source port] Initial source port to use for query
-sl 'slow link delay' Wait longer for UDP replies from remote systems
-nr By-pass default IP address-to-name resolution
ignored unless an IP address is specified after -n
-cn Specify SNMP community name for query
ignored unless querying an SNMP port
must be delimited with !
-q 'Quiet' operation runs with no output
returns 0 if port is listening
returns 1 if port is not listening
returns 2 if port is listening or filtered
Local Mode:
Local Mode gives detailed data on local system's ports
portqry -local [-wt seconds] [-l logfile] [-v]
portqry -wpid pid [-wt seconds] [-l logfile] [-v]
portqry -wport port [-wt seconds] [-l logfile] [-v]
Local mode options:
-local Enumerate local port usage, port to process mapping,
service port usage, and list loaded modules
-wport [port_number] Watch the specified port
report when the port's connection status changes
-wpid [process_ID] Watch the specified process ID (PID)
report when the PID's connection status changes
-wt [seconds] Watch time option
specify how often to check for status changes
valid range: 1 - 1200 seconds (default = 60 secs)
-l [logfile] Log file to create
-v Verbose output
Interactive Mode:
An alternative to command line mode
portqry -i [-options]
For help with -i run portqry.exe and then type 'help' <enter>
Examples
portqry -local
portqry -local -l MyLogFile.txt -v
portqry -wpid 1272 -wt 5 -l MyLogFile.txt -y -v
portqry -wport 53 -l dnslog.txt
portqry -n myserver.com -e 25
portqry -n 10.0.0.1 -e 53 -p UDP -i
portqry -n host1.dev.reskit.com -r 21:445
portqry -n 10.0.0.1 -o 25,445,1024 -p both -sp 53
portqry -n host2 -cn !my community name! -e 161 -p udp
Notes
PortQry runs on Windows 2000 and later systems For best results run local commands in the context of local administrator.
Port to process mapping may not be available on all systems.
Defaults: TCP, port 80, no log file, slow link delay off
Hit Ctrl-C to terminate prematurely.
Related:
nslookup - Lookup IP addresses on a NameServer
PortRptr - Port Reporter, logging service for TCP/IP port usage
NETSH diag - Connect to TCP port
WMIC PORTCONNECTOR - Access Physical port
Q310099 - Description of PortQry
Q832919 - PortQry Version2
Q310456 - Use PortQry to Troubleshoot Active Directory Connectivity
Q310298 - Use PortQry to Troubleshoot MS Exchange
PowerCFG (Vista/Windows7/Server 2008)
Control power settings, configure Hibernate/Standby modes. See also the Windows XP SP2 version of PowerCfg.
Syntax
powercfg [Options]
Options
-l
-list
List the current user's power schemes (GUIDs)
-query [Scheme_GUID] [Sub_GUID]
-q [Scheme_GUID] [Sub_GUID]
Display the contents of a power scheme.
-change settingvalue
-x setting value
Modify one of the following settings in the current power scheme:
-monitor-timeout-ac minutes
-monitor-timeout-dc minutes
-disk-timeout-ac minutes
-disk-timeout-dc minutes
-standby-timeout-ac minutes
-standby-timeout-dc minutes
-hibernate-timeout-ac minutes
-hibernate-timeout-dc minutes
Setting any value to 0 will set the timeout=Never
AC settings are used when the system is on AC power. DC settings on battery power.
-changename GUID PowerSchemeName [scheme_description]
Modify the name of a power scheme and, optionally, the scheme description.
-duplicatescheme GUID [DestinationGUID]
Duplicate a power scheme. The GUID of the new scheme will be displayed.
If DestinationGUID is omitted, then a new GUID will be created for the duplicated scheme.
-delete GUID
-d GUID
Delete the power scheme with the specified GUID.
-deletesetting Sub_GUID Setting_GUID
Delete a power setting.
-setactive Scheme_GUID
-s Scheme_GUID
Make the specified power scheme active on the computer.
-getactivescheme
Retrieve the currently active power scheme.
-setacvalueindex Scheme_GUID Sub_GUID Setting_GUID SettingIndex
Set a value associated with a specified power setting while the
computer is powered by AC power. Use the -l and -q options to discover the GUIDs
SettingIndex Specifies which value in the list to set, so 3 = 3rd in the list
-setdcvalueindex Scheme_GUID Sub_GUID Setting_GUID SettingIndex
Set a value associated with a specified power setting while the
computer is powered by DC power.
SettingIndex Specifies which value in the list to set, so 3 = 3rd in the list
-hibernate [on|off]
-h [on|off]
Enable or disable the hibernate feature. Hibernate timeout is not supported on all computers.
-availablesleepstates
-a
Report the sleep states available on the computer.
Will also attempt to report reasons why sleep states are unavailable.
-devicequery query_flags
Return a list of devices that meet the specified flags:
wake_from_S1_supported – Waking the computer from a light sleep state.
wake_from_S2_supported – Waking the computer from a deeper sleep state.
wake_from_S3_supported – Waking the computer from the deepest sleep state.
wake_from_any – Support waking the computer from any sleep state.
S1_supported – Light sleep.
S2_supported – Deeper sleep.
S3_supported – Deepest sleep.
S4_supported – Hibernation.
wake_programmable – User-configurable to wake the computer from a sleep state.
wake_armed – Currently configured to wake the computer from any sleep state.
all_devices – Present in the computer.
all_devices_verbose – Verbose list of devices.
-deviceEnableWake devicename
Enable the device to wake the computer from a sleep state.
-deviceDisableWake devicename
Disable the device from waking the computer from a sleep state.
-import filename [GUID]
Import all power settings from the specified file.
filename is the path to a file generated with powercfg -export
-export filename GUID
Export a power scheme, represented by GUID, into filename.
-lastwake
Report information about the last event that woke the computer.
-energy
Create energy-report.html in the current directory, Windows7 only.
-help
-?
Display help
-aliases
Display all aliases and their corresponding GUIDs.
These may be used in place of a GUID at the command prompt
-setsecruitydescriptor [GUID|Action] SDDL
Set a security descriptor associated with a specified power setting, power scheme, or action.
Action Is one of: ActionSetActive, ActionCreate, ActionDefault
SDDL is a valid security descriptor string in SDD format.
Call powercfg -getsecuritydescriptor to see an example SDDL STRING.
-getsecuritydescriptor [GUID|Action]
Get a security descriptor associated with a specified power setting, power scheme, or action.
Action is one of: ActionSetActive, ActionCreate, ActionDefault
Powercfg must be run from an elevated command prompt.
The most common cause of problems with power saving/hibernation is an incompatible device driver, diagnose this by disabling each device in turn (with -deviceDisableWake)
When activating Power Saving across an organisation, it is important to ensure that software updates (security patches and antivirus) are not disrupted.
WSUS can be configured to install updates when workstations are available and Scheduled Tasks can be set to Wake the machine when needed.
Power scheme GUIDs
The use of GUIDs avoids any problems with internationalisation when applying Power Saving to non-english versions of Windows. The three built-in power schemes have the GUIDs listed below:
SCHEME_MAX = Power saver (Max power saving)
SCHEME_BALANCED = Balanced (Typical)
SCHEME_MIN = High performance (Min power saving)
Examples
List all Aliases:
C:\> powercfg -aliases
a1841308-3541-4fab-bc81-f71556f20b4a SCHEME_MAX
8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c SCHEME_MIN
381b4222-f694-41f0-9685-ff5bb260df2e SCHEME_BALANCED
fea3413e-7e05-4911-9a71-700331f1c294 SUB_NONE
238c9fa8-0aad-41ed-83f4-97be242c8f20 SUB_SLEEP
29f6c1db-86da-48c5-9fdb-f2b67b1f44da STANDBYIDLE
9d7815a6-7ee4-497e-8888-515a05f02364 HIBERNATEIDLE
94ac6d29-73ce-41a6-809f-6363ba21b47e HYBRIDSLEEP
d4c1d4c8-d5cc-43d3-b83e-fc51215cb04d REMOTEFILESLEEP
7516b95f-f776-4464-8c53-06167f40cc99 SUB_VIDEO
Retrieve the currently active power scheme
C:\> Powercfg -getactivescheme
Set the Monitor and disc timeouts for the current Power saver scheme
C:\> Powercfg -Change -monitor-timeout-ac 20
C:\> Powercfg -Change -disk-timeout-ac 30
Enable the mouse to wake from sleep
C:\> Powercfg -deviceEnableWake "Microsoft USB IntelliMouse Explorer"
Set the 'Power saver' scheme
C:\> Powercfg -SETACTIVE SCHEME_MAX
Create a Custom Power scheme and set it as active
Set _Custom_Power=B1234567-SS64-SS64-SS64-F00000111AAA
Powercfg -DUPLICATESCHEME SCHEME_MAX %_Custom_Power%
Powercfg -CHANGENAME %_Custom_Power% "SS64 Power Scheme "
Powercfg -SETACTIVE %_Custom_Power%
Disable the sleep button (for the users current power scheme)
For /f "tokens=2 delims=:(" %%G in ('powercfg -getActiveScheme') do (
Powercfg -setAcValueIndex %%G sub_buttons sButtonAction 0
Powercfg -setActive %%G
)
Disable the sleep button (for all available power schemes):
For /f "skip=2 tokens=2,4 delims=:()" %%G in ('powercfg -list') do (
Powercfg -setAcValueIndex %%G sub_buttons sButtonAction 0
if "%%H" == " *" Powercfg -setActive %%G
)
“The fact that you have to choose between nine different ways of turning off your computer... produces just a little bit of unhappiness every time” - Joel on Software
Related:
PowerCfg for Windows XP SP2
Q915160 - Create a Group Policy object for power schemes
Q324347 - How to use Powercfg.exe in Windows Server 2003
3rd party Power Management tools - EnergyStar.gov
Print a file or files to a local or network printer.
Syntax
PRINT [/D:device] [pathname(s)]
Key
device : either a local printer (LPTx, COMx )
or a network printer by its sharename (\\servername\print_share)
pathname : The file or files to be printed
The default device is PRN. The values PRN and LPT1 refer to the same parallel port.
To delete a print job:
Use Control Panel, Printers (GUI) or use
NET PRINT job# /DELETE
It is possible to delete the spool .spl and .shd files from %SystemRoot%\system32\spool\PRINTERS but this should be a last resort, you may need to stop the spooler service first.
Status Messages
Most modern laser printers have a status display panel, the 'Ready' message can be changed using HP Job Language (PCL/PJL) like this:
Echo @PJL RDYMSG DISPLAY ="Ready Message" >\\server\printQ
e.g.
Echo @PJL RDYMSG DISPLAY ="Ready Printer64" >\\printserv1\printer64
It's not essential to include the word "Ready" in the ready message, but the status display has 16 characters, which is usually enough space for "Ready" plus the printer Name/Number. e.g. "Ready Printer123", "Ready Prn1234567", "Ready #123-45678" etc
Note that when a printer error or jam occurs the status message will change, so adding a printer identifier to the status display does not replace the need for a physical label. It can still be very useful when the physical label is wrong or missing.
Get a list of all printer share names for a print server: net view \\printserv1
Printing requires the Spooler service to be running
Related:
NET PRINT - View and Delete print jobs
Print to File - Configure a printer to always print to a file.
Defptr - Default Printer. (Win 2K ResKit)
PRNCNFG - Display, configure or rename a printer
WMIC PRINTER - Set printing options through WMI.
PRINTBRM - Printer Backup/Recovery/Migration
Q246868 - New TCP/IP Printing Options in the Windows Standard Port Monitor
Q234270 - Group Policies to Control Printers
HP PCL 5 Printer Language Technical Reference Manual - Full PCL Manual
Resource Kit: prncnfg.vbs, prndrvr.vbs, prnjobs.vbs, prnmngr.vbs, prnport.vbs, prnqctl.vbs, pubprn.vbs
Powershell: Out-Printer - Send the output to a printer (lp)
Equivalent bash command (Linux): printf - Format and print data
PRINTBRM.exe Print queue Backup/Recovery/Migration.
Syntax
PRINTBRM -b -s \\server_name -f file_name options
PRINTBRM -r -s \\server_name -f file_name options
PRINTBRM -q options
Key
-s server_name The unc path to the print server.
-b Back up the server to the specified file.
-r Restore the configuration in the file to the server.
-q Query the server or the backup file.
-f file_name The backup file.
-d directory Unpack the backup file to the directory (with -r),
or repack a backup file from the directory (with -b).
-o force Forces overwriting of existing objects.
-p all Publish all printers in the directory, or
-p org Publish the printers that were originally published.
-nobin Omit binary files from the backup.
-lpr2tcp Convert LPR ports to standard TCP/IP ports on restore.
-c file_name Use the specified configuration file.
-noacl Remove ACLs from print queues on restore.
In Windows 2008 PrintBRM replaces the old Win 2003 PrintMig utility, it is backwards compatible with 2003.
Get a list of all printer share names for a print server: net view \\printserv1
“Lots of people want to ride with you in the limo, but what you want is someone who will take the bus with you when the limo breaks down” - Oprah Winfrey
Related:
NET PRINT - View and Delete print jobs
PRINT - Print a text file
Q938923 - Back up and restore printers from Win Server 2003 to Win Server 2008
Equivalent bash command (Linux): printf - Format and print data
PRNCNFG.VBS (XP and .Net) Display, configure or rename a printer.
To display configuration information about a printer:
cscript prncnfg.vbs -g [-s RemoteComputer]
-p PrinterName
[-u UserName -w Password]
To configure a printer:
cscript prncnfg.vbs -t [-s RemoteComputer]
-p PrinterName [-r PortName] [-l Location]
[-m Comment] [-h ShareName] [-f SeparatorText]
[-y DataType] [-st StartTime] [-ut EndTime] [-o Priority]
[-i DefaultPriority] [{+ | -}shared] [{+ | -}direct]
[{+ | -}published] [{+ | -}hidden] [{+ | -}rawonly]
[{+ | -}queued] [{+ | -}keepprintedjobs]
[{+ | -}workoffline] [{+ | -}enabledevq]
[{+ | -}docompletefirst][{+ | -}enablebidi]
To change the name of a printer
cscript prncnfg.vbs -x [-s RemoteComputer]
-p PrinterName -z NewPrinterName
[-u UserName -w Password]
Parameters
-s RemoteComputer
The name of the remote computer that manages the printer.
-p PrinterName
The name of the printer.
-u UserName -w Password
An account with permission to connect WMI services to the computer
that hosts the printer. e.g. A member of the Administrators group.
-r PortName
The port to which the printer is connected.
If this is a parallel or a serial port, then use the ID of the port
(for example, LPT1 or COM1). If this is a TCP/IP port, then use the
port name that was specified when the port was added.
-l Location
The printer location, such as "Copier Room."
-m Comment
A comment string.
-h ShareName
The share name.
-f SeparatorText
A file that contains the text that appears on the separator page.
-y DataType
Data types that the printer can accept.
-st StartTime
Specify a time of the day after which the printer is available.
If you send a document to a printer when it is unavailable, the
document is held (spooled) until the printer becomes available.
Specify time as a 24-hour clock. e.g. 2300
-ut EndTime
Specify a time of the day after which the printer is no longer available.
-o Priority
A priority that the spooler uses to route print jobs.
A print queue with a higher priority receives all its
jobs before any queue with a lower priority.
-i DefaultPriority
The default priority assigned to each print job.
{+ | -}shared
Is this printer is shared on the network.
{+ | -}direct
Is the document to be sent directly to the printer without being spooled.
{+ | -}published
Is this printer to be published in Active Directory.
If you publish a printer, other users can search for it based on its location
and capabilities, such as color printing and stapling.
{+ | -}hidden
Reserved function.
{+ | -}rawonly
Are only raw data print jobs to be spooled on this queue.
{+ | -}queued
Do not begin to print until after the last page of the document is spooled.
The printing program is unavailable until the document has finished printing.
This option ensures that the whole document is available to the printer.
{+ | -}keepprintedjobs
Retain documents after they are printed.
Allows a user to resubmit a document to the printer from the print queue.
{+ | -}workoffline
Allow sending print jobs when computer is not connected to the network.
{+ | -}enabledevq
Print jobs that do not match the printer setup (for example, PostScript files
spooled to non-PostScript printers) should be held in the queue rather than
being printed.
{+ | -}docompletefirst
Allocate jobs to a printer as soon as thay are spooled.
If this option is disabled, the spooler always sends higher priority
jobs to their respective queues first.
You should enable this option if you want to maximize printer efficiency
at the cost of job priority.
{+ | -}enablebidi
Send bi-directional status information to the spooler.
To get online help for this .VBS Script change to the directory (CD) where
it's installed (\windows\system32) and run PRNCNFG -?
Related:
PRINT - Print a text file
CON2PRT - Connect or disconnect a Printer
NET VIEW - to view a list of printers
NET PRINT - View and Delete print jobs
PRNDRVR - Add, delete or list printer drivers.
PRNJOBS - Pause, resume, cancel, or list print jobs
PRNMNGR - Add, delete, or list printers / connections, set the default printer.
PRNPORT/PRNQCTL - Manage printer ports & printer queues.
RUNDLL32 - Install/Remove Printers (plus advanced options)
WMIC PRINTER - Set printing options through WMI.
Q246868 - New TCP/IP Printing Options in the Windows Standard Port Monitor
Add printer - .AddPrinterConnection
Add Network printer - .AddWindowsPrinterConnection
List printers - .EnumPrinterConnections
Set default printer - .SetDefaultPrinter
Equivalent bash command (Linux): lpc - Line printer control program
PRNMNGR (XP and above)
Display, add, remove or set default printer.
Syntax
PRNMNGR [-options] [-s server][-p printer_name][-m driver model]
[-r port][-u user_name][-w password]
Options
-l list printers
-a add local printer
-ac add printer connection
-g get the default printer
-t set the default printer
-d delete printer
-x delete all printers
Examples
prnmngr -a -p "printer" -m "driver" -r "lpt1:"
prnmngr -d -p "printer" -s server
prnmngr -ac -p "\\server\printer"
prnmngr -d -p "\\server\printer"
prnmngr -x -s server
prnmngr -l -s server
prnmngr -l |find "Printer name"
prnmngr -g
prnmngr -t -p "\\server\printer"
Related:
CON2PRT - Connect or disconnect a Printer
NET VIEW \\Printserver - to view a list of available printers
NET PRINT - View and Delete print jobs
PRNCNFG - Add, delete, or list printers / connections, set the default printer.
PRNDRVR - Add, delete or list printer drivers.
PRNJOBS - Pause, resume, cancel, or list print jobs
PRNPORT - Create, delete, or list TCP/IP printer ports, change port configuration.
PRNQCTL - Print a test page, pause or resume a printer, clear a printer queue.
PRINT - Print a text file
RUNDLL32 - Install/Remove Printers (plus advanced options)
WMIC PRINTER - Set printing options through WMI.
Q246868 - New TCP/IP Printing Options in the Windows Standard Port Monitor
Add printer - .AddPrinterConnection
Add Network printer - .AddWindowsPrinterConnection
List printers - .EnumPrinterConnections
Set default printer - .SetDefaultPrinter
Equivalent bash command (Linux): lpc - Line printer control program
PROMPT Change the cmd.exe command prompt.
Syntax
PROMPT [text]
Key
text : a text string.
The prompt text can be made up of normal characters and the following special codes:
$A & (Ampersand)
$B | (pipe)
$C ( (Left parenthesis)
$D Current date
$E Escape code (ASCII code 27)
$F ) (Right parenthesis)
$G > (greater-than sign)
$H Backspace (erases previous character)
$L < (less-than sign)
$M Display the remote name for Network drives
$N Current drive
$P Current drive and path
$Q = (equal sign)
$S (space)
$T Current time
$V Windows NT version number
$_ Carriage return and linefeed
$$ $ (dollar sign)
$+ Will display plus signs (+) one for each level of the PUSHD directory stack
Examples
Display the UNC path whenever you are using a network drive (mapped with NET USE)
PROMPT $M$_$P$G
Simulate an HP-UX style prompt with the computername and the current folder on separate lines:
PROMPT=$p$_%username%@%computername%:.
Restore the default prompt:
PROMPT $P$G
PROMPT is implemented as a hidden* environment variable called PROMPT: ECHO %prompt%
Knowing this you can force an over-ride of the CMD prompt for all sessions by setting a permanent environment variable with the appropriate prompt text. e.g.
SETX PROMPT $M$_$P$G
You can also create a shortcut to the command prompt like this:
CMD /K PROMPT $M$_$P$G
* In fact the prompt variable is a property of the CMD console, it's not available to Windows Explorer or any other applications, so strictly speaking is not an environment variable.
If Command Extensions are disabled the commands $M and $+ are not supported.
Related:
SETX - Set an environment variable permanently.
Powershell: Create a function called Prompt (save in Profile.ps1 to make permanent)
Equivalent bash command (Linux): variable $PROMPT_COMMAND
PsExec (part of PsTools - download PsExec) Execute a command-line process on a remote machine.
Syntax
psexec \\computer[,computer[,..] [options] command [arguments]
psexec @run_file [options] command [arguments]
Options:
computer The computer on which psexec will run command. Default = local system
To run against all computers in the current domain enter "\\*"
@run_file Run command on every computer listed in the text file specified.
command Name of the program to execute
arguments Arguments to pass (file paths must be absolute paths on the target system)
-a n,n,... Set processor affinity to n. Processors are numbered as 1,2,3,4 etc
so to run the application on CPU 2 and CPU 4, enter: "-a 2,4"
-c Copy the program (command)to the remote system for execution.
-c -f Copy even if the file already exists on the remote system.
-c -v Copy only if the file is a higher version or is newer than the remote copy.
If you omit the -c option then the application must be in the system path on the remote system.
-d Don't wait for the application to terminate.
Only use for non-interactive applications.
-e Load the user account's profile, don't use with the system account (-s)
-i Interactive - Run the program so that it interacts with the desktop on the remote system.
-l Limited - Run process as limited user. Only allow privs assigned to the Users group.
-n s Specify a timeout s seconds for connecting to the remote computer.
-p psswd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-s Run remote process in the System account.
-u user Specify a user name for login to remote computer(optional).
-w directory Set the working directory of the process (relative to the remote computer).
-x Display the UI on the Winlogon desktop (local system only).
-low, -belownormal, -abovenormal, -high or -realtime
These options will run the process at a different priority.
Psexec can also be used to start GUI applications, but in that case the GUI will appear on the remote machine.
Input is passed to the remote system when you press the enter key - typing Ctrl-C will terminate the remote process.
When you specify a username the remote process will execute in that account, and will have access to that account's network resources.
If you omit username the remote process will run in the same account from which you execute PsExec, but because the remote process is impersonating it will not have access to network resources on the remote system.
If you do specify an alternative username/password, then PsExec will send the password in clear text. This may be a security risk if unauthorized network sniffers could intercept traffic between the local and remote system.
PsExec does not require you to be an administrator of the local filesystem this can allow UserA to run commands as UserB - a Runasreplacement.
Surround any long filenames "with quotation marks"
Examples:
Launch an interactive command prompt on \\workstation64, the CMD prompt window will appear locally:
psexec \\workstation64 cmd
Execute IpConfig on the remote system, and display the output locally:
psexec \\workstation64 ipconfig /all
Copy the program test.exe to the remote system and execute it interactively:
psexec \\workstation64 -c test.exe
Execute a program that is already installed on the remote system:
psexec \\workstation64 "c:\Program Files\test.exe"
Run Internet Explorer on the local machine but with limited-user privileges:
psexec -l -d "c:\program files\internet explorer\iexplore.exe"
Related:
RUNAS - Execute a program under a different user account
Equivalent Linux BASH command: xon - start an X program on a remote machine
PsFile (part of PsTools - download PsFile) Show files opened remotely, or close an open file (kill file locks)
Syntax
psfile [\\Computer [-u User [-p Passwd]]] [[Id | path] [-c]]
Options:
computer The remote computer on which to list files. Default = local system
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a username for login to remote computer(optional).
Id Identifier (as assigned by PsFile) of the file for which to display info or to close.
Path Full or partial path of files to match for information display or close.
-c Close the files identifed by ID or path.
Unlike the NET FILE command, PsFile does not truncate long filenames.
Examples:
List all the files on \\workstation64 that have been opened remotely:
psfile \\workstation64
Related:
NET FILE - Display all the open shared files on a server and the lock-id
OPENFILES - Query or display open files
Equivalent bash command (Linux): inotify - file-monitoring mechanism
PsGetSid (part of PsTools - download PsGetSid) Display the SID of a computer or a user.
Syntax
psgetsid [\\computer[,computer[,...] | @get_file] [-u user [-p passwd]]] [account|SID]
Options:
computer The remote computer on which to list files. Default = local system
@get_file Get the SID of every computer listed in the text file specified.
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a username for login to remote computer(optional).
account The user account to resolve to a user SID
Specify a user name if the account you are running from doesn't have administrative privileges on the computer you want to query.
Examples:
Get the SID of \\workstation64:
psgetsid \\workstation64
Get the domain SID for the domain: Niamod
psgetsid Niamod
Get the SID for the currently logged-in user
psgetsid %username%
Related:
SYSTEMINFO - List system configuration
PsInfo (part of PsTools - download PsInfo) List information about a system including the type of installation, kernel build, registered organization, owner, processor details, physical memory and the system install date.
Syntax
psinfo [\\computer[,computer[,..]] [options] [filter]
psinfo @file [options] [filter]
Options:
computer The computer(s) on which psinfo will list information. Default=local system
@file List info for every computer listed in the text file specified.
-c Print in CSV format.
-c -t d Print in CSV format, separate items with delimiter d.
-h Show list of installed hotfixes.
-s Show list of installed applications.
-d Show disk volume information: drive letter, format, capacity.
-p psswd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a user name for login to remote computer(optional).
filter Psinfo will only show data for the field matching the filter.
e.g. "psinfo service" lists only the service pack field.
PsInfo relies on remote Registry access to obtain its data, the remote system must be running the Remote Registry service and the account from which you run PsInfo must have access to the HKLM\System portion of the remote Registry.
In order to aid in automated Service Pack updates, PsInfo returns as a value the Service Pack number of system (e.g. 0 for no service pack, 1 for SP 1, etc).
Examples:
List disc information about \\workstation64:
psinfo \\workstation64 -d
psinfo -d | find "%"
Related:
PsGetSid - Display the SID of a computer or a user
SYSTEMINFO - List system configuration
FSUTIL fsinfo - File and Volume specific commands
Equivalent Linux BASH command: cat /proc/*
PsKill (part of PsTools - download PsKill) Kill processes by name or process ID
Syntax
pskill [- ] [-t] [\\computer [-u user] [-p passwd]] <process name | process id>
Options:
computer The computer on which the process is running. Default=local system
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a user name for login to remote computer(optional).
-t Kill the process and its descendants.
process id/name
The process or processes to be killed.
- Help, display the supported options.
To kill a process on a remote system requires administrative privileges on the remote system.
Examples:
Kill all instances of notepad.exe running on \\workstation64:
pskill \\workstation64 notepad
Related:
TSKILL - Kill process on a Terminal Server
PsList - List detailed information about processes
The process button of Task Manager in Windows will also identify the process ID (PID)
PsSuspend - Suspend processes (so they can be continued at a later point in time)
KILL - Remove a program from memory
Powershell: Stop-Process - Stop a running process (kill)
Equivalent bash command (Linux): kill - Stop a process from running.
PsList (part of PsTools - download PsList)
Process Status, list information about processes running in memory.
Syntax
pslist [-?] [-t] [-m] [-x] [\\computer [-u user] [-p passwd]] [name | pid]
Options:
computer The computer on which the process is running. Default=local system
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a user name for login to remote computer(optional).
-t Show statistics for all active threads on the system,
each thread is grouped with its owning process.
-m Show memory-oriented information for each process,
rather than the default of CPU-oriented information.
-x Show CPU, memory and thread information for each process specified.
name Scan only those processes that begin with the name process.
Thus:
pslist exp
will display processes that start with exp... Explorer, Export etc
-? Display options and units of measurement.
The default information listed includes the time the process has executed, the amount of time the process has executed in kernel and user modes, and the amount of physical memory that the OS has assigned the process.
When running PsList against a remote system you must have administrative rights on that system, and the system must be running the Remote Registry service.
Examples:
List all processes running on \\workstation64:
C:\> SC \\workstation64 start RemoteRegistry
C:\> pslist \\workstation64
Related:
PsKill - Kill processes by name or process ID
OPENFILES - Query or display open files, disconnect files opened by network users.
TASKLIST - List running applications and services
Windows Task Manager - List of running process IDs (PID)
PerfMon - Monitoring tool
Powershell: Get-Process - Get a list of processes on a machine (ps/gps)
Equivalent bash command (Linux): ps - Process status, information about processes running in memory.
PsLoggedOn (part of PsTools - download PsLoggedOn) See who is logged onto a computer, either locally or remotely
Syntax
psloggedon [- ] [-l] [-x] [\\computer | username]
Options:
computer The computer on which the process is running. Default=local system
-l Show only local logons instead of both local and network resource logons.
-x Don't show logon times.
username Search the network for computers to which that user is loggedon.
- Help, display all options and units of measurement used.
PsLoggedOn's definition of a locally logged on user is one that has their profile loaded into the Registry. If no one is currently logged on, PsLoggedOn will return the last logged on user.
Note that PsLoggedOn will show you as logged on via resource share to remote computers that you query because a logon is required for PsLoggedOn to access the Registry of a remote system.
Examples:
List all processes running on \\workstation64:
pslist \\workstation64
WhoIsLoggedOnWhere.cmd - script to list all workstations
Related:
net session - List or disconnect user sessions (Local machine only)
Powershell: Get-WMIobject Win32_ComputerSystem (UserName )
Equivalent bash command (Linux): who - Print who is currently logged in
PsLogList (part of PsTools - download) Event log records
Syntax
psloglist [- ] [\\computer[,computer[,...] | @file
[-u user [-p passwd]]] [-s [-t delim]]
[-m #|-n #|-h #|-d #|-w]
[-c][-x][-r][-a mm/dd/yy][-b mm/dd/yy]
[-f filter] [-i ID[,ID[,...] | -e ID[,ID[,...]]]
[-o event source[,event source][,..]]]
[-q event source[,event source][,..]]]
[-l event_log_file] <eventlog>
Options:
computer The computer on which the log resides. Default=local system
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a user name for login to remote computer(optional).
@file Execute the command on each of the computers listed in the file.
-a Dump records timestamped after specified date.
-b Dump records timestamped before specified date.
-c Clear the event log after displaying.
-d # Only display records from previous # days.
-e ID Exclude events with the specified ID or IDs (up to 10).
-f filter Filter event types with filter string (e.g. "-f w" to filter warnings).
-h # Only display records from previous # hours.
-i ID Show only events with the specified ID or IDs (up to 10).
-l event_log_file Dump records from the specified event log file.
-m # Only display records from previous # minutes.
-n # Only display # number of most recent entries.
-o event source
Show only records from the specified event source (e.g. \"-o cdrom\").
-q event source
Omit records from the specified event source or sources (e.g. \"-q cdrom\").
-r Dump log from least recent to most recent.
-s Print Event Log records one-per-line, with comma delimited fields.
This format is convenient for text searches, e.g. psloglist | findstr /i text
and for importing the output into a spreadsheet.
-t delim The default delimeter is a comma, but can be overriden with the specified character.
-w Wait for new events, dumping them as they generate (local system only).
-x Dump extended data.
eventlog application, system or security, only the first few letters need be used.
default=system log.
If your current security credentials would not permit access to the Event Log, specify a different username ( -u user ).
Examples:
List everything in the application event log on \\workstation64 from the last 24 hours:
psloglist \\workstation64 -h 24 application
Related:
elogdump - Resource Kit event log dump (local machine only)
Equivalent bash command (Linux): Logs are in plain ascii text
PsPasswd (part of PsTools - download) Change account password
Syntax
pspasswd [[\\computer[,computer[,..] | @file
[-u user [-p passwd]]] Username [NewPassword]
Options:
computer The computer on which the user account resides. Default=local system
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a user name for login to remote computer(optional).
@file Execute the command on each of the computers listed in the file.
Username Name of account for password change.
NewPassword The new password, If ommitted a NULL password is applied.
This tool allows administrators to create a batch file that will run against multiple computers to perform a mass change of the administrator password.
Examples:
Change the password for user JDoe on \\workstation64
pspasswd \\workstation64 jdoe password567
Related:
NET USER
Equivalent bash command (Linux): passwd - Modify a user password
Password generator
PsService (part of PsTools - download) View and control services
Syntax
psservice [\\computer [-u user] [-p passwd]] <command> <options>
Options:
computer The computer on which the service is running. Default=local system
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a user name for login to remote computer(optional).
commands:
query Display the status of a service
config Display the configuration of a service
setconfig Set the start type (disabled, auto, demand) of a service.
start Start a service
stop Stop a service
restart Stop and then restart a service
pause Pause a service
cont Resume a paused service
depend List the services dependent on the one specified
security Dump the service's security descriptor
find Search the network for the specified service
Typing a command followed by "- " displays the syntax for that command.
Service States:
1 - Stopped
2 - Start Pending
3 - Stop Pending
4 - Running
Examples:
Restart the spooler service on \\server64
psservice \\server64 restart spooler
Related:
NET START/STOP
SC - Service control
Powershell: Get-Service - Get a list of services
PsShutdown (part of PsTools - download)
Initiate a shutdown/reboot of a local or remote computer, logoff a user, lock a system.
Syntax
psshutdown [[\\computer[,computer[,..] | @file [-u user [-p passwd]]]
-s|-r|-h|-d|-k|-a|-l|-o
[-f] [-c] [-t nn|h:m] [-n s] [-v nn]
[-e [u|p]:xx:yy] [-m "message"]
Options:
computer The computer on which the user account resides. Default=local system
a wildcard (\\*), will affect all computers in the current domain.
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a user name for login to remote computer(optional).
@file Execute the command on each of the computers listed in the file.
-a Abort a shutdown (only possible while a countdown is in progress)
-c Allow the shutdown to be aborted by the interactive user
-d Suspend the computer
-e [u|p]:xx:yy
Shutdown reason code, 'u' = user, 'p'= planned shutdown.
xx is the major reason code (must be less than 256)
yy is the minor reason code (must be less than 65536)
-f Force all running applications to exit during the shutdown
instead of giving them a chance to gracefully save their data.
-h Hibernate the computer
-k Poweroff the computer (reboot if poweroff is not supported)
-l Lock the computer
-m "message" Specify a message to logged-on users when a shutdown countdown commences
-n Timeout in seconds connecting to remote computers
-o Logoff the console user
-r Reboot after shutdown
-s Shutdown without poweroff
-t Countdown in seconds until the shutdown (default: 20 seconds)
or the time of shutdown (in 24 hour notation)
-v Display message for the specified number of seconds before the shutdown.
default= display a shutdown notification dialog,
specifying a value of 0 results in no dialog.
- Help, display the supported options.
This tool allows administrators to create a batch file that will run against multiple computers to perform a mass change of the administrator password.
Examples:
Reboot \\workstation64 as part of an OS upgrade
psshutdown \\workstation64 -r -e p:2:3
Related:
SHUTDOWN - With full list of reason codes
TSSHUTDN - Remotely shut down or reboot a terminal server
Powershell:
$os = (Get-WmiObject Win32_OperatingSystem -ComputerName MyServer64)
$os.psbase.Scope.Options.EnablePrivileges = $true
$os.reboot()
Equivalent bash command (Linux): shutdown - Shutdown or restart linux
PsSuspend (part of PsTools - download) Suspend processes on the local or a remote system.
Syntax
pssuspend [- ] [-r] [\\computer [-u user] [-p passwd]] <process name | process id>
Options:
computer The computer on which the service resides. Default=local system
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a user name for login to remote computer(optional).
-r Resume the processes specified if they are suspended.
process id/name
The process or processes to suspend or resume.
- Help, display the supported options.
Suspend is desirable in cases where a process is consuming a resource (e.g. network, CPU or disk) that you want to allow different processes to use. Rather than kill the process that's consuming the resource, suspending permits you to let it continue operation at some later point in time.
Examples:
Suspend the notepad process on \\workstation64
pssuspend \\workstation64 notepad
Related:
PsKill - Kill processes by name or process ID
PUSHD Change the current directory/folder and store the previous folder/path for use by the POPD command.
Syntax
PUSHD [drive]path
PUSHD
Key
drive The drive to switch to
path The folder to make 'current' (UNC names accepted)
If the drive is not specified, the current drive will be assumed.
If neither drive nor path are specified PUSHD will display a list of previous pathnames, you may switch back to any of these by using POPD one or more times.
If the path specified does not exist, PUSHD will return %errorlevel% =1
Examples
C:\demo> pushd \work
C:\work> pushd F:\music
F:\music> pushd
C:\work>
C:\demo>
F:\music> popd
C:\work>
Network paths
When a UNC path is specified, PUSHD will create a temporary drive map and will then use that new drive.
The temporary drive letters are allocated in reverse alphabetical order, so if Z: is free it will be used first.
If Command Extensions are disabled the PUSHD command will not accept a network (UNC) path.
#Ah, push it - push it good
Ah, push it - p-push it real good# - Salt 'N' Pepa
Related:
CD - Change directory
CMD - UNC options
PROMPT - Display the level of the PUSHD stack
Powershell: Push-Location - Push a location to the stack (pushd)
Powershell: cd - Jump to the previous working directory
Equivalent bash command (Linux): pushd - Save and then change the current directory
QGREP (Windows 2000 Resource Kit) Search file(s) for lines that match a given pattern.
Syntax
QGREP [options] [-e string] [-f file] [-i file] [strings] [files]
key:
-L Search strings literally.
-X Treat search strings as regular expressions.
-B Match pattern at beginning of line.
-E Match pattern at end of line.
-y Treat upper and lower-case as equivalent.
-x Print lines that match exactly.
-l Print only the file name if the file contains a match.
-n Print line numbers before each matching line.
-O Print seek offset before each matching line.
-v Print only lines that do not contain a match.
-z Print matching lines in MSC error message format.
-e string Treat the next argument as a literal search string.
-f file Read search strings from file.
-i file Read file list from file.
strings Specifies the search string(s).
files The file(s) to search, which can include wildcard characters
(* and ?)
Examples:
Find either arg1 or arg2 in FileName:
qgrep "arg1 arg2" FileName
Find arg1 arg2 in FileName:
qgrep -e "arg1 arg2" FileName.
White space separates search strings unless the argument is prefixed with -e.
QGREP "all out" x.y
means find either "all" or "out" in x.y, while
QGREP -e "all out" x.y
means find "all out".
grep is simply an odd concatenation of the phrase "grab regular expression"
Related Commands:
FINDSTR - Search for strings in files
Powershell: Where-Object - Filter objects passed along the pipeline.
Equivalent bash command (Linux): grep - Search file(s) for lines that match a given pattern
RASDIAL (Dial Up Networking) Manage RAS/DUN connections.
Dial a RAS connection:
RASDIAL entryname [/PHONEBOOK:PhonebookFile]
[/PHONE:PhoneNumber] [username [password|*]]
[/CALLBACK:CallBackNumber]
[/DOMAIN:domain][/PREFIXSUFFIX]
Hang up a RAS connection:
RASDIAL [entryname] /DISCONNECT
Display RAS Status:
RASDIAL
To use this command requires that Dial Up Networking Service be installed (via Control Panel - Networking)
The default location for PhoneBook entries is \%SystemRoot%\system32\ras\
"If advanced switching technology had not been developed and the telephone still had one operator for every 120 of some 100 million telephones, it would take 2,400,000 telephone operators (on three shifts) - John R. Pierce
Related:
RASPHONE - Manage RAS connections
Connection Manager Administration Kit - VPN connections (2003 Resource Kit)
RASMON - Windows 2000 GUI Resource Kit tool
CHECKRAS - SMS support tools
RASPHONE (Dial Up Networking) Manage Remote Access Service (RAS) connections.
This is a part of the Dial-Up Networking service, typically used to connect a PC to an Internet Service Provider.
Dial a RAS connection:
RASPHONE [-v] -f PhoneBook_file -d "PhoneBook_entry"
Hang up a RAS connection:
RASPHONE [-v] -f PhoneBook_file -h "PhoneBook_entry"
Display RAS Status dialogue box
RASPHONE -S
Other RAS options:
RASPHONE [-v] -f PhoneBook_file options "PhoneBook_entry"
OPTIONS
-a : Add new PhoneBook entry
-e : Edit an existing PhoneBook entry
-c : Clone an existing PhoneBook entry
-r : Delete/remove an existing PhoneBook entry
-v : Disable - 'grey out' the option to rename the PhoneBook_entry
To use this command requires that Dial Up Networking Service be installed (via Control Panel - Networking)
The default location for PhoneBook entries is %SystemRoot%\System32\ras\
"Someone invented the telephone, And interrupted a nation's slumber, Ringing wrong but similar numbers" - Ogden Nash
Related:
RASDIAL - Manage RAS connections
Connection Manager Administration Kit - VPN connections (2003 Resource Kit)
RASMON - Windows 2000 GUI Resource Kit tool
CHECKRAS - SMS support tools
RECOVER Recover a damaged file from a defective disk.
Syntax
RECOVER [drive:][path]filename
Recover is designed to help in the case of hardware failure. When a drive fails the failure is not always total, in other words you may be able to read some of the files but not others, and some files will be only partly readable.
The data on a disk is stored in tracks and sectors in an almost random manner. Data stored in a bad sectors cannot be read.
RECOVER reads a file sector by sector and recovers data from the good sectors. You must specify a filename.
Recover does not allow you to undelete a file.
Recover the files one at a time.
"Whom the gods love dies young - Menander 300 BC
Related:
CHKDSK - Check Disk - check and repair disk problems
Equivalent bash command (Linux): cksum - Print CRC checksum and byte counts (can detect problems but not fix them)
REG.exe Read, Set or Delete registry keys and values, save and restore from a .REG file.
Syntax:
REG QUERY [ROOT\]RegKey /v ValueName [/s]
REG QUERY [ROOT\]RegKey /ve --This returns the (default) value
REG ADD [ROOT\]RegKey /v ValueName [/t DataType] [/S Separator] [/d Data] [/f]
REG ADD [ROOT\]RegKey /ve [/d Data] [/f] -- Set the (default) value
REG DELETE [ROOT\]RegKey /v ValueName [/f]
REG DELETE [ROOT\]RegKey /ve [/f] -- Remove the (default) value
REG DELETE [ROOT\]RegKey /va [/f] -- Delete all values under this key
REG COPY [\\SourceMachine\][ROOT\]RegKey [\\DestMachine\][ROOT\]RegKey
REG EXPORT [ROOT\]RegKey FileName.reg
REG IMPORT FileName.reg
REG SAVE [ROOT\]RegKey FileName.hiv
REG RESTORE \\MachineName\[ROOT]\KeyName FileName.hiv
REG LOAD FileName KeyName
REG UNLOAD KeyName
REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/v ValueName] [Output] [/s]
REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/ve] [Output] [/s]
Key:
ROOT :
HKLM = HKey_Local_machine (default)
HKCU = HKey_current_user
HKU = HKey_users
HKCR = HKey_classes_root
ValueName : The value, under the selected RegKey, to edit.
(default is all keys and values)
/d Data : The actual data to store as a "String", integer etc
/f : Force an update without prompting "Value exists, overwrite Y/N"
\\Machine : Name of remote machine - omitting defaults to current machine.
Only HKLM and HKU are available on remote machines.
FileName : The filename to save or restore a registry hive.
KeyName : A key name to load a hive file into. (Creating a new key)
/S : Query all subkeys and values.
/S Separator : Character to use as the separator in REG_MULTI_SZ values
the default is "\0"
/t DataType : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ
Output : /od (only differences) /os (only matches) /oa (all) /on (no output)
Notes:
Any of the above commands can be run against a remote machine by adding \\MachineName to the command line, assuming the Remote Registry Service is running.
Registry data stored under HKCU will be visible and writable by the currently logged in user.
Registry data stored under HKLM will be visible to all users and writable by administrators.
To include a quote mark (") in the data, prefix it with the escape character (\) e.g. "Here is \" a quote"
Enclose ValueNames that contain the \ character in single quotes.
REG RESTORE has a tendency not to work, possibly due to firewall issues, Export and Import are much more reliable.
Examples
REG QUERY HKCU\Console\
REG QUERY HKCU\Console /v ScreenBufferSize
Find the location of the Start Menu folder:
REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v "Start Menu"
REG ADD HKCU\Software\SS64 /v Sample /d "some test data"
REG QUERY HKCU\Software\SS64 /v Sample
REG ADD HKLM\Software\DiLithium /v WarpSpeed /t REG_BINARY /d ffffffff
REG QUERY HKLM\Software\DiLithium /v WarpSpeed
REG COPY \\Wks580\HKCU\Software\SS64 HKCU\Software\SS64
REG COPY HKCU\Software\SS64 HKCU\Software\SS64Copy
REG EXPORT HKCU\Software\SS64 C:\MyReg.REG
REG IMPORT C:\MyReg.REG
REG SAVE HKCU\Software\SS64 C:\MyRegHive.hiv
REG RESTORE \\Wks580\HKCU\Software\SS64 C:\MyRegHive.hiv
Run a script at first logon (Run Once) to do this we edit the Default User profile by temporarily loading it as ZZZ:
REG LOAD HKU\ZZZ "C:\Documents and Settings\Default User\NTUSER.DAT"
REG ADD HKU\ZZZ\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce /v newUserProfile /t REG_EXPAND_SZ /d "D:\setup.cmd" /f
REG UNLOAD HKU\ZZZ
More examples are available via: REG QUERY /? REG ADD /? etc
"The way to a mans heart is through his stomach" - Fanny Fern (writer)
Related:
SETX - Set environment variables permanently, can also read a registry key and write the value to a text file.
REGEDIT - Load Registry settings from a .REG file
Dureg - Registry Size Estimator. (Win 2K ResKit)
Powershell: Get-ItemProperty / Set-ItemProperty - Retrieve / save registry Keys
Q325347 - Run a Logon Script once when a new user logs on, Windows 2003
Q284193 - Run a Logon Script once when a new user logs on, Windows 2000
Q945219 - Reg.exe fails for REG_EXPAND_SZ registry types
Q948698 - Remote access to 64-bit registry keys
REGEDIT
Import, export or delete registry settings from a text (.REG) file
Syntax
Export the Registry (all HKLM plus current user)
REGEDIT /E pathname
Export part of the Registry
REGEDIT /E pathname "RegPath"
Import a reg script
REGEDIT pathname
Silent import
REGEDIT /S pathname
Start the regedit GUI
REGEDIT
Open multiple copies of GUI (XP and 2003 only)
REGEDIT -m
Key
/E : Export
/S : Silent Import
How to add keys and values from the registry:
Create a text file like this:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\SomeKey]
"SomeStringValue"="Hello"
When double clicking this .reg file the key and value will be added.
Alternatively run REGEDIT MYKEY.REG from the command line.
How to delete keys and values from the registry:
Create a reg file like this, notice the hyphen inside the first bracket
Windows Registry Editor Version 5.00
[-HKEY_CURRENT_USER\SomeKey]
When double clicking this .reg file the key "SomeKey" will be deleted along with all string, binary or Dword values in that key.
If you want to just delete values, leaving the key in place, set the value you want to delete = to a hyphen
e.g.
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\SomeKey]
"SomeStringValue"=-
Again double clicking this .reg file will delete the values specified, or you can use REGEDIT /s MyDeleteScript.REG
Compare the Registry of two machines
Windiff is your friend, this simple GUI utility from the resource kit will list all the differences.
Comments
Within a registry file, comments can be preceded by "; "
e.g.
;
; Turn the NUMLOCK on at login
;
[HKEY_CURRENT_USER\Control Panel\Keyboard]
"InitialKeyboardIndicators"="2"
Under Windows NT 4 all registry scripts start with: REGEDIT4
(This version string will also work in XP and later versions of Windows.)
"I never make stupid mistakes. Only very, very clever ones" - John Peel
Related:
REG - Read, Set or Delete registry keys and values
SET - Display, set, or remove Windows NT environment variables
SETX - Set environment variables permanently
WMIC REGISTRY - Set registry options through WMI
Powershell: Get-ItemProperty / Set-ItemProperty - Retrieve / save registry Keys
Q322756 - How to backup and edit the registry
Dureg - Registry Size Estimator. (Win 2K ResKit)
XP Registry Keys - Commonly tweaked user interface settings
REGSVR32
Register or unregister a DLL.
Syntax
REGSVR32 [/U] [/S] [/C] [/I:[Command_Line]] DLL_Name
REGSVR32 [/U] [/S] [/C] /N /I:[Command_Line] DLL_Name
Key
/u Unregister Server.
/s Silent - no dialogue boxes.
/c Console output.
/n Don't call DllRegisterServer
/i Call DllInstall (or DllUninstall if /u is specified)
Command_Line An optional command line for DllInstall
Examples
Unregister (disable) XP Zip folders
REGSVR32 /u C:\Windows\System32\zipfldr.dll
Unregister (Disable) CAB file viewer:
REGSVR32 /u C:\Windows\System32\cabview.dll
Register (enable) XP Zip folders
REGSVR32 zipfldr.dll
Register (enable) CAB file viewer:
REGSVR32 cabview.dll
Register Windows Update DLLs (for those times when XP repair breaks Windows Update)
regsvr32 /s wuapi.dll
regsvr32 /s wuaueng1.dll
regsvr32 /s wuaueng.dll
regsvr32 /s wucltui.dll
regsvr32 /s wups2.dll
regsvr32 /s wups.dll
regsvr32 /s wuweb.dll
Register DAO 3.6 (Data Access Objects):
REGSVR32 "C:\Program Files\Common Files\Microsoft Shared\DAO\DAO360.DLL"
It costs nothing to register and will only take a moment...
Related:
Delsrv - unregister a service with the Services Control Manager. (Win 2K ResKit)
MSIEXEC - Microsoft Windows Installer
RUNDLL32 - Run a DLL command
Q249873 - Regsvr32 usage and error messages
REGINI (Resource kit) Change Registry Permissions.
Syntax
REGINI [-m \\machinename | -h hivefile hiveroot | -w Win95Directory]
[-i n] [-o outputWidth]
[-b] textFiles...
Key
-m A remote computer.
-h The local hive to manipulate.
-w Path to Windows 95 system.dat / user.dat files
-i n The display indentation multiple. Default is 4
-o outputWidth
How wide the output is to be. By default the
outputWidth is set to the width of the console window if standard
output has not been redirected to a file. In the latter case, an
outputWidth of 240 is used.
-b Make REGINI backward compatible with older versions of REGINI that
did not strictly enforce line continuations and quoted strings
Specifically, REG_BINARY, REG_RESOURCE_LIST and
REG_RESOURCE_REQUIREMENTS_LIST data types did not need line
continuations after the first number that gave the size of the data.
It just kept looking on following lines until it found enough data
values to equal the data length or hit invalid input. Quoted
strings were only allowed in REG_MULTI_SZ. They could not be
specified around key or value names, or around values for REG_SZ or
REG_EXPAND_SZ Finally, the old REGINI did not support the semicolon
as an end of line comment character.
textFiles One or more ANSI or Unicode text files with registry data.
The easiest way to understand the format of the input textFile is to use the REGDMP command with no arguments to dump the current contents of
your NT Registry to standard out. Redirect standard out to a file and this file is acceptable as input to REGINI
Some general rules are:
Semicolon character is an end-of-line comment character, provided it is the first non-blank character on a line
Backslash character is a line continuation character. All characters from the backslash up to but not including the first non-blank character of the next line are ignored. If there is more than one space before the line continuation character, it is replaced by a single space.
Indentation is used to indicate the tree structure of registry keys The REGDMP program uses indentation in multiples of 4. You may use hard tab characters for indentation, but embedded hard tab characters are converted to a single space regardless of their position
Values should come before child keys, as they are associated with the previous key at or above the value's indentation level.
For key names, leading and trailing space characters are ignored and not included in the key name, unless the key name is surrounded by quotes. Imbedded spaces are part of a key name.
Key names can be followed by an Access Control List (ACL) which is a series of decimal numbers, separated by spaces, bracketed by a square brackets (e.g. [8 4 17]). The valid numbers and their meanings are:
1 - Administrators Full Access
2 - Administrators Read Access
3 - Administrators Read and Write Access
4 - Administrators Read, Write and Delete Access
5 - Creator Full Access
6 - Creator Read and Write Access
7 - World Full Access
8 - World Read Access
9 - World Read and Write Access
10 - World Read, Write and Delete Access
11 - Power Users Full Access
12 - Power Users Read and Write Access
13 - Power Users Read, Write and Delete Access
14 - System Operators Full Access
15 - System Operators Read and Write Access
16 - System Operators Read, Write and Delete Access
17 - System Full Access
18 - System Read and Write Access
19 - System Read Access
20 - Administrators Read, Write and Execute Access
21 - Interactive User Full Access
22 - Interactive User Read and Write Access
23 - Interactive User Read, Write and Delete Access
If there is an equal sign on the same line as a left square bracket then the equal sign takes precedence, and the line is treated as a registry value. If the text between the square brackets is the string DELETE with no spaces, then REGINI will delete the key and any values and keys under it.
For registry values, the syntax is:
value Name = type data
Leading spaces, spaces on either side of the equal sign and spaces between the type keyword and data are ignored, unless the value name
is surrounded by quotes. If the text to the right of the equal sign is the string DELETE, then REGINI will delete the value.
The value name may be left off or be specified by an at-sign character which is the same thing, namely the empty value name. So the following two lines are identical:
= type data
@ = type data
This syntax means that you can't create a value with leading or trailing spaces, an equal sign or an at-sign in the value name, unless you put the name in quotes.
Valid value types and format of data that follows are:
REG_SZ text
REG_EXPAND_SZ text
REG_MULTI_SZ "string1" "str""ing2" ...
REG_DATE mm/dd/yyyy HH:MM DayOfWeek
REG_DWORD numberDWORD
REG_BINARY numberOfBytes numberDWORD(s)...
REG_NONE (same format as REG_BINARY)
REG_RESOURCE_LIST (same format as REG_BINARY)
REG_RESOURCE_REQUIREMENTS (same format as REG_BINARY)
REG_RESOURCE_REQUIREMENTS_LIST (same format as REG_BINARY)
REG_FULL_RESOURCE_DESCRIPTOR (same format as REG_BINARY)
REG_QWORD numberQWORD
REG_MULTISZ_FILE fileName
REG_BINARYFILE fileName
If no value type is specified, default is REG_SZ
For REG_SZ and REG_EXPAND_SZ, if you want leading or trailing spaces in the value text, surround the text with quotes. The value text
can contain any number of imbedded quotes, and REGINI will ignore them, as it only looks at the first and last character for quote characters.
For REG_MULTI_SZ, each component string is surrounded by quotes. If you want an imbedded quote character, then double quote it, as in string2 above.
For REG_BINARY, the value data consists of one or more numbers The default base for numbers is decimal. Hexidecimal may be specified by using 0x prefix. The first number is the number of data bytes, excluding the first number. After the first number must come enough numbers to fill the value. Each number represents one DWORD or 4 bytes. So if the first number was 0x5 you would need two more numbers after that to fill the 5 bytes. The high order 3 bytes
of the second DWORD would be ignored.
Whenever specifying a registry path, either on the command line or in an input file, the following prefix strings can be used:
HKEY_LOCAL_MACHINE
HKEY_USERS
HKEY_CURRENT_USER
USER:
Each of these strings can stand alone as the key name or be followed
a backslash and a subkey path.
There are several versions of regini with different syntax - the resource kit includes a word document with help and examples.
“If you're not failing every now and again, it's a sign you're not doing anything very innovative” - Woody Allen
Related:
REGEDIT - Import or export registry settings
REG - Registry: Read, Set, Export, Delete keys and values
Q245031 - Use a Script to Change Registry Permissions
REM
In a batch file REM at the start of a line signifies a comment or REMARK
alternatively adding :: at the start of a line has a similar effect
For example:
@ECHO OFF
::
:: First comment
::
REM Second comment
REM
::
Although you can use rem without a comment to add vertical spacing to a batch file, you can also use completely blank lines. The blank lines are ignored when processing the batch program.
The double-colon is not documented as a comment command, it is a special case of a CALL label that acts like a comment. The pro's and cons of each method are listed below.
Bugs
There are problems using a :: comment within an IF or FOR code bracket
e.g.
@echo off
FOR /L %%i IN (1,1,10) Do (
Echo before comment
:: Some comment
Echo after comment
)
The above will return the error :: was unexpected at this time.
In Windows 2000 and XP a comment like
::%~
or
REM %~ will be interpreted giving the error:
The following usage of the path operator in batch-parameter substitution is invalid: %~
In Windows NT 4 the REM command would incorrectly reset the %errorlevel% to 0
The bottom line on this is that you must test your comments to be sure they will be ignored as you expect.
Registry Comments
Within a registry file comments can be preceded by "; "
e.g.
;
; Turn the NUMLOCK on at login
;
[HKEY_CURRENT_USER\Control Panel\Keyboard]
"InitialKeyboardIndicators"="2"
FTP Comments
There is no valid comment character for FTP but you can cheat by escaping to the shell and running REM
e.g.
C:\WORK>type ftpscript
!REM This is a remark
bye
C:\WORK>ftp -s:ftpscript
ftp> !REM This is a remark
ftp> bye
C:\WORK>
#Now stand in the place where you work, Now face West
Think about the place where you live, Wonder why you haven't before# - REM 'Stand'
Related:
Powershell: # - Comment / Remark
Equivalent bash command: ### - Comment / Remark
REN Rename a file or files.
REN [drive:][path]old_filename new_filename
RENAME is a synonym for REN
You cannot specify a different drive or path for `new_filename` - use the MOVE command instead.
Both the source and/or destination may include wildcards.
Examples
Rename Monday.txt as Tuesday.txt
C:\> REN Monday.txt Tuesday.txt
Rename all text files in the current folder to have the extension .BAK
C:\> REN *.txt *.BAK
Rename Monday.txt as Monday.BAK
C:\> REN Monday.txt *.BAK
“We may dig in our heels and dare life never to change, but, all the same, it changes under our feet like sand under the feet of a sea gazer as the tide runs out. Life is forever undermining us. Life is forever washing away our castles, reminding us that they were, after all, only sand and sea water.” - Erica Jong (Parachutes and Kisses)
Related:
MOVE - Move a file from one folder to another
Stamp.cmd - Batch file to rename a file to include the current date and time.
Powershell: Rename-Item - Change the name of an existing item (ren/rni)
Equivalent bash command (Linux): mv - Move or rename files or directories
REPLACE Replace or update one file with another
Syntax
REPLACE Source_PathName Destination_path [/A] [/P] [/R] [/W]
REPLACE Source_PathName Destination_path [/P] [/R] [/S] [/W] [/U]
Key
path : The folder where files are to be replaced.
/A : Add any missing files.
/P : Prompt for confirmation (each file)
/R : Replace even Read-only files
/S : Include all subfolders of the destination.
/W : Wait for you to insert a floppy disk.
/U : Replace (update) only files that are older than the source.
Limitations:
When replacing in all subdirectories (/S ) you cannot ADD files (/A) or restrict to replacing older files (/U)
"That's the secret to life... replace one worry with another" - Charles M. Schulz
Related:
ROBOCOPY - Robust File and Folder Copy
MOVE - Move files from one folder to another folder on the same drive
DEL - Delete one or more files
COPY - Copy one or more files to another location
Equivalent bash command (Linux): install - Copy files and set attributes
RD Delete folder(s)
Syntax
RD pathname
RD /S pathname
RD /S /Q pathname
Key
/S : Delete all files and subfolders
in addition to the folder itself.
Use this to remove an entire folder tree.
/Q : Quiet - do not display YN confirmation
Place any long pathnames in double quotes.
RD does not support wildcards but you can remove several folders in one command by listing the pathname to each.
e.g.
RD c:\docs\Jan c:\docs\Feb "c:\My Documents\Mar"
RMDIR is a synonym for RD
“Dying is the most embarrassing thing that can happen to you, because someones got to take care of all your details” - Andy Warhol
Related:
MD - Create folder(s)
DEL - Delete selected files from an entire folder tree
Delrp - Delete a file/directory and NTFS reparse points.(Win 2K ResKit)
INUSE - updated file replacement utility (may not preserve file permissions)
Powershell: Remove-Item - Remove an item (rd/ri/rmdir)
Equivalent bash command (Linux): rmdir - Remove folder(s) rm -rf - Delete directory recursively
RMTSHARE.exe (NT 4 Resource kit - download)
Manage File and Printer shares, local or on a remote server.
Although missing from recent Resource kits, the old version appears to work fine under Windows 2000/XP/2003.
Syntax
Display all shares
RMTSHARE \\server
Display details of a specific share
RMTSHARE \\server\sharename
Share a Folder
RMTSHARE \\server\sharename=drive:path [options]
Share a Printer
RMTSHARE \\server\sharename=printername /PRINTER [options]
Edit an existing SHARE
RMTSHARE \\server\sharename [options]
Delete a SHARE
RMTSHARE \\server\sharename /DELETE
Options
/USERS:number
/UNLIMITED
/REMARK:"text"
/GRANT user:perm
/REMOVE user
Notes: Either specify /Users to restrict the number of connections that can be made OR specify /UNLIMITED
You can include several /GRANTs in a single command line.
Enclose paths that include spaces like this
\\server\"long share name"="c:\long file name"
“How to be green? consume less, share more, enjoy life” - Penny Kemp
Related:
CACLS - Apply File permissions
NET USE - Connect to a file share
REMOTE - Run a command on a remote computer (Resource Kit)
RUNDLL32 - Run a DLL command (add/remove print connections)
SHARE - List or edit a file share or print share (on any computer)
Powershell: Get-WmiObject win32_share
Equivalent bash command (Linux): mount - Mount a file system
ROBOCOPY.exe (XP Resource Kit/Standard Windows 7 command)
Robust File and Folder Copy.
By default Robocopy will only copy a file if the source and destination have different time stamps or different file sizes.
Syntax
ROBOCOPY Source_folder Destination_folder [files_to_copy] [options]
Key
file(s)_to_copy : A list of files or a wildcard.
(defaults to copying *.*)
Source options
/S : Copy Subfolders.
/E : Copy Subfolders, including Empty Subfolders.
/COPY:copyflag[s] : What to COPY (default is /COPY:DAT)
(copyflags : D=Data, A=Attributes, T=Timestamps
S=Security=NTFS ACLs, O=Owner info, U=aUditing info).
/SEC : Copy files with SECurity (equivalent to /COPY:DATS).
/DCOPY:T : Copy Directory Timestamps. ##
/COPYALL : Copy ALL file info (equivalent to /COPY:DATSOU).
/NOCOPY : Copy NO file info (useful with /PURGE).
/A : Copy only files with the Archive attribute set.
/M : like /A, but remove Archive attribute from source files.
/LEV:n : Only copy the top n LEVels of the source tree.
/MAXAGE:n : MAXimum file AGE - exclude files older than n days/date.
/MINAGE:n : MINimum file AGE - exclude files newer than n days/date.
(If n < 1900 then n = no of days, else n = YYYYMMDD date).
/FFT : Assume FAT File Times (2-second date/time granularity).
/256 : Turn off very long path (> 256 characters) support.
Copy options
/L : List only - don't copy, timestamp or delete any files.
/MOV : MOVe files (delete from source after copying).
/MOVE : Move files and dirs (delete from source after copying).
/Z : Copy files in restartable mode (survive network glitch).
/B : Copy files in Backup mode.
/ZB : Use restartable mode; if access denied use Backup mode.
/IPG:n : Inter-Packet Gap (ms), to free bandwidth on slow lines.
/R:n : Number of Retries on failed copies - default is 1 million.
/W:n : Wait time between retries - default is 30 seconds.
/REG : Save /R:n and /W:n in the Registry as default settings.
/TBD : Wait for sharenames To Be Defined (retry error 67).
Destination options
/A+:[RASHCNET] : Set file Attribute(s) on destination files + add.
/A-:[RASHCNET] : UnSet file Attribute(s) on destination files - remove.
/FAT : Create destination files using 8.3 FAT file names only.
/CREATE : CREATE directory tree structure + zero-length files only.
/DST : Compensate for one-hour DST time differences ##
/PURGE : Delete dest files/folders that no longer exist in source.
/MIR : MIRror a directory tree - equivalent to /PURGE plus all subfolders (/E)
Logging options
/L : List only - don't copy, timestamp or delete any files.
/NP : No Progress - don't display % copied.
/LOG:file : Output status to LOG file (overwrite existing log).
/UNILOG:file : Output status to Unicode Log file (overwrite) ##
/LOG+:file : Output status to LOG file (append to existing log).
/UNILOG+:file : Output status to Unicode Log file (append) ##
/TS : Include Source file Time Stamps in the output.
/FP : Include Full Pathname of files in the output.
/NS : No Size - don't log file sizes.
/NC : No Class - don't log file classes.
/NFL : No File List - don't log file names.
/NDL : No Directory List - don't log directory names.
/TEE : Output to console window, as well as the log file.
/NJH : No Job Header.
/NJS : No Job Summary.
Repeated Copy Options
/MON:n : MONitor source; run again when more than n changes seen.
/MOT:m : MOnitor source; run again in m minutes Time, if changed.
/RH:hhmm-hhmm : Run Hours - times when new copies may be started.
/PF : Check run hours on a Per File (not per pass) basis.
Job Options
/JOB:jobname : Take parameters from the named JOB file.
/SAVE:jobname : SAVE parameters to the named job file
/QUIT : QUIT after processing command line (to view parameters).
/NOSD : NO Source Directory is specified.
/NODD : NO Destination Directory is specified.
/IF : Include the following Files.
Advanced options you'll probably never use
/EFSRAW : Copy any encrypted files using EFS RAW mode. ##
/MT[:n] : Multithreaded copying, n = no. of threads to use (1-128) ###
default = 8 threads, not compatible with /IPG and /EFSRAW
The use of /LOG is recommended for better performance.
/SECFIX : FIX file SECurity on all files, even skipped files.
/TIMFIX : FIX file TIMes on all files, even skipped files.
/XO : eXclude Older - if destination file exists and is the same date
or newer than the source - don't bother to overwrite it.
/XC | /XN : eXclude Changed | Newer files
/XL : eXclude "Lonely" files and dirs (present in source but not destination)
This will prevent any new files being added to the destination.
/XX : eXclude "eXtra" files and dirs (present in destination but not source)
This will prevent any deletions from the destination. (this is the default)
/XF file [file]... : eXclude Files matching given names/paths/wildcards.
/XD dirs [dirs]... : eXclude Directories matching given names/paths.
XF and XD can be used in combination e.g.
ROBOCOPY c:\source d:\dest /XF *.doc *.xls /XD c:\unwanted /S
/IA:[RASHCNETO] : Include files with any of the given Attributes
/XA:[RASHCNETO] : eXclude files with any of the given Attributes
/IS : Include Same, overwrite files even if they are already the same.
/IT : Include Tweaked files.
/XJ : eXclude Junction points. (normally included by default).
/MAX:n : MAXimum file size - exclude files bigger than n bytes.
/MIN:n : MINimum file size - exclude files smaller than n bytes.
/MAXLAD:n : MAXimum Last Access Date - exclude files unused since n.
/MINLAD:n : MINimum Last Access Date - exclude files used since n.
(If n < 1900 then n = n days, else n = YYYYMMDD date).
/BYTES : Print sizes as bytes.
/X : Report all eXtra files, not just those selected & copied.
/V : Produce Verbose output log, showing skipped files.
/ETA : Show Estimated Time of Arrival of copied files.
## = New Option in Vista (XP027) all other options on this page are for the XP version of Robocopy (XP010)
### = New Option in Windows 7 and Windows 2008 R2
Robocopy EXIT CODES
File Attributes [RASHCNETO]
R – Read only
A – Archive
S – System
H – Hidden
C – Compressed
N – Not content indexed
E – Encrypted
T – Temporary
O - Offline
If either the source or desination are a "quoted long foldername" do not include a trailing backslash as this will be treated as an escape character, i.e. "C:\some path\" will fail but "C:\some path\\" or "C:\some path\." or "C:\some path" will work.
Robocopy will fail to copy files that are 'locked' by other users or applications, limiting the number of retries with /R:0 will speed up large jobs.
By copying only the files that have changed, robocopy can be used to backup very large volumes.
To limit the network bandwidth used by robocopy, specify the Inter-Packet Gap parameter /IPG:n
This will send packets of 64 KB each followed by a delay of n Milliseconds.
ROBOCOPY will accept UNC pathnames including UNC pathnames over 256 characters long.
/REG Writes to the registry at HKCU\Software\Microsoft\ResKit\Robocopy
/B (backup mode) will allow Robocopy to override file and folder permission settings (ACLs).
/XX If used in conjunction with /Purge or /Mir, this switch will take precedence and prevent any files being deleted from the destination.
All versions of Robocopy will copy security information (ACLs) for directories, version XP010 will not copy file security changes unless the file itself has also changed, this greatly improves performance.
To run ROBOCOPY under a non-administrator account will require backup files privilege, to copy security information auditing privilege is also required, plus of course you need at least read access to the files and folders.
Robocopy is a standard command in Windows 7 and above. The Windows Server 2003 Resource Kit Tools include Robocopy XP010, which can be run on NT 4/ Windows 2000. Robocopy does not run on Windows 95, or NT 3.5. (RoboCopy is a Unicode application).
Robocopy 'Jobs' and the 'MOnitor source' option provide an alternative to setting up a Scheduled Task to run a batchfile with a RoboCopy command.
Examples:
Copy files from one server to another (auto skip files already in the destination)
ROBOCOPY \\Server1\reports \\Server2\backup *.doc /S
List files over 32 MBytes in size:
ROBOCOPY C:\work /MAX:33554432 /L
Move files over 14 days old: (note the MOVE option will fail if any files are open and locked.)
ROBOCOPY C:\work C:\destination /move /minage:14
Backup a Server
The script below copies data from FileServ1 to FileServ2, the destination holds a full mirror along with file security info. When run regularly to synchronize the source and destination, robocopy will only copy those files that have changed (change in time stamp or size.)
@ECHO OFF
SETLOCAL
SET _source=\\FileServ1\e$\users
SET _dest=\\FileServ2\e$\BackupUsers
SET _what=/COPYALL /B /SEC /MIR
:: /COPYALL :: COPY ALL file info
:: /B :: copy files in Backup mode.
:: /SEC :: copy files with SECurity
:: /MIR :: MIRror a directory tree
SET _options=/R:0 /W:0 /LOG:MyLogfile.txt /NFL /NDL
:: /R:n :: number of Retries
:: /W:n :: Wait time between retries
:: /LOG :: Output log file
:: /NFL :: No file logging
:: /NDL :: No dir logging
ROBOCOPY %_source% %_dest% %_what% %_options%
Run two robocopy jobs at the same time with START /Min
Start /Min "Job one" Robocopy \\FileServA\C$\Database1 \\FileServeBackupA\c$\Backups
Start /Min "Job two" Robocopy \\FileServB\C$\Database2 \\FileServeBackupB\c$\Backups
Bugs
Version XP026 returns a success errorlevel even when it fails.
“One, a robot may not injure a human being, or through inaction, allow a human being to come to harm” - Isaac Asimov, Laws of Robotics from I. Robot, 1950
Related:
Robocopy EXIT CODES
COPY - Copy one or more files to another location
Robocopy GUI - Technet magazine (installs Robocopy XP026)
RichCopy free GUI copy utility - Ken Tamaru @ Microsoft
Copy Open files - with VShadow.exe (Shadow copies)
SyncToy - Microsoft Powertoy for synchronizing two folders
Convert KB/MB - Bits and Bytes, bandwidth calculations
Permcopy - Copy share & file ACLs from one share to another. (Win 2K ResKit)
Q323275 - Copy Security info without copying files (/SECFIX or /COPY:S)
Equivalent bash command:rsync - Remote file copy (Synchronize file trees)
ROUTE.exe
Manipulate network routing tables. Route packets of network traffic from one subnet to another by modifying the route table.
Syntax
Display route details:
ROUTE [-f] PRINT [destination_host] [MASK subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
Add a route:
ROUTE [-f] [-p] ADD [destination_host] [MASK subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
Change a route:
ROUTE [-f] CHANGE [destination_host] [MASK subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
Delete a route:
ROUTE [-f] DELETE [destination_host] [MASK subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
key
-f Clear (flush) the routing tables of all gateway entries. If this is
used in conjunction with one of the commands, the tables are
cleared prior to running the command.
destination_host
The address (or set of addresses) that you want to reach.
-p Create a persistent route - survives system reboots.
(not supported in Windows 95)
subnet_mask_value
The subnet mask value for this route entry.
This defines how many addresses are there.
If not specified, it defaults to 255.255.255.255.
gateway The gateway.
interface The interface number (1,2,...) for the specified route.
If the option `IF interface_no` is not given, ROUTE will try
to find the best interface available.
metric The metric, ie. cost for the destination.
Note that routes added to the table are not made persistent unless the -p switch is specified. Non-persistent routes only last until the computer is rebooted.
Symbolic names used for Destination_Host are looked up in the network database file NETWORKS.
The symbolic names for gateway are looked up in the host name database file HOSTS.
If the command is PRINT or DELETE. Destination or gateway can be a wildcard ('*'), or the gateway argument may be omitted.
An IP address mask of 0.0.0.0 means everything. (rather like the *.* wildcard). In other words it says: When matching this pattern, don't worry about matching any of the bits - everything matches.
If Destination_Host contains a * or ?, it is treated as a shell pattern, and only matching destination routes are printed. The '*' matches any string, and '?' matches any one char.
Examples:
157.*.1
157.*
127.*
*224*
"Get your kicks on ROUTE 66" - Jack Kerouac.
Related:
NETSTAT-rn - Display TCP/IP network connections, routing and protocol statistics
TRACERT - Trace route to a remote host
Q140859 - Win NT TCP/IP Routing Basics
Equivalent bash command (Linux): trace - Find the IP address of a remote host
Start | Run Commands for Windows XP, Vista and Windows 7: Accessibility Controls access.cpl
Accessibility Options control access.cpl
Adapter Troubleshooter (Vista/Win7) AdapterTroubleshooter
Add Hardware Wizard hdwwiz.cpl
Add/Remove Programs appwiz.cpl
Add/Remove Programs (Add New Programs) control appwiz.cpl,,1
Add/Remove Programs (Add Remove Windows Components) control appwiz.cpl,,2
Add/Remove Programs (Set Program Access & Defaults ) control appwiz.cpl,,3
Administrative Tools control admintools
Advanced User Accounts Control Panel (Vista/Win7) Netplwiz
Automatic Updates wuaucpl.cpl
Authorization Manager (Vista/Win7) azman.msc
Backup Status and Utility (Vista/Win7) sdclt
Bluetooth Transfer Wizard fsquirt
Calculator calc
Certificate Manager certmgr.msc
Character Map charmap
Check Disk Utility (XP) chkdsk
Clipboard Viewer clipbrd
Color Management colorcpl
Command Prompt cmd
Component Services dcomcnfg
Computer Management (XP) compmgmt.msc
Computer Management (Vista/Win7) CompMgmtLauncher
Control Panel control
Credential (passwords) Backup and Restore Wizard (Vista/Win7) credwiz
Date and Time Properties timedate.cpl
Device Manager devmgmt.msc
Direct X Control Panel* directx.cpl
Direct X Troubleshooter dxdiag
Disk Cleanup Utility cleanmgr
Disk Defragmenter (XP) dfrg.msc
Disk Defragmenter (Vista) dfrgui
Disk Defragmenter defrag
Disk Management diskmgmt.msc
Disk Partition Manager diskpart
Display Properties control desktop
Display Properties desk.cpl
Display Properties (Appearance) control color
Dr. Watson System Troubleshooting Utility drwtsn32
Driver Verifier Utility verifier
Driver Package Installer (Vista/Win7) dpinst
DVD Player dvdplay
Event Viewer eventvwr.msc
File Signature Verification Tool sigverif
Files and Settings Transfer Tool migwiz
Findfast findfast.cpl
Firewall Control Panel (Vista/Win7) FirewallControlPanel
Firewall Settings (Vista/Win7) FirewallSettings
Folders Properties control folders
Fonts control fonts
Fonts Folder fonts
Game Controllers joy.cpl
Group Policy Editor (XP Prof) gpedit.msc
IExpress - Turn a cmd/vbs script into an installer .exe file C:\Windows\System32\iexpress.exe (example)
Indexing Service ciadv.msc
Internet Properties inetcpl.cpl
IP Configuration ipconfig
iSCSI Initiator (Vista/Win7) iscsicpl
Keyboard Properties control keyboard
Language Pack Installer (Vista/Win7) lpksetup
Local Security Policy secpol.msc
Local Users and Groups (XP) lusrmgr.msc
Log out logoff
Microsoft Access* msaccess
Microsoft Excel* excel
Microsoft Malicious Software Removal Tool mrt
Microsoft Paint mspaint
Microsoft Powerpoint* powerpnt
Microsoft Support Diagnostic Tool (Vista/Win7) msdt
Microsoft Word* winword
Mouse Properties control mouse
Mouse Properties main.cpl
MSN Messenger* msnmsgr
Network Connections control netconnections
Network Connections ncpa.cpl
Network Setup Wizard netsetup.cpl
Notepad notepad
ODBC Data Source Administrator odbccp32.cpl
32-bit ODBC driver under 64-bit platform = C:\windows\sysWOW64\odbcad32.exe
64 bit ODBC driver under 64-bit platform = C:\windows\system32\odbcad32.exe
On Screen Keyboard osk
Paint pbrush
Password Properties password.cpl
Performance Monitor perfmon.msc
Phone and Modem Options telephon.cpl
Phone Dialer dialer
Power Configuration powercfg.cpl
Printers and Faxes control printers
Printers Folder printers
Private Character Editor eudcedit
Quicktime* QuickTime.cpl
Quicktime Player* quicktimeplayer
Regional Settings intl.cpl
Registry Editor regedit
Registry Editor regedit32
Reliability and Performance Monitor perfmon.msc
Remote Assistance(Vista/Win7) msra
Remote Desktop mstsc
Removable Storage ntmsmgr.msc
Removable Storage Operator Requests ntmsoprq.msc
Resultant Set of Policy (XP Prof) rsop.msc
Scanners and Cameras sticpl.cpl
Scheduled Tasks control schedtasks
Security Center wscui.cpl
Services services.msc
Shared Creation Wizard shrpubw
Shared Folders fsmgmt.msc
Shut Down Windows shutdown
Software Licensing/Activation (Vista/Win7) slui
Sounds and Audio mmsys.cpl
Sound Recorder (Vista/Win7) soundrecorder
Sound Volume (Vista/Win7) sndvol
SQL Client Configuration cliconfg
Sync Center mobsync
Syncronization Tool mobsync
System Configuration Editor sysedit
System Configuration Utility msconfig
System File Checker Utility (Scan/Purge) sfc
System Information msinfo32
System Properties sysdm.cpl
System Properties (Vista/Win7) SystemPropertiesAdvanced, SystemPropertiesComputerName,
SystemPropertiesDataExecutionPrevention,SystemPropertiesHardware,
SystemPropertiesPerformance,SystemPropertiesProtection, SystemPropertiesRemote
Task Manager taskmgr
Telnet Client telnet
Trusted Platform Module Initialization Wizard (Vista/Win7) TpmInit
Tweak UI* tweakui
User Account Management nusrmgr.cpl
User Accounts (Autologon) control userpasswords2
Utility Manager utilman
Windows Error Reports wercon
Windows Features (Vista/Win7) optionalfeatures
Windows Firewall firewall.cpl
Windows Firewall with Advanced Security (Vista/Win7) wf.msc
Windows Image Acquisition (scanner)(Vista/Win7) wiaacmgr
Windows Magnifier magnify
Windows Management Infrastructure wmimgmt.msc
Windows Mobility Center (Mobile PCs only)(Vista/Win7) mblctr
Windows Security Center wscui.cpl
Windows System Security Tool syskey
Windows Update wupdmgr
Windows Update (Vista/Win7) wuapp
Windows Update Standalone Installer(Vista/Win7) wusa
Windows XP Tour Wizard tourstart
Windows Version (About Windows) winver
Wordpad write
* = optional component that may not be installed on all machines.
“The Macintosh uses an experimental pointing device called a 'mouse.' There is no evidence that people want to use these things” - John Dvorak
RUNAS
Execute a program under a different user account.
Syntax
RUNAS [/profile] [/env] [/netonly] /user:user Program
Key
/profile Option to load the user's profile (registry)
/env Use current environment instead of user's.
/netonly Use the credentials specified only for remote connections.
/user Username in form USER@DOMAIN or DOMAIN\USER
(USER@DOMAIN is not compatible with /netonly)
Program The command to execute
Enter the password when prompted.
When you start a program with RunAs /netonly, the program will execute on your local computer as the user you are currently logged on as, but any connections to other computers on the network will be made using the user account specified.
Without /netonly everything will run under the user account specified.
RunAs from Windows Explorer
Select an executable file, Shift-Right-click and select Run As..
This option can be hidden by setting
HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
HideRunAsVerb=1
ErrorLevel
The error level (%ERRORLEVEL%) returned by RunAs in Windows XP and above: success=0, failure=1
Examples
Run mycommand.exe as the user Jdoe on domain SS64dom
Runas /user:SS64Dom\jDoe "mycommand.exe"
Run CMD.exe as the Administrator on the local machine:
Runas /profile /user:DELLPC218\administrator CMD
Run Notepad.exe as the Domain Administrator on domain SS64dom
Runas /profile /env /user:SS64Dom\administrator NOTEPAD
Run Notepad.exe and open a file, escape the quote characters around the filename with \
Runas /env /user:[email protected] "NOTEPAD \"my file.txt\""
Notes:
The backslash \ is NOT the standard escape character used by other CMD commands.
RunAs Reqires the "Secondary Logon" service to be running.
“He who reigns within himself, and rules passions, desires, and fears, is more than a king” - Milton
Related:
AT - Run a command on a remote machine (at a scheduled time)
Aaron Margosis - Running with least privilege
joeware.net - CPAU (Create Process As User) like RunAs but with an options to encrypt the password.
PsExec - Execute process remotely
Powershell: you can run an entire powershell session via RunAs to elevate your permissions.
Equivalent bash command (Linux): SU - Switch User
RunDLL32.exe Run a DLL program. This command is available on all version of Windows from Win95 onwards, but the DLL's and options available do vary considerably. Many options are case sensitive.
Syntax
RUNDLL32.EXE dll_name,EntryPoint [options]
Examples
Un-install MS Java Virtual Machine (JVM):
RUNDLL32 advpack.dll,LaunchINFSection java.inf,UnInstall
Copy a floppy disk
RUNDLL32 diskcopy,DiskCopyRunDll
Lock workstation
RUNDLL32.exe user32.dll, LockWorkStation
Add a Network Printer
RUNDLL32 printui.dll,PrintUIEntry /ia /c\\server /m "AGFA-AccuSet v52.3"
/h "Intel" /v "Windows 2000" /f %windir%\inf\ntprint.inf
Add a Local Printer
RUNDLL32 printui.dll,PrintUIEntry /if /b "Test Printer" /c\\SERVER
/f "%windir%\inf\ntprint.inf" /r "lpt1:" /m "AGFA-AccuSet v52.3"
Add a printer connection that's available to anyone who logs on:
Rundll32 printui.dll,PrintUIEntry /ga /n\\Server\PrintShare
Display all the available commands for PRINTUI.DLL
RUNDLL32 printui.dll,PrintUIEntry /?
(add/remove print drivers, print queues, preferences, properties etc)
"If you're rich you can buy books. If you're poor, you need a library" - John Kenneth Galbraith
Related:
CON2PRT - Connect or disconnect a Printer
Qchange.vbs - Change Printer Connection
PRNCNFG - Add, delete, or list printers / connections, set the default printer.
PRNMNGR - Add, delete, or list printers / connections, set the default printer.
psexec -l -d "c:\program files\internet explorer\iexplore.exe"
Related:
RUNAS - Execute a program under a different user account
Equivalent Linux BASH command: xon - start an X program on a remote machine
PsFile (part of PsTools - download PsFile) Show files opened remotely, or close an open file (kill file locks)
Syntax
psfile [\\Computer [-u User [-p Passwd]]] [[Id | path] [-c]]
Options:
computer The remote computer on which to list files. Default = local system
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a username for login to remote computer(optional).
Id Identifier (as assigned by PsFile) of the file for which to display info or to close.
Path Full or partial path of files to match for information display or close.
-c Close the files identifed by ID or path.
Unlike the NET FILE command, PsFile does not truncate long filenames.
Examples:
List all the files on \\workstation64 that have been opened remotely:
psfile \\workstation64
Related:
NET FILE - Display all the open shared files on a server and the lock-id
OPENFILES - Query or display open files
Equivalent bash command (Linux): inotify - file-monitoring mechanism
PsGetSid (part of PsTools - download PsGetSid) Display the SID of a computer or a user.
Syntax
psgetsid [\\computer[,computer[,...] | @get_file] [-u user [-p passwd]]] [account|SID]
Options:
computer The remote computer on which to list files. Default = local system
@get_file Get the SID of every computer listed in the text file specified.
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a username for login to remote computer(optional).
account The user account to resolve to a user SID
Specify a user name if the account you are running from doesn't have administrative privileges on the computer you want to query.
Examples:
Get the SID of \\workstation64:
psgetsid \\workstation64
Get the domain SID for the domain: Niamod
psgetsid Niamod
Get the SID for the currently logged-in user
psgetsid %username%
Related:
SYSTEMINFO - List system configuration
PsInfo (part of PsTools - download PsInfo) List information about a system including the type of installation, kernel build, registered organization, owner, processor details, physical memory and the system install date.
Syntax
psinfo [\\computer[,computer[,..]] [options] [filter]
psinfo @file [options] [filter]
Options:
computer The computer(s) on which psinfo will list information. Default=local system
@file List info for every computer listed in the text file specified.
-c Print in CSV format.
-c -t d Print in CSV format, separate items with delimiter d.
-h Show list of installed hotfixes.
-s Show list of installed applications.
-d Show disk volume information: drive letter, format, capacity.
-p psswd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a user name for login to remote computer(optional).
filter Psinfo will only show data for the field matching the filter.
e.g. "psinfo service" lists only the service pack field.
PsInfo relies on remote Registry access to obtain its data, the remote system must be running the Remote Registry service and the account from which you run PsInfo must have access to the HKLM\System portion of the remote Registry.
In order to aid in automated Service Pack updates, PsInfo returns as a value the Service Pack number of system (e.g. 0 for no service pack, 1 for SP 1, etc).
Examples:
List disc information about \\workstation64:
psinfo \\workstation64 -d
psinfo -d | find "%"
Related:
PsGetSid - Display the SID of a computer or a user
SYSTEMINFO - List system configuration
FSUTIL fsinfo - File and Volume specific commands
Equivalent Linux BASH command: cat /proc/*
PsKill (part of PsTools - download PsKill) Kill processes by name or process ID
Syntax
pskill [- ] [-t] [\\computer [-u user] [-p passwd]] <process name | process id>
Options:
computer The computer on which the process is running. Default=local system
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a user name for login to remote computer(optional).
-t Kill the process and its descendants.
process id/name
The process or processes to be killed.
- Help, display the supported options.
To kill a process on a remote system requires administrative privileges on the remote system.
Examples:
Kill all instances of notepad.exe running on \\workstation64:
pskill \\workstation64 notepad
Related:
TSKILL - Kill process on a Terminal Server
PsList - List detailed information about processes
The process button of Task Manager in Windows will also identify the process ID (PID)
PsSuspend - Suspend processes (so they can be continued at a later point in time)
KILL - Remove a program from memory
Powershell: Stop-Process - Stop a running process (kill)
Equivalent bash command (Linux): kill - Stop a process from running.
PsList (part of PsTools - download PsList)
Process Status, list information about processes running in memory.
Syntax
pslist [-?] [-t] [-m] [-x] [\\computer [-u user] [-p passwd]] [name | pid]
Options:
computer The computer on which the process is running. Default=local system
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a user name for login to remote computer(optional).
-t Show statistics for all active threads on the system,
each thread is grouped with its owning process.
-m Show memory-oriented information for each process,
rather than the default of CPU-oriented information.
-x Show CPU, memory and thread information for each process specified.
name Scan only those processes that begin with the name process.
Thus:
pslist exp
will display processes that start with exp... Explorer, Export etc
-? Display options and units of measurement.
The default information listed includes the time the process has executed, the amount of time the process has executed in kernel and user modes, and the amount of physical memory that the OS has assigned the process.
When running PsList against a remote system you must have administrative rights on that system, and the system must be running the Remote Registry service.
Examples:
List all processes running on \\workstation64:
C:\> SC \\workstation64 start RemoteRegistry
C:\> pslist \\workstation64
Related:
PsKill - Kill processes by name or process ID
OPENFILES - Query or display open files, disconnect files opened by network users.
TASKLIST - List running applications and services
Windows Task Manager - List of running process IDs (PID)
PerfMon - Monitoring tool
Powershell: Get-Process - Get a list of processes on a machine (ps/gps)
Equivalent bash command (Linux): ps - Process status, information about processes running in memory.
PsLoggedOn (part of PsTools - download PsLoggedOn) See who is logged onto a computer, either locally or remotely
Syntax
psloggedon [- ] [-l] [-x] [\\computer | username]
Options:
computer The computer on which the process is running. Default=local system
-l Show only local logons instead of both local and network resource logons.
-x Don't show logon times.
username Search the network for computers to which that user is loggedon.
- Help, display all options and units of measurement used.
PsLoggedOn's definition of a locally logged on user is one that has their profile loaded into the Registry. If no one is currently logged on, PsLoggedOn will return the last logged on user.
Note that PsLoggedOn will show you as logged on via resource share to remote computers that you query because a logon is required for PsLoggedOn to access the Registry of a remote system.
Examples:
List all processes running on \\workstation64:
pslist \\workstation64
WhoIsLoggedOnWhere.cmd - script to list all workstations
Related:
net session - List or disconnect user sessions (Local machine only)
Powershell: Get-WMIobject Win32_ComputerSystem (UserName )
Equivalent bash command (Linux): who - Print who is currently logged in
PsLogList (part of PsTools - download) Event log records
Syntax
psloglist [- ] [\\computer[,computer[,...] | @file
[-u user [-p passwd]]] [-s [-t delim]]
[-m #|-n #|-h #|-d #|-w]
[-c][-x][-r][-a mm/dd/yy][-b mm/dd/yy]
[-f filter] [-i ID[,ID[,...] | -e ID[,ID[,...]]]
[-o event source[,event source][,..]]]
[-q event source[,event source][,..]]]
[-l event_log_file] <eventlog>
Options:
computer The computer on which the log resides. Default=local system
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a user name for login to remote computer(optional).
@file Execute the command on each of the computers listed in the file.
-a Dump records timestamped after specified date.
-b Dump records timestamped before specified date.
-c Clear the event log after displaying.
-d # Only display records from previous # days.
-e ID Exclude events with the specified ID or IDs (up to 10).
-f filter Filter event types with filter string (e.g. "-f w" to filter warnings).
-h # Only display records from previous # hours.
-i ID Show only events with the specified ID or IDs (up to 10).
-l event_log_file Dump records from the specified event log file.
-m # Only display records from previous # minutes.
-n # Only display # number of most recent entries.
-o event source
Show only records from the specified event source (e.g. \"-o cdrom\").
-q event source
Omit records from the specified event source or sources (e.g. \"-q cdrom\").
-r Dump log from least recent to most recent.
-s Print Event Log records one-per-line, with comma delimited fields.
This format is convenient for text searches, e.g. psloglist | findstr /i text
and for importing the output into a spreadsheet.
-t delim The default delimeter is a comma, but can be overriden with the specified character.
-w Wait for new events, dumping them as they generate (local system only).
-x Dump extended data.
eventlog application, system or security, only the first few letters need be used.
default=system log.
If your current security credentials would not permit access to the Event Log, specify a different username ( -u user ).
Examples:
List everything in the application event log on \\workstation64 from the last 24 hours:
psloglist \\workstation64 -h 24 application
Related:
elogdump - Resource Kit event log dump (local machine only)
Equivalent bash command (Linux): Logs are in plain ascii text
PsPasswd (part of PsTools - download) Change account password
Syntax
pspasswd [[\\computer[,computer[,..] | @file
[-u user [-p passwd]]] Username [NewPassword]
Options:
computer The computer on which the user account resides. Default=local system
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a user name for login to remote computer(optional).
@file Execute the command on each of the computers listed in the file.
Username Name of account for password change.
NewPassword The new password, If ommitted a NULL password is applied.
This tool allows administrators to create a batch file that will run against multiple computers to perform a mass change of the administrator password.
Examples:
Change the password for user JDoe on \\workstation64
pspasswd \\workstation64 jdoe password567
Related:
NET USER
Equivalent bash command (Linux): passwd - Modify a user password
Password generator
PsService (part of PsTools - download) View and control services
Syntax
psservice [\\computer [-u user] [-p passwd]] <command> <options>
Options:
computer The computer on which the service is running. Default=local system
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a user name for login to remote computer(optional).
commands:
query Display the status of a service
config Display the configuration of a service
setconfig Set the start type (disabled, auto, demand) of a service.
start Start a service
stop Stop a service
restart Stop and then restart a service
pause Pause a service
cont Resume a paused service
depend List the services dependent on the one specified
security Dump the service's security descriptor
find Search the network for the specified service
Typing a command followed by "- " displays the syntax for that command.
Service States:
1 - Stopped
2 - Start Pending
3 - Stop Pending
4 - Running
Examples:
Restart the spooler service on \\server64
psservice \\server64 restart spooler
Related:
NET START/STOP
SC - Service control
Powershell: Get-Service - Get a list of services
PsShutdown (part of PsTools - download)
Initiate a shutdown/reboot of a local or remote computer, logoff a user, lock a system.
Syntax
psshutdown [[\\computer[,computer[,..] | @file [-u user [-p passwd]]]
-s|-r|-h|-d|-k|-a|-l|-o
[-f] [-c] [-t nn|h:m] [-n s] [-v nn]
[-e [u|p]:xx:yy] [-m "message"]
Options:
computer The computer on which the user account resides. Default=local system
a wildcard (\\*), will affect all computers in the current domain.
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a user name for login to remote computer(optional).
@file Execute the command on each of the computers listed in the file.
-a Abort a shutdown (only possible while a countdown is in progress)
-c Allow the shutdown to be aborted by the interactive user
-d Suspend the computer
-e [u|p]:xx:yy
Shutdown reason code, 'u' = user, 'p'= planned shutdown.
xx is the major reason code (must be less than 256)
yy is the minor reason code (must be less than 65536)
-f Force all running applications to exit during the shutdown
instead of giving them a chance to gracefully save their data.
-h Hibernate the computer
-k Poweroff the computer (reboot if poweroff is not supported)
-l Lock the computer
-m "message" Specify a message to logged-on users when a shutdown countdown commences
-n Timeout in seconds connecting to remote computers
-o Logoff the console user
-r Reboot after shutdown
-s Shutdown without poweroff
-t Countdown in seconds until the shutdown (default: 20 seconds)
or the time of shutdown (in 24 hour notation)
-v Display message for the specified number of seconds before the shutdown.
default= display a shutdown notification dialog,
specifying a value of 0 results in no dialog.
- Help, display the supported options.
This tool allows administrators to create a batch file that will run against multiple computers to perform a mass change of the administrator password.
Examples:
Reboot \\workstation64 as part of an OS upgrade
psshutdown \\workstation64 -r -e p:2:3
Related:
SHUTDOWN - With full list of reason codes
TSSHUTDN - Remotely shut down or reboot a terminal server
Powershell:
$os = (Get-WmiObject Win32_OperatingSystem -ComputerName MyServer64)
$os.psbase.Scope.Options.EnablePrivileges = $true
$os.reboot()
Equivalent bash command (Linux): shutdown - Shutdown or restart linux
PsSuspend (part of PsTools - download) Suspend processes on the local or a remote system.
Syntax
pssuspend [- ] [-r] [\\computer [-u user] [-p passwd]] <process name | process id>
Options:
computer The computer on which the service resides. Default=local system
-p passwd Specify a password for user (optional). Passed as clear text.
If omitted, you will be prompted to enter a hidden password.
-u user Specify a user name for login to remote computer(optional).
-r Resume the processes specified if they are suspended.
process id/name
The process or processes to suspend or resume.
- Help, display the supported options.
Suspend is desirable in cases where a process is consuming a resource (e.g. network, CPU or disk) that you want to allow different processes to use. Rather than kill the process that's consuming the resource, suspending permits you to let it continue operation at some later point in time.
Examples:
Suspend the notepad process on \\workstation64
pssuspend \\workstation64 notepad
Related:
PsKill - Kill processes by name or process ID
PUSHD Change the current directory/folder and store the previous folder/path for use by the POPD command.
Syntax
PUSHD [drive]path
PUSHD
Key
drive The drive to switch to
path The folder to make 'current' (UNC names accepted)
If the drive is not specified, the current drive will be assumed.
If neither drive nor path are specified PUSHD will display a list of previous pathnames, you may switch back to any of these by using POPD one or more times.
If the path specified does not exist, PUSHD will return %errorlevel% =1
Examples
C:\demo> pushd \work
C:\work> pushd F:\music
F:\music> pushd
C:\work>
C:\demo>
F:\music> popd
C:\work>
Network paths
When a UNC path is specified, PUSHD will create a temporary drive map and will then use that new drive.
The temporary drive letters are allocated in reverse alphabetical order, so if Z: is free it will be used first.
If Command Extensions are disabled the PUSHD command will not accept a network (UNC) path.
#Ah, push it - push it good
Ah, push it - p-push it real good# - Salt 'N' Pepa
Related:
CD - Change directory
CMD - UNC options
PROMPT - Display the level of the PUSHD stack
Powershell: Push-Location - Push a location to the stack (pushd)
Powershell: cd - Jump to the previous working directory
Equivalent bash command (Linux): pushd - Save and then change the current directory
QGREP (Windows 2000 Resource Kit) Search file(s) for lines that match a given pattern.
Syntax
QGREP [options] [-e string] [-f file] [-i file] [strings] [files]
key:
-L Search strings literally.
-X Treat search strings as regular expressions.
-B Match pattern at beginning of line.
-E Match pattern at end of line.
-y Treat upper and lower-case as equivalent.
-x Print lines that match exactly.
-l Print only the file name if the file contains a match.
-n Print line numbers before each matching line.
-O Print seek offset before each matching line.
-v Print only lines that do not contain a match.
-z Print matching lines in MSC error message format.
-e string Treat the next argument as a literal search string.
-f file Read search strings from file.
-i file Read file list from file.
strings Specifies the search string(s).
files The file(s) to search, which can include wildcard characters
(* and ?)
Examples:
Find either arg1 or arg2 in FileName:
qgrep "arg1 arg2" FileName
Find arg1 arg2 in FileName:
qgrep -e "arg1 arg2" FileName.
White space separates search strings unless the argument is prefixed with -e.
QGREP "all out" x.y
means find either "all" or "out" in x.y, while
QGREP -e "all out" x.y
means find "all out".
grep is simply an odd concatenation of the phrase "grab regular expression"
Related Commands:
FINDSTR - Search for strings in files
Powershell: Where-Object - Filter objects passed along the pipeline.
Equivalent bash command (Linux): grep - Search file(s) for lines that match a given pattern
RASDIAL (Dial Up Networking) Manage RAS/DUN connections.
Dial a RAS connection:
RASDIAL entryname [/PHONEBOOK:PhonebookFile]
[/PHONE:PhoneNumber] [username [password|*]]
[/CALLBACK:CallBackNumber]
[/DOMAIN:domain][/PREFIXSUFFIX]
Hang up a RAS connection:
RASDIAL [entryname] /DISCONNECT
Display RAS Status:
RASDIAL
To use this command requires that Dial Up Networking Service be installed (via Control Panel - Networking)
The default location for PhoneBook entries is \%SystemRoot%\system32\ras\
"If advanced switching technology had not been developed and the telephone still had one operator for every 120 of some 100 million telephones, it would take 2,400,000 telephone operators (on three shifts) - John R. Pierce
Related:
RASPHONE - Manage RAS connections
Connection Manager Administration Kit - VPN connections (2003 Resource Kit)
RASMON - Windows 2000 GUI Resource Kit tool
CHECKRAS - SMS support tools
RASPHONE (Dial Up Networking) Manage Remote Access Service (RAS) connections.
This is a part of the Dial-Up Networking service, typically used to connect a PC to an Internet Service Provider.
Dial a RAS connection:
RASPHONE [-v] -f PhoneBook_file -d "PhoneBook_entry"
Hang up a RAS connection:
RASPHONE [-v] -f PhoneBook_file -h "PhoneBook_entry"
Display RAS Status dialogue box
RASPHONE -S
Other RAS options:
RASPHONE [-v] -f PhoneBook_file options "PhoneBook_entry"
OPTIONS
-a : Add new PhoneBook entry
-e : Edit an existing PhoneBook entry
-c : Clone an existing PhoneBook entry
-r : Delete/remove an existing PhoneBook entry
-v : Disable - 'grey out' the option to rename the PhoneBook_entry
To use this command requires that Dial Up Networking Service be installed (via Control Panel - Networking)
The default location for PhoneBook entries is %SystemRoot%\System32\ras\
"Someone invented the telephone, And interrupted a nation's slumber, Ringing wrong but similar numbers" - Ogden Nash
Related:
RASDIAL - Manage RAS connections
Connection Manager Administration Kit - VPN connections (2003 Resource Kit)
RASMON - Windows 2000 GUI Resource Kit tool
CHECKRAS - SMS support tools
RECOVER Recover a damaged file from a defective disk.
Syntax
RECOVER [drive:][path]filename
Recover is designed to help in the case of hardware failure. When a drive fails the failure is not always total, in other words you may be able to read some of the files but not others, and some files will be only partly readable.
The data on a disk is stored in tracks and sectors in an almost random manner. Data stored in a bad sectors cannot be read.
RECOVER reads a file sector by sector and recovers data from the good sectors. You must specify a filename.
Recover does not allow you to undelete a file.
Recover the files one at a time.
"Whom the gods love dies young - Menander 300 BC
Related:
CHKDSK - Check Disk - check and repair disk problems
Equivalent bash command (Linux): cksum - Print CRC checksum and byte counts (can detect problems but not fix them)
REG.exe Read, Set or Delete registry keys and values, save and restore from a .REG file.
Syntax:
REG QUERY [ROOT\]RegKey /v ValueName [/s]
REG QUERY [ROOT\]RegKey /ve --This returns the (default) value
REG ADD [ROOT\]RegKey /v ValueName [/t DataType] [/S Separator] [/d Data] [/f]
REG ADD [ROOT\]RegKey /ve [/d Data] [/f] -- Set the (default) value
REG DELETE [ROOT\]RegKey /v ValueName [/f]
REG DELETE [ROOT\]RegKey /ve [/f] -- Remove the (default) value
REG DELETE [ROOT\]RegKey /va [/f] -- Delete all values under this key
REG COPY [\\SourceMachine\][ROOT\]RegKey [\\DestMachine\][ROOT\]RegKey
REG EXPORT [ROOT\]RegKey FileName.reg
REG IMPORT FileName.reg
REG SAVE [ROOT\]RegKey FileName.hiv
REG RESTORE \\MachineName\[ROOT]\KeyName FileName.hiv
REG LOAD FileName KeyName
REG UNLOAD KeyName
REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/v ValueName] [Output] [/s]
REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/ve] [Output] [/s]
Key:
ROOT :
HKLM = HKey_Local_machine (default)
HKCU = HKey_current_user
HKU = HKey_users
HKCR = HKey_classes_root
ValueName : The value, under the selected RegKey, to edit.
(default is all keys and values)
/d Data : The actual data to store as a "String", integer etc
/f : Force an update without prompting "Value exists, overwrite Y/N"
\\Machine : Name of remote machine - omitting defaults to current machine.
Only HKLM and HKU are available on remote machines.
FileName : The filename to save or restore a registry hive.
KeyName : A key name to load a hive file into. (Creating a new key)
/S : Query all subkeys and values.
/S Separator : Character to use as the separator in REG_MULTI_SZ values
the default is "\0"
/t DataType : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ
Output : /od (only differences) /os (only matches) /oa (all) /on (no output)
Notes:
Any of the above commands can be run against a remote machine by adding \\MachineName to the command line, assuming the Remote Registry Service is running.
Registry data stored under HKCU will be visible and writable by the currently logged in user.
Registry data stored under HKLM will be visible to all users and writable by administrators.
To include a quote mark (") in the data, prefix it with the escape character (\) e.g. "Here is \" a quote"
Enclose ValueNames that contain the \ character in single quotes.
REG RESTORE has a tendency not to work, possibly due to firewall issues, Export and Import are much more reliable.
Examples
REG QUERY HKCU\Console\
REG QUERY HKCU\Console /v ScreenBufferSize
Find the location of the Start Menu folder:
REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v "Start Menu"
REG ADD HKCU\Software\SS64 /v Sample /d "some test data"
REG QUERY HKCU\Software\SS64 /v Sample
REG ADD HKLM\Software\DiLithium /v WarpSpeed /t REG_BINARY /d ffffffff
REG QUERY HKLM\Software\DiLithium /v WarpSpeed
REG COPY \\Wks580\HKCU\Software\SS64 HKCU\Software\SS64
REG COPY HKCU\Software\SS64 HKCU\Software\SS64Copy
REG EXPORT HKCU\Software\SS64 C:\MyReg.REG
REG IMPORT C:\MyReg.REG
REG SAVE HKCU\Software\SS64 C:\MyRegHive.hiv
REG RESTORE \\Wks580\HKCU\Software\SS64 C:\MyRegHive.hiv
Run a script at first logon (Run Once) to do this we edit the Default User profile by temporarily loading it as ZZZ:
REG LOAD HKU\ZZZ "C:\Documents and Settings\Default User\NTUSER.DAT"
REG ADD HKU\ZZZ\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce /v newUserProfile /t REG_EXPAND_SZ /d "D:\setup.cmd" /f
REG UNLOAD HKU\ZZZ
More examples are available via: REG QUERY /? REG ADD /? etc
"The way to a mans heart is through his stomach" - Fanny Fern (writer)
Related:
SETX - Set environment variables permanently, can also read a registry key and write the value to a text file.
REGEDIT - Load Registry settings from a .REG file
Dureg - Registry Size Estimator. (Win 2K ResKit)
Powershell: Get-ItemProperty / Set-ItemProperty - Retrieve / save registry Keys
Q325347 - Run a Logon Script once when a new user logs on, Windows 2003
Q284193 - Run a Logon Script once when a new user logs on, Windows 2000
Q945219 - Reg.exe fails for REG_EXPAND_SZ registry types
Q948698 - Remote access to 64-bit registry keys
REGEDIT
Import, export or delete registry settings from a text (.REG) file
Syntax
Export the Registry (all HKLM plus current user)
REGEDIT /E pathname
Export part of the Registry
REGEDIT /E pathname "RegPath"
Import a reg script
REGEDIT pathname
Silent import
REGEDIT /S pathname
Start the regedit GUI
REGEDIT
Open multiple copies of GUI (XP and 2003 only)
REGEDIT -m
Key
/E : Export
/S : Silent Import
How to add keys and values from the registry:
Create a text file like this:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\SomeKey]
"SomeStringValue"="Hello"
When double clicking this .reg file the key and value will be added.
Alternatively run REGEDIT MYKEY.REG from the command line.
How to delete keys and values from the registry:
Create a reg file like this, notice the hyphen inside the first bracket
Windows Registry Editor Version 5.00
[-HKEY_CURRENT_USER\SomeKey]
When double clicking this .reg file the key "SomeKey" will be deleted along with all string, binary or Dword values in that key.
If you want to just delete values, leaving the key in place, set the value you want to delete = to a hyphen
e.g.
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\SomeKey]
"SomeStringValue"=-
Again double clicking this .reg file will delete the values specified, or you can use REGEDIT /s MyDeleteScript.REG
Compare the Registry of two machines
Windiff is your friend, this simple GUI utility from the resource kit will list all the differences.
Comments
Within a registry file, comments can be preceded by "; "
e.g.
;
; Turn the NUMLOCK on at login
;
[HKEY_CURRENT_USER\Control Panel\Keyboard]
"InitialKeyboardIndicators"="2"
Under Windows NT 4 all registry scripts start with: REGEDIT4
(This version string will also work in XP and later versions of Windows.)
"I never make stupid mistakes. Only very, very clever ones" - John Peel
Related:
REG - Read, Set or Delete registry keys and values
SET - Display, set, or remove Windows NT environment variables
SETX - Set environment variables permanently
WMIC REGISTRY - Set registry options through WMI
Powershell: Get-ItemProperty / Set-ItemProperty - Retrieve / save registry Keys
Q322756 - How to backup and edit the registry
Dureg - Registry Size Estimator. (Win 2K ResKit)
XP Registry Keys - Commonly tweaked user interface settings
REGSVR32
Register or unregister a DLL.
Syntax
REGSVR32 [/U] [/S] [/C] [/I:[Command_Line]] DLL_Name
REGSVR32 [/U] [/S] [/C] /N /I:[Command_Line] DLL_Name
Key
/u Unregister Server.
/s Silent - no dialogue boxes.
/c Console output.
/n Don't call DllRegisterServer
/i Call DllInstall (or DllUninstall if /u is specified)
Command_Line An optional command line for DllInstall
Examples
Unregister (disable) XP Zip folders
REGSVR32 /u C:\Windows\System32\zipfldr.dll
Unregister (Disable) CAB file viewer:
REGSVR32 /u C:\Windows\System32\cabview.dll
Register (enable) XP Zip folders
REGSVR32 zipfldr.dll
Register (enable) CAB file viewer:
REGSVR32 cabview.dll
Register Windows Update DLLs (for those times when XP repair breaks Windows Update)
regsvr32 /s wuapi.dll
regsvr32 /s wuaueng1.dll
regsvr32 /s wuaueng.dll
regsvr32 /s wucltui.dll
regsvr32 /s wups2.dll
regsvr32 /s wups.dll
regsvr32 /s wuweb.dll
Register DAO 3.6 (Data Access Objects):
REGSVR32 "C:\Program Files\Common Files\Microsoft Shared\DAO\DAO360.DLL"
It costs nothing to register and will only take a moment...
Related:
Delsrv - unregister a service with the Services Control Manager. (Win 2K ResKit)
MSIEXEC - Microsoft Windows Installer
RUNDLL32 - Run a DLL command
Q249873 - Regsvr32 usage and error messages
REGINI (Resource kit) Change Registry Permissions.
Syntax
REGINI [-m \\machinename | -h hivefile hiveroot | -w Win95Directory]
[-i n] [-o outputWidth]
[-b] textFiles...
Key
-m A remote computer.
-h The local hive to manipulate.
-w Path to Windows 95 system.dat / user.dat files
-i n The display indentation multiple. Default is 4
-o outputWidth
How wide the output is to be. By default the
outputWidth is set to the width of the console window if standard
output has not been redirected to a file. In the latter case, an
outputWidth of 240 is used.
-b Make REGINI backward compatible with older versions of REGINI that
did not strictly enforce line continuations and quoted strings
Specifically, REG_BINARY, REG_RESOURCE_LIST and
REG_RESOURCE_REQUIREMENTS_LIST data types did not need line
continuations after the first number that gave the size of the data.
It just kept looking on following lines until it found enough data
values to equal the data length or hit invalid input. Quoted
strings were only allowed in REG_MULTI_SZ. They could not be
specified around key or value names, or around values for REG_SZ or
REG_EXPAND_SZ Finally, the old REGINI did not support the semicolon
as an end of line comment character.
textFiles One or more ANSI or Unicode text files with registry data.
The easiest way to understand the format of the input textFile is to use the REGDMP command with no arguments to dump the current contents of
your NT Registry to standard out. Redirect standard out to a file and this file is acceptable as input to REGINI
Some general rules are:
Semicolon character is an end-of-line comment character, provided it is the first non-blank character on a line
Backslash character is a line continuation character. All characters from the backslash up to but not including the first non-blank character of the next line are ignored. If there is more than one space before the line continuation character, it is replaced by a single space.
Indentation is used to indicate the tree structure of registry keys The REGDMP program uses indentation in multiples of 4. You may use hard tab characters for indentation, but embedded hard tab characters are converted to a single space regardless of their position
Values should come before child keys, as they are associated with the previous key at or above the value's indentation level.
For key names, leading and trailing space characters are ignored and not included in the key name, unless the key name is surrounded by quotes. Imbedded spaces are part of a key name.
Key names can be followed by an Access Control List (ACL) which is a series of decimal numbers, separated by spaces, bracketed by a square brackets (e.g. [8 4 17]). The valid numbers and their meanings are:
1 - Administrators Full Access
2 - Administrators Read Access
3 - Administrators Read and Write Access
4 - Administrators Read, Write and Delete Access
5 - Creator Full Access
6 - Creator Read and Write Access
7 - World Full Access
8 - World Read Access
9 - World Read and Write Access
10 - World Read, Write and Delete Access
11 - Power Users Full Access
12 - Power Users Read and Write Access
13 - Power Users Read, Write and Delete Access
14 - System Operators Full Access
15 - System Operators Read and Write Access
16 - System Operators Read, Write and Delete Access
17 - System Full Access
18 - System Read and Write Access
19 - System Read Access
20 - Administrators Read, Write and Execute Access
21 - Interactive User Full Access
22 - Interactive User Read and Write Access
23 - Interactive User Read, Write and Delete Access
If there is an equal sign on the same line as a left square bracket then the equal sign takes precedence, and the line is treated as a registry value. If the text between the square brackets is the string DELETE with no spaces, then REGINI will delete the key and any values and keys under it.
For registry values, the syntax is:
value Name = type data
Leading spaces, spaces on either side of the equal sign and spaces between the type keyword and data are ignored, unless the value name
is surrounded by quotes. If the text to the right of the equal sign is the string DELETE, then REGINI will delete the value.
The value name may be left off or be specified by an at-sign character which is the same thing, namely the empty value name. So the following two lines are identical:
= type data
@ = type data
This syntax means that you can't create a value with leading or trailing spaces, an equal sign or an at-sign in the value name, unless you put the name in quotes.
Valid value types and format of data that follows are:
REG_SZ text
REG_EXPAND_SZ text
REG_MULTI_SZ "string1" "str""ing2" ...
REG_DATE mm/dd/yyyy HH:MM DayOfWeek
REG_DWORD numberDWORD
REG_BINARY numberOfBytes numberDWORD(s)...
REG_NONE (same format as REG_BINARY)
REG_RESOURCE_LIST (same format as REG_BINARY)
REG_RESOURCE_REQUIREMENTS (same format as REG_BINARY)
REG_RESOURCE_REQUIREMENTS_LIST (same format as REG_BINARY)
REG_FULL_RESOURCE_DESCRIPTOR (same format as REG_BINARY)
REG_QWORD numberQWORD
REG_MULTISZ_FILE fileName
REG_BINARYFILE fileName
If no value type is specified, default is REG_SZ
For REG_SZ and REG_EXPAND_SZ, if you want leading or trailing spaces in the value text, surround the text with quotes. The value text
can contain any number of imbedded quotes, and REGINI will ignore them, as it only looks at the first and last character for quote characters.
For REG_MULTI_SZ, each component string is surrounded by quotes. If you want an imbedded quote character, then double quote it, as in string2 above.
For REG_BINARY, the value data consists of one or more numbers The default base for numbers is decimal. Hexidecimal may be specified by using 0x prefix. The first number is the number of data bytes, excluding the first number. After the first number must come enough numbers to fill the value. Each number represents one DWORD or 4 bytes. So if the first number was 0x5 you would need two more numbers after that to fill the 5 bytes. The high order 3 bytes
of the second DWORD would be ignored.
Whenever specifying a registry path, either on the command line or in an input file, the following prefix strings can be used:
HKEY_LOCAL_MACHINE
HKEY_USERS
HKEY_CURRENT_USER
USER:
Each of these strings can stand alone as the key name or be followed
a backslash and a subkey path.
There are several versions of regini with different syntax - the resource kit includes a word document with help and examples.
“If you're not failing every now and again, it's a sign you're not doing anything very innovative” - Woody Allen
Related:
REGEDIT - Import or export registry settings
REG - Registry: Read, Set, Export, Delete keys and values
Q245031 - Use a Script to Change Registry Permissions
REM
In a batch file REM at the start of a line signifies a comment or REMARK
alternatively adding :: at the start of a line has a similar effect
For example:
@ECHO OFF
::
:: First comment
::
REM Second comment
REM
::
Although you can use rem without a comment to add vertical spacing to a batch file, you can also use completely blank lines. The blank lines are ignored when processing the batch program.
The double-colon is not documented as a comment command, it is a special case of a CALL label that acts like a comment. The pro's and cons of each method are listed below.
Bugs
There are problems using a :: comment within an IF or FOR code bracket
e.g.
@echo off
FOR /L %%i IN (1,1,10) Do (
Echo before comment
:: Some comment
Echo after comment
)
The above will return the error :: was unexpected at this time.
In Windows 2000 and XP a comment like
::%~
or
REM %~ will be interpreted giving the error:
The following usage of the path operator in batch-parameter substitution is invalid: %~
In Windows NT 4 the REM command would incorrectly reset the %errorlevel% to 0
The bottom line on this is that you must test your comments to be sure they will be ignored as you expect.
Registry Comments
Within a registry file comments can be preceded by "; "
e.g.
;
; Turn the NUMLOCK on at login
;
[HKEY_CURRENT_USER\Control Panel\Keyboard]
"InitialKeyboardIndicators"="2"
FTP Comments
There is no valid comment character for FTP but you can cheat by escaping to the shell and running REM
e.g.
C:\WORK>type ftpscript
!REM This is a remark
bye
C:\WORK>ftp -s:ftpscript
ftp> !REM This is a remark
ftp> bye
C:\WORK>
#Now stand in the place where you work, Now face West
Think about the place where you live, Wonder why you haven't before# - REM 'Stand'
Related:
Powershell: # - Comment / Remark
Equivalent bash command: ### - Comment / Remark
REN Rename a file or files.
REN [drive:][path]old_filename new_filename
RENAME is a synonym for REN
You cannot specify a different drive or path for `new_filename` - use the MOVE command instead.
Both the source and/or destination may include wildcards.
Examples
Rename Monday.txt as Tuesday.txt
C:\> REN Monday.txt Tuesday.txt
Rename all text files in the current folder to have the extension .BAK
C:\> REN *.txt *.BAK
Rename Monday.txt as Monday.BAK
C:\> REN Monday.txt *.BAK
“We may dig in our heels and dare life never to change, but, all the same, it changes under our feet like sand under the feet of a sea gazer as the tide runs out. Life is forever undermining us. Life is forever washing away our castles, reminding us that they were, after all, only sand and sea water.” - Erica Jong (Parachutes and Kisses)
Related:
MOVE - Move a file from one folder to another
Stamp.cmd - Batch file to rename a file to include the current date and time.
Powershell: Rename-Item - Change the name of an existing item (ren/rni)
Equivalent bash command (Linux): mv - Move or rename files or directories
REPLACE Replace or update one file with another
Syntax
REPLACE Source_PathName Destination_path [/A] [/P] [/R] [/W]
REPLACE Source_PathName Destination_path [/P] [/R] [/S] [/W] [/U]
Key
path : The folder where files are to be replaced.
/A : Add any missing files.
/P : Prompt for confirmation (each file)
/R : Replace even Read-only files
/S : Include all subfolders of the destination.
/W : Wait for you to insert a floppy disk.
/U : Replace (update) only files that are older than the source.
Limitations:
When replacing in all subdirectories (/S ) you cannot ADD files (/A) or restrict to replacing older files (/U)
"That's the secret to life... replace one worry with another" - Charles M. Schulz
Related:
ROBOCOPY - Robust File and Folder Copy
MOVE - Move files from one folder to another folder on the same drive
DEL - Delete one or more files
COPY - Copy one or more files to another location
Equivalent bash command (Linux): install - Copy files and set attributes
RD Delete folder(s)
Syntax
RD pathname
RD /S pathname
RD /S /Q pathname
Key
/S : Delete all files and subfolders
in addition to the folder itself.
Use this to remove an entire folder tree.
/Q : Quiet - do not display YN confirmation
Place any long pathnames in double quotes.
RD does not support wildcards but you can remove several folders in one command by listing the pathname to each.
e.g.
RD c:\docs\Jan c:\docs\Feb "c:\My Documents\Mar"
RMDIR is a synonym for RD
“Dying is the most embarrassing thing that can happen to you, because someones got to take care of all your details” - Andy Warhol
Related:
MD - Create folder(s)
DEL - Delete selected files from an entire folder tree
Delrp - Delete a file/directory and NTFS reparse points.(Win 2K ResKit)
INUSE - updated file replacement utility (may not preserve file permissions)
Powershell: Remove-Item - Remove an item (rd/ri/rmdir)
Equivalent bash command (Linux): rmdir - Remove folder(s) rm -rf - Delete directory recursively
RMTSHARE.exe (NT 4 Resource kit - download)
Manage File and Printer shares, local or on a remote server.
Although missing from recent Resource kits, the old version appears to work fine under Windows 2000/XP/2003.
Syntax
Display all shares
RMTSHARE \\server
Display details of a specific share
RMTSHARE \\server\sharename
Share a Folder
RMTSHARE \\server\sharename=drive:path [options]
Share a Printer
RMTSHARE \\server\sharename=printername /PRINTER [options]
Edit an existing SHARE
RMTSHARE \\server\sharename [options]
Delete a SHARE
RMTSHARE \\server\sharename /DELETE
Options
/USERS:number
/UNLIMITED
/REMARK:"text"
/GRANT user:perm
/REMOVE user
Notes: Either specify /Users to restrict the number of connections that can be made OR specify /UNLIMITED
You can include several /GRANTs in a single command line.
Enclose paths that include spaces like this
\\server\"long share name"="c:\long file name"
“How to be green? consume less, share more, enjoy life” - Penny Kemp
Related:
CACLS - Apply File permissions
NET USE - Connect to a file share
REMOTE - Run a command on a remote computer (Resource Kit)
RUNDLL32 - Run a DLL command (add/remove print connections)
SHARE - List or edit a file share or print share (on any computer)
Powershell: Get-WmiObject win32_share
Equivalent bash command (Linux): mount - Mount a file system
ROBOCOPY.exe (XP Resource Kit/Standard Windows 7 command)
Robust File and Folder Copy.
By default Robocopy will only copy a file if the source and destination have different time stamps or different file sizes.
Syntax
ROBOCOPY Source_folder Destination_folder [files_to_copy] [options]
Key
file(s)_to_copy : A list of files or a wildcard.
(defaults to copying *.*)
Source options
/S : Copy Subfolders.
/E : Copy Subfolders, including Empty Subfolders.
/COPY:copyflag[s] : What to COPY (default is /COPY:DAT)
(copyflags : D=Data, A=Attributes, T=Timestamps
S=Security=NTFS ACLs, O=Owner info, U=aUditing info).
/SEC : Copy files with SECurity (equivalent to /COPY:DATS).
/DCOPY:T : Copy Directory Timestamps. ##
/COPYALL : Copy ALL file info (equivalent to /COPY:DATSOU).
/NOCOPY : Copy NO file info (useful with /PURGE).
/A : Copy only files with the Archive attribute set.
/M : like /A, but remove Archive attribute from source files.
/LEV:n : Only copy the top n LEVels of the source tree.
/MAXAGE:n : MAXimum file AGE - exclude files older than n days/date.
/MINAGE:n : MINimum file AGE - exclude files newer than n days/date.
(If n < 1900 then n = no of days, else n = YYYYMMDD date).
/FFT : Assume FAT File Times (2-second date/time granularity).
/256 : Turn off very long path (> 256 characters) support.
Copy options
/L : List only - don't copy, timestamp or delete any files.
/MOV : MOVe files (delete from source after copying).
/MOVE : Move files and dirs (delete from source after copying).
/Z : Copy files in restartable mode (survive network glitch).
/B : Copy files in Backup mode.
/ZB : Use restartable mode; if access denied use Backup mode.
/IPG:n : Inter-Packet Gap (ms), to free bandwidth on slow lines.
/R:n : Number of Retries on failed copies - default is 1 million.
/W:n : Wait time between retries - default is 30 seconds.
/REG : Save /R:n and /W:n in the Registry as default settings.
/TBD : Wait for sharenames To Be Defined (retry error 67).
Destination options
/A+:[RASHCNET] : Set file Attribute(s) on destination files + add.
/A-:[RASHCNET] : UnSet file Attribute(s) on destination files - remove.
/FAT : Create destination files using 8.3 FAT file names only.
/CREATE : CREATE directory tree structure + zero-length files only.
/DST : Compensate for one-hour DST time differences ##
/PURGE : Delete dest files/folders that no longer exist in source.
/MIR : MIRror a directory tree - equivalent to /PURGE plus all subfolders (/E)
Logging options
/L : List only - don't copy, timestamp or delete any files.
/NP : No Progress - don't display % copied.
/LOG:file : Output status to LOG file (overwrite existing log).
/UNILOG:file : Output status to Unicode Log file (overwrite) ##
/LOG+:file : Output status to LOG file (append to existing log).
/UNILOG+:file : Output status to Unicode Log file (append) ##
/TS : Include Source file Time Stamps in the output.
/FP : Include Full Pathname of files in the output.
/NS : No Size - don't log file sizes.
/NC : No Class - don't log file classes.
/NFL : No File List - don't log file names.
/NDL : No Directory List - don't log directory names.
/TEE : Output to console window, as well as the log file.
/NJH : No Job Header.
/NJS : No Job Summary.
Repeated Copy Options
/MON:n : MONitor source; run again when more than n changes seen.
/MOT:m : MOnitor source; run again in m minutes Time, if changed.
/RH:hhmm-hhmm : Run Hours - times when new copies may be started.
/PF : Check run hours on a Per File (not per pass) basis.
Job Options
/JOB:jobname : Take parameters from the named JOB file.
/SAVE:jobname : SAVE parameters to the named job file
/QUIT : QUIT after processing command line (to view parameters).
/NOSD : NO Source Directory is specified.
/NODD : NO Destination Directory is specified.
/IF : Include the following Files.
Advanced options you'll probably never use
/EFSRAW : Copy any encrypted files using EFS RAW mode. ##
/MT[:n] : Multithreaded copying, n = no. of threads to use (1-128) ###
default = 8 threads, not compatible with /IPG and /EFSRAW
The use of /LOG is recommended for better performance.
/SECFIX : FIX file SECurity on all files, even skipped files.
/TIMFIX : FIX file TIMes on all files, even skipped files.
/XO : eXclude Older - if destination file exists and is the same date
or newer than the source - don't bother to overwrite it.
/XC | /XN : eXclude Changed | Newer files
/XL : eXclude "Lonely" files and dirs (present in source but not destination)
This will prevent any new files being added to the destination.
/XX : eXclude "eXtra" files and dirs (present in destination but not source)
This will prevent any deletions from the destination. (this is the default)
/XF file [file]... : eXclude Files matching given names/paths/wildcards.
/XD dirs [dirs]... : eXclude Directories matching given names/paths.
XF and XD can be used in combination e.g.
ROBOCOPY c:\source d:\dest /XF *.doc *.xls /XD c:\unwanted /S
/IA:[RASHCNETO] : Include files with any of the given Attributes
/XA:[RASHCNETO] : eXclude files with any of the given Attributes
/IS : Include Same, overwrite files even if they are already the same.
/IT : Include Tweaked files.
/XJ : eXclude Junction points. (normally included by default).
/MAX:n : MAXimum file size - exclude files bigger than n bytes.
/MIN:n : MINimum file size - exclude files smaller than n bytes.
/MAXLAD:n : MAXimum Last Access Date - exclude files unused since n.
/MINLAD:n : MINimum Last Access Date - exclude files used since n.
(If n < 1900 then n = n days, else n = YYYYMMDD date).
/BYTES : Print sizes as bytes.
/X : Report all eXtra files, not just those selected & copied.
/V : Produce Verbose output log, showing skipped files.
/ETA : Show Estimated Time of Arrival of copied files.
## = New Option in Vista (XP027) all other options on this page are for the XP version of Robocopy (XP010)
### = New Option in Windows 7 and Windows 2008 R2
Robocopy EXIT CODES
File Attributes [RASHCNETO]
R – Read only
A – Archive
S – System
H – Hidden
C – Compressed
N – Not content indexed
E – Encrypted
T – Temporary
O - Offline
If either the source or desination are a "quoted long foldername" do not include a trailing backslash as this will be treated as an escape character, i.e. "C:\some path\" will fail but "C:\some path\\" or "C:\some path\." or "C:\some path" will work.
Robocopy will fail to copy files that are 'locked' by other users or applications, limiting the number of retries with /R:0 will speed up large jobs.
By copying only the files that have changed, robocopy can be used to backup very large volumes.
To limit the network bandwidth used by robocopy, specify the Inter-Packet Gap parameter /IPG:n
This will send packets of 64 KB each followed by a delay of n Milliseconds.
ROBOCOPY will accept UNC pathnames including UNC pathnames over 256 characters long.
/REG Writes to the registry at HKCU\Software\Microsoft\ResKit\Robocopy
/B (backup mode) will allow Robocopy to override file and folder permission settings (ACLs).
/XX If used in conjunction with /Purge or /Mir, this switch will take precedence and prevent any files being deleted from the destination.
All versions of Robocopy will copy security information (ACLs) for directories, version XP010 will not copy file security changes unless the file itself has also changed, this greatly improves performance.
To run ROBOCOPY under a non-administrator account will require backup files privilege, to copy security information auditing privilege is also required, plus of course you need at least read access to the files and folders.
Robocopy is a standard command in Windows 7 and above. The Windows Server 2003 Resource Kit Tools include Robocopy XP010, which can be run on NT 4/ Windows 2000. Robocopy does not run on Windows 95, or NT 3.5. (RoboCopy is a Unicode application).
Robocopy 'Jobs' and the 'MOnitor source' option provide an alternative to setting up a Scheduled Task to run a batchfile with a RoboCopy command.
Examples:
Copy files from one server to another (auto skip files already in the destination)
ROBOCOPY \\Server1\reports \\Server2\backup *.doc /S
List files over 32 MBytes in size:
ROBOCOPY C:\work /MAX:33554432 /L
Move files over 14 days old: (note the MOVE option will fail if any files are open and locked.)
ROBOCOPY C:\work C:\destination /move /minage:14
Backup a Server
The script below copies data from FileServ1 to FileServ2, the destination holds a full mirror along with file security info. When run regularly to synchronize the source and destination, robocopy will only copy those files that have changed (change in time stamp or size.)
@ECHO OFF
SETLOCAL
SET _source=\\FileServ1\e$\users
SET _dest=\\FileServ2\e$\BackupUsers
SET _what=/COPYALL /B /SEC /MIR
:: /COPYALL :: COPY ALL file info
:: /B :: copy files in Backup mode.
:: /SEC :: copy files with SECurity
:: /MIR :: MIRror a directory tree
SET _options=/R:0 /W:0 /LOG:MyLogfile.txt /NFL /NDL
:: /R:n :: number of Retries
:: /W:n :: Wait time between retries
:: /LOG :: Output log file
:: /NFL :: No file logging
:: /NDL :: No dir logging
ROBOCOPY %_source% %_dest% %_what% %_options%
Run two robocopy jobs at the same time with START /Min
Start /Min "Job one" Robocopy \\FileServA\C$\Database1 \\FileServeBackupA\c$\Backups
Start /Min "Job two" Robocopy \\FileServB\C$\Database2 \\FileServeBackupB\c$\Backups
Bugs
Version XP026 returns a success errorlevel even when it fails.
“One, a robot may not injure a human being, or through inaction, allow a human being to come to harm” - Isaac Asimov, Laws of Robotics from I. Robot, 1950
Related:
Robocopy EXIT CODES
COPY - Copy one or more files to another location
Robocopy GUI - Technet magazine (installs Robocopy XP026)
RichCopy free GUI copy utility - Ken Tamaru @ Microsoft
Copy Open files - with VShadow.exe (Shadow copies)
SyncToy - Microsoft Powertoy for synchronizing two folders
Convert KB/MB - Bits and Bytes, bandwidth calculations
Permcopy - Copy share & file ACLs from one share to another. (Win 2K ResKit)
Q323275 - Copy Security info without copying files (/SECFIX or /COPY:S)
Equivalent bash command:rsync - Remote file copy (Synchronize file trees)
ROUTE.exe
Manipulate network routing tables. Route packets of network traffic from one subnet to another by modifying the route table.
Syntax
Display route details:
ROUTE [-f] PRINT [destination_host] [MASK subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
Add a route:
ROUTE [-f] [-p] ADD [destination_host] [MASK subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
Change a route:
ROUTE [-f] CHANGE [destination_host] [MASK subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
Delete a route:
ROUTE [-f] DELETE [destination_host] [MASK subnet_mask_value] [gateway]
[METRIC metric] [IF interface_no.]
key
-f Clear (flush) the routing tables of all gateway entries. If this is
used in conjunction with one of the commands, the tables are
cleared prior to running the command.
destination_host
The address (or set of addresses) that you want to reach.
-p Create a persistent route - survives system reboots.
(not supported in Windows 95)
subnet_mask_value
The subnet mask value for this route entry.
This defines how many addresses are there.
If not specified, it defaults to 255.255.255.255.
gateway The gateway.
interface The interface number (1,2,...) for the specified route.
If the option `IF interface_no` is not given, ROUTE will try
to find the best interface available.
metric The metric, ie. cost for the destination.
Note that routes added to the table are not made persistent unless the -p switch is specified. Non-persistent routes only last until the computer is rebooted.
Symbolic names used for Destination_Host are looked up in the network database file NETWORKS.
The symbolic names for gateway are looked up in the host name database file HOSTS.
If the command is PRINT or DELETE. Destination or gateway can be a wildcard ('*'), or the gateway argument may be omitted.
An IP address mask of 0.0.0.0 means everything. (rather like the *.* wildcard). In other words it says: When matching this pattern, don't worry about matching any of the bits - everything matches.
If Destination_Host contains a * or ?, it is treated as a shell pattern, and only matching destination routes are printed. The '*' matches any string, and '?' matches any one char.
Examples:
157.*.1
157.*
127.*
*224*
"Get your kicks on ROUTE 66" - Jack Kerouac.
Related:
NETSTAT-rn - Display TCP/IP network connections, routing and protocol statistics
TRACERT - Trace route to a remote host
Q140859 - Win NT TCP/IP Routing Basics
Equivalent bash command (Linux): trace - Find the IP address of a remote host
Start | Run Commands for Windows XP, Vista and Windows 7: Accessibility Controls access.cpl
Accessibility Options control access.cpl
Adapter Troubleshooter (Vista/Win7) AdapterTroubleshooter
Add Hardware Wizard hdwwiz.cpl
Add/Remove Programs appwiz.cpl
Add/Remove Programs (Add New Programs) control appwiz.cpl,,1
Add/Remove Programs (Add Remove Windows Components) control appwiz.cpl,,2
Add/Remove Programs (Set Program Access & Defaults ) control appwiz.cpl,,3
Administrative Tools control admintools
Advanced User Accounts Control Panel (Vista/Win7) Netplwiz
Automatic Updates wuaucpl.cpl
Authorization Manager (Vista/Win7) azman.msc
Backup Status and Utility (Vista/Win7) sdclt
Bluetooth Transfer Wizard fsquirt
Calculator calc
Certificate Manager certmgr.msc
Character Map charmap
Check Disk Utility (XP) chkdsk
Clipboard Viewer clipbrd
Color Management colorcpl
Command Prompt cmd
Component Services dcomcnfg
Computer Management (XP) compmgmt.msc
Computer Management (Vista/Win7) CompMgmtLauncher
Control Panel control
Credential (passwords) Backup and Restore Wizard (Vista/Win7) credwiz
Date and Time Properties timedate.cpl
Device Manager devmgmt.msc
Direct X Control Panel* directx.cpl
Direct X Troubleshooter dxdiag
Disk Cleanup Utility cleanmgr
Disk Defragmenter (XP) dfrg.msc
Disk Defragmenter (Vista) dfrgui
Disk Defragmenter defrag
Disk Management diskmgmt.msc
Disk Partition Manager diskpart
Display Properties control desktop
Display Properties desk.cpl
Display Properties (Appearance) control color
Dr. Watson System Troubleshooting Utility drwtsn32
Driver Verifier Utility verifier
Driver Package Installer (Vista/Win7) dpinst
DVD Player dvdplay
Event Viewer eventvwr.msc
File Signature Verification Tool sigverif
Files and Settings Transfer Tool migwiz
Findfast findfast.cpl
Firewall Control Panel (Vista/Win7) FirewallControlPanel
Firewall Settings (Vista/Win7) FirewallSettings
Folders Properties control folders
Fonts control fonts
Fonts Folder fonts
Game Controllers joy.cpl
Group Policy Editor (XP Prof) gpedit.msc
IExpress - Turn a cmd/vbs script into an installer .exe file C:\Windows\System32\iexpress.exe (example)
Indexing Service ciadv.msc
Internet Properties inetcpl.cpl
IP Configuration ipconfig
iSCSI Initiator (Vista/Win7) iscsicpl
Keyboard Properties control keyboard
Language Pack Installer (Vista/Win7) lpksetup
Local Security Policy secpol.msc
Local Users and Groups (XP) lusrmgr.msc
Log out logoff
Microsoft Access* msaccess
Microsoft Excel* excel
Microsoft Malicious Software Removal Tool mrt
Microsoft Paint mspaint
Microsoft Powerpoint* powerpnt
Microsoft Support Diagnostic Tool (Vista/Win7) msdt
Microsoft Word* winword
Mouse Properties control mouse
Mouse Properties main.cpl
MSN Messenger* msnmsgr
Network Connections control netconnections
Network Connections ncpa.cpl
Network Setup Wizard netsetup.cpl
Notepad notepad
ODBC Data Source Administrator odbccp32.cpl
32-bit ODBC driver under 64-bit platform = C:\windows\sysWOW64\odbcad32.exe
64 bit ODBC driver under 64-bit platform = C:\windows\system32\odbcad32.exe
On Screen Keyboard osk
Paint pbrush
Password Properties password.cpl
Performance Monitor perfmon.msc
Phone and Modem Options telephon.cpl
Phone Dialer dialer
Power Configuration powercfg.cpl
Printers and Faxes control printers
Printers Folder printers
Private Character Editor eudcedit
Quicktime* QuickTime.cpl
Quicktime Player* quicktimeplayer
Regional Settings intl.cpl
Registry Editor regedit
Registry Editor regedit32
Reliability and Performance Monitor perfmon.msc
Remote Assistance(Vista/Win7) msra
Remote Desktop mstsc
Removable Storage ntmsmgr.msc
Removable Storage Operator Requests ntmsoprq.msc
Resultant Set of Policy (XP Prof) rsop.msc
Scanners and Cameras sticpl.cpl
Scheduled Tasks control schedtasks
Security Center wscui.cpl
Services services.msc
Shared Creation Wizard shrpubw
Shared Folders fsmgmt.msc
Shut Down Windows shutdown
Software Licensing/Activation (Vista/Win7) slui
Sounds and Audio mmsys.cpl
Sound Recorder (Vista/Win7) soundrecorder
Sound Volume (Vista/Win7) sndvol
SQL Client Configuration cliconfg
Sync Center mobsync
Syncronization Tool mobsync
System Configuration Editor sysedit
System Configuration Utility msconfig
System File Checker Utility (Scan/Purge) sfc
System Information msinfo32
System Properties sysdm.cpl
System Properties (Vista/Win7) SystemPropertiesAdvanced, SystemPropertiesComputerName,
SystemPropertiesDataExecutionPrevention,SystemPropertiesHardware,
SystemPropertiesPerformance,SystemPropertiesProtection, SystemPropertiesRemote
Task Manager taskmgr
Telnet Client telnet
Trusted Platform Module Initialization Wizard (Vista/Win7) TpmInit
Tweak UI* tweakui
User Account Management nusrmgr.cpl
User Accounts (Autologon) control userpasswords2
Utility Manager utilman
Windows Error Reports wercon
Windows Features (Vista/Win7) optionalfeatures
Windows Firewall firewall.cpl
Windows Firewall with Advanced Security (Vista/Win7) wf.msc
Windows Image Acquisition (scanner)(Vista/Win7) wiaacmgr
Windows Magnifier magnify
Windows Management Infrastructure wmimgmt.msc
Windows Mobility Center (Mobile PCs only)(Vista/Win7) mblctr
Windows Security Center wscui.cpl
Windows System Security Tool syskey
Windows Update wupdmgr
Windows Update (Vista/Win7) wuapp
Windows Update Standalone Installer(Vista/Win7) wusa
Windows XP Tour Wizard tourstart
Windows Version (About Windows) winver
Wordpad write
* = optional component that may not be installed on all machines.
“The Macintosh uses an experimental pointing device called a 'mouse.' There is no evidence that people want to use these things” - John Dvorak
RUNAS
Execute a program under a different user account.
Syntax
RUNAS [/profile] [/env] [/netonly] /user:user Program
Key
/profile Option to load the user's profile (registry)
/env Use current environment instead of user's.
/netonly Use the credentials specified only for remote connections.
/user Username in form USER@DOMAIN or DOMAIN\USER
(USER@DOMAIN is not compatible with /netonly)
Program The command to execute
Enter the password when prompted.
When you start a program with RunAs /netonly, the program will execute on your local computer as the user you are currently logged on as, but any connections to other computers on the network will be made using the user account specified.
Without /netonly everything will run under the user account specified.
RunAs from Windows Explorer
Select an executable file, Shift-Right-click and select Run As..
This option can be hidden by setting
HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
HideRunAsVerb=1
ErrorLevel
The error level (%ERRORLEVEL%) returned by RunAs in Windows XP and above: success=0, failure=1
Examples
Run mycommand.exe as the user Jdoe on domain SS64dom
Runas /user:SS64Dom\jDoe "mycommand.exe"
Run CMD.exe as the Administrator on the local machine:
Runas /profile /user:DELLPC218\administrator CMD
Run Notepad.exe as the Domain Administrator on domain SS64dom
Runas /profile /env /user:SS64Dom\administrator NOTEPAD
Run Notepad.exe and open a file, escape the quote characters around the filename with \
Runas /env /user:[email protected] "NOTEPAD \"my file.txt\""
Notes:
The backslash \ is NOT the standard escape character used by other CMD commands.
RunAs Reqires the "Secondary Logon" service to be running.
“He who reigns within himself, and rules passions, desires, and fears, is more than a king” - Milton
Related:
AT - Run a command on a remote machine (at a scheduled time)
Aaron Margosis - Running with least privilege
joeware.net - CPAU (Create Process As User) like RunAs but with an options to encrypt the password.
PsExec - Execute process remotely
Powershell: you can run an entire powershell session via RunAs to elevate your permissions.
Equivalent bash command (Linux): SU - Switch User
RunDLL32.exe Run a DLL program. This command is available on all version of Windows from Win95 onwards, but the DLL's and options available do vary considerably. Many options are case sensitive.
Syntax
RUNDLL32.EXE dll_name,EntryPoint [options]
Examples
Un-install MS Java Virtual Machine (JVM):
RUNDLL32 advpack.dll,LaunchINFSection java.inf,UnInstall
Copy a floppy disk
RUNDLL32 diskcopy,DiskCopyRunDll
Lock workstation
RUNDLL32.exe user32.dll, LockWorkStation
Add a Network Printer
RUNDLL32 printui.dll,PrintUIEntry /ia /c\\server /m "AGFA-AccuSet v52.3"
/h "Intel" /v "Windows 2000" /f %windir%\inf\ntprint.inf
Add a Local Printer
RUNDLL32 printui.dll,PrintUIEntry /if /b "Test Printer" /c\\SERVER
/f "%windir%\inf\ntprint.inf" /r "lpt1:" /m "AGFA-AccuSet v52.3"
Add a printer connection that's available to anyone who logs on:
Rundll32 printui.dll,PrintUIEntry /ga /n\\Server\PrintShare
Display all the available commands for PRINTUI.DLL
RUNDLL32 printui.dll,PrintUIEntry /?
(add/remove print drivers, print queues, preferences, properties etc)
"If you're rich you can buy books. If you're poor, you need a library" - John Kenneth Galbraith
Related:
CON2PRT - Connect or disconnect a Printer
Qchange.vbs - Change Printer Connection
PRNCNFG - Add, delete, or list printers / connections, set the default printer.
PRNMNGR - Add, delete, or list printers / connections, set the default printer.
REGSVR32 - Register or unregister a DLL
WMIC PRINTER - Set printing options through WMI.
Bruce Sanderson - Setup shared printers (PrintUI.dll)
DX21.com - A long list of rundll32 options
Q189105 - Add Printers with No User Interaction (Win 2000)
Q314486 - Add Printers with No User Interaction (Win XP)
SC.exe (Resource Kit)
Service Control - Create, Start, Stop, Query or Delete any Windows SERVICE. The command options for SC are case sensitive.
Syntax
SC [\\server] [command] [service_name] [Options]
Key
server : The machine where the service is running
service_name : The KeyName of the service, this is often but not always
the same as the DisplayName shown in Control Panel, Services.
You can get the KeyName by running:
SC GetKeyName <DisplayName>
commands:
query [qryOpt] Show status
queryEx [qryOpt] Show extended info - pid, flags
GetDisplayName Show the DisplayName
GetKeyName Show the ServiceKeyName
EnumDepend Show Dependencies
qc Show config - dependencies, full path etc
start START a service.
stop STOP a service
pause PAUSE a service.
continue CONTINUE a service.
create Create a service. (add it to the registry)
config permanently change the service configuration
delete Delete a service (from the registry)
control Send a control to a service
interrogate Send an INTERROGATE control request to a service
Qdescription Query the description of a service
description Change the description of a service
Qfailure Query the actions taken by a service upon failure
failure Change the actions taken by a service upon failure
sdShow Display a service's security descriptor using SDDL
SdSet Sets a service's security descriptor using SDDL
qryOpt:
driver|service|all
Query specific types of service
state= active|inactive|all
Query services in a particular state only
bufsize= bytes
ri= resume_index_number (default=0)
group= groupname
Query services in a particular group
Misc commands that don't require a service name:
SC QueryLock Query the LockStatus for the ServiceManager Database.
this will show if a service request is running
SC Lock Lock the Service Database
SC BOOT Values are {ok | bad} Indicates whether to save
the last restart configuration as the `last-known-good`
restart configuration
Options
The CREATE and CONFIG commands allow additional options to be set
see the build-in help: 'SC create' and 'SC config'
Note the qryOpt options above are case sensitive - they must be entered in lower case, also the position of spaces and = must be exactly as shown.
The SC command duplicates some aspects of the NET command but adds the ability to create a service.
SC query will display if a service is running, giving output like this:
SERVICE_NAME : messenger
TYPE : 20 WIN32_SHARE_PROCESS
STATE : 4 RUNNING
(STOPPABLE,NOT_PAUSABLE,ACCEPTS_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
To retrieve specific information from SC's output, pipe into FIND or FindStr
e.g.
C:\> SC query messenger | FIND "STATE" | FIND "STOPPED"
C:\> SC query messenger | FIND "STATE" | FIND "RUNNING"
The statements above will return an %ERRORLEVEL% = 1 if the text is not found
IF errorlevel 1 GOTO :my_subroutine
The NET START command can be used in a similar way to check if a service is running:
NET START | FIND "Service name" > nul
IF errorlevel 1 ECHO The service is not running
The service control manager will normally wait up to 30 seconds to allow a service to start - you can modify this time (30,000 milliseconds) in the registry
HKLM\SYSTEM\CurrentControlSet\Control
ServicesPipeTimeout (REG_DWORD)
Some options only take effect at the point when the service is started e.g. the SC config command allows the executable of a service to be changed. When the service next starts up it will run the new executable. Config changes requires the current user to have “permission to configure the service”.
Examples:
SC GetKeyName "task scheduler"
SC GetDisplayName schedule
SC start schedule
SC QUERY schedule
SC QUERY driver
SC QUERY state= all |findstr "DISPLAY_NAME STATE" >svc_installed.txt
SC \\myServer CONFIG myService obj= LocalSystem password= mypassword
SC CONFIG MyService binPath=c:\myprogram.exe obj=".\LocalSystem" password=""
Watch out for extra spaces:
SC QUERY state= all Works
SC QUERY sTate =all Fails!
"There is always room at the top" - Daniel Webster
Related:
DELSRV - Delete a service
INSTSRV - Install a service (run under a specific account)
NET - manage network resources
NETSVC - Command-line Service Controller (Win 2K ResKit)
PsService - View and control services
SCLIST - Display Services
Svcmon - Monitor services and raise an alert if they stop. (Win 2K ResKit)
Svcacls - Service ACL Editor (Win 2K ResKit)
SUBINACL - Set service permissions
WMIC SERVICE - WMI access to services
List of Windows Services
Q251192 - Create a Windows Service using SC
Q166819 - Control Services Remotely
Q170738 - Debug a Windows Service
Powershell: Get-Service - Get a list of services
Equivalent bash command (Linux): nice - Change job scheduling priority
SCHTASKS Create, delete, edit, list, start or stop a scheduled task.
Works on local or remote computers.
Syntax:
SCHTASKS /Create [Connect_Options] Create_Options /TN taskname
SCHTASKS /Delete [Connect_Options] /TN taskname [/F]
SCHTASKS /Query [Connect_Options] [/FO format] [/NH] [/V]
SCHTASKS /Run [Connect_Options] /TN taskname
SCHTASKS /End [Connect_Options] /TN taskname
SCHTASKS /Change [Connect_Options] {[/RU username] [/RP password] [/TR taskrun]} /TN taskname
Connect_Options:
/S system # Remote system (default is local)
[/U username [/P password]] # Submit job under this name
Create_Options:
/TR taskrun # Pathname of the executable to run
/ST starttime # HH:MM:SS (24 hour)
[/RU username [/RP password]] # Run job as this user
/SC schedule [/MO modifier] # When to run, see below
[/D day] # Day = MON,TUE,WED,THU,FRI,SAT,SUN
[/M months] # Month=JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC.
[/I idletime] # 1 - 999 minutes (ONIDLE task only)
[/SD startdate] [/ED enddate] # Start and end date "dd/mm/yyyy"
options:
/TN A name for the task
/F Force delete, ignore warnings even if the task is currently runnning.
/FO Output format: TABLE, LIST, CSV
/NH No header
/V Verbose output
Notes:
For MONTHLY schedules give the DAY as a number 1 - 31 (default=1)
To prompt for the password, specify /RP * or /RP none
The User Account under which the Schedule service runs may require specific file access permissions, user permissions and drive mappings.
If the /RU username and /RP Password parameters match the currently logged-in user, the task will run interactively (visible in the foreground).
For the system account, /RU username can be written as "", "NT AUTHORITY\SYSTEM" or "SYSTEM", a Password is not required. Thesystem account has full access to the local machine but has no permissions on any other machines (or mapped drives) across the Network.
/SC schedule The schedule frequency.
Valid schedules: MINUTE,HOURLY,DAILY,WEEKLY,MONTHLY, ONCE,ONSTART,ONLOGON,ONIDLE.
/MO modifiers allow finer control:
MINUTE: 1 - 1439 minutes.
HOURLY: 1 - 23 hours.
DAILY: 1 - 365 days.
WEEKLY: 1 - 52 weeks.
ONCE: No modifiers.
ONSTART: No modifiers.
ONLOGON: No modifiers.
ONIDLE: No modifiers.
MONTHLY: 1 - 12, or FIRST, SECOND, THIRD, FOURTH, LAST, LASTDAY.
Power Saving
The property for "Wake up the machine to run this task" cannot be set using schtasks, but this property is essential if you need the task to run on a machine that has PowerSaving enabled.
To work around this, create a task on one computer using the control panel GUI. This will create a .job file in C:\%windir%\Tasks\
To replicate the scheduled task onto other machines copy the .JOB file to C:\%windir%\Tasks on each machine.
This techique will not retain any system account credentials, so if you need to run the tasks under System, run the following after copying the .JOB file:
SCHTASKS /CHANGE /RU "NT Authority\System" /TN "Yourtaskname"
Examples:
Create a task to run at 11 pm every weekday
SCHTASKS /Create /SC weekly /D MON,TUE,WED,THU,FRI /TN MyDailyBackup /ST 23:00:00 /TR c:\backup.cmd /RU MyDomain\MyLogin /RP MyPassword
Now delete the task:
SCHTASKS /Delete /TN "MyDailyBackup" /f
Create a daily task to run a script at 5 pm:
SCHTASKS /create /tn "My Script" /tr "\"c:\my folder\script.cmd\" arguments" /sc daily /sd 12/29/2008 /st 17:00
Task Scheduler options are stored in the registry
HKLM\SOFTWARE\Microsoft\SchedulingAgent\
"We don't wake up for less than $10,000 a day" - Linda Evangelista
Related:
Q823093 - Scheduled task does not run when the Path contains a space
WAITFOR - Wait for or send a signal.
Powershell: To schedule a PS task call Powershell.exe
Equivalent bash command (linux): crontab - Schedule a command to run at a later time
SCLIST (Resource Kit) List Services
Syntax
SCLIST [options] [ComputerName]
Key
-r : Display only running services
-s : Display only stopped services
ComputerName : The computer running the services
(default = %ComputerName% )
Related:
NET - Manage network resources
SC - Service Control
NETSVC - Command-line Service Controller (Win 2K ResKit)
Powershell: Get-Service - Get a list of services
Equivalent bash command (Linux): ps - process status
SET
Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.
Syntax
SET variable
SET variable=string
SET /A variable=expression
SET "variable="
SET /P variable=[promptString]
SET "
Key
variable : A new or existing environment variable name
string : A text string to assign to the variable.
expression: : Arithmetic Sum
Also see SetX, VarSearch and VarSubstring for more advanced variable manipulation.
Variable names are not case sensitive but the contents can be. Variables can contain spaces.
The number one problem people run into with SET is having extra spaces around either the variable name or the string, SET is not forgiving of extra spaces like many other scripting languages.
The CMD shell will fail to read an environment variable if it contains more than 8,191 characters.
To display current variables:
Type SET without parameters to display all the current environment variables.
Type SET with a variable name to display that variable SET _department
or use ECHO: ECHO [%_department%]
The SET command invoked with a string (and no equal sign) will display a wildcard list of all matching variables
Display variables that begin with 'P': SET p
Display variables that begin with an underscore SET _
Examples
Storing a text string:
C:\> SET _dept=Sales and Marketing
C:\> set _
_dept=Sales and Marketing
One variable can be based on another, but this is not dynamic
E.g.
C:\> set xx=fish
C:\> set msg=%xx% chips
C:\> set msg
msg=fish chips
C:\> set xx=sausage
C:\> set msg
msg=fish chips
C:\> set msg=%xx% chips
C:\> set msg
msg=sausage chips
Avoid starting variable names with a number, this will avoid the variable being mis-interpreted as a parameter
%123_myvar% < > %1 23_myvar
To display undocumented system variables:
SET "
Prompt for user input
@echo off
Set /P _dept=Please enter Department:
If "%_dept%"=="" goto :sub_error
If /i "%_dept%"=="finance" goto sub_finance
If /i "%_dept%"=="hr" goto sub_hr
goto:eof
:sub_finance
echo You chose the finance dept
goto:eof
:sub_hr
echo You chose the hr dept
The /P switch allows you to set a variable equal to a line of input entered by the user.
The PromptString is displayed before the user input is read. The PromptString can be empty.
The CHOICE command is an alternative to SET /P
To place the first line of a file into a variable:
Set /P _MyVar=<MyFilename.txt
CALL SET
SET can be CALLed allowing a variable substring to be evaluated:
SET
SET length=9
SET string=The quick brown fox jumps over the lazy dog
CALL SET substring=%%string:~%start%,%length%%%
ECHO (%substring%)
Deleting an environment variable
Type SET with just the variable name and an equals sign:
SET _department=
Better still, to be sure there is no trailing space after the = use:
(SET _department=)
or
SET "_department="
Variable names can include Spaces
A variable can contain spaces and also the variable name itself may contain spaces, therefore the following assignment:
SET my var=MyText
will create a variable called "my var"
Similarly
SET _var =MyText
will create a variable called "_var " - note trailing space
To avoid problems with extra spaces appearing in your output, issue SET statements in parentheses, like this
(SET _department=Some Text)
Alternatively you can do
SET "_department=Some Text"
Note: if you wanted to actually include a bracket in the variable you need to use an escape character.
The SET command will set ERRORLEVEL to 1 if the variable name is not found in the current environment.
This can be detected using the IF ERRORLEVEL command
Arithmetic expressions (SET /a)
The expression to be evaluated can include the following operators:
Multiply *
Divide /
Add +
Subtract -
Modulus %
AND &
OR |
XOR ^
LSH <<
RSH >>
Multiply Variable *=
Divide Variable /=
Add Variable +=
Subtract Variable -=
AND Variable &=
OR Variable |=
XOR Variable ^=
LSH Variable <<=
RSH Variable >>=
SET /a calculations
Enclose any logical expressions in "quotes"
Several calculations can be put on one line if separated with commas.
Warning: any SET /A calculation that returns a fractional result will be rounded down to the nearest whole integer.
Examples:
SET /A _result=2+4
(=6)
SET /A _result=5
(=5)
SET /A _result+=5
(=10)
SET /A _result="2<<3"
(=16) { 2 Lsh 3 = binary 10 Lsh 3 = binary 10000 = decimal 16 }
SET /A _result="5%%2"
(=1) { 5/2 = 2 + 2 remainder 1 = 1 }
Modulus operator - note that in a batch script, (as opposed to on the command-line), you need to double up the % to %%
SET /A will treat any character string in the expression as an environment variable name. This allows you to do arithmetic with environment variable values without having to type any % signs to get the values. SET /A _result=5 + _MyVar
Leading Zero will specify Octal
Numeric values are decimal numbers, unless prefixed by
0x for hexadecimal numbers,
0 for octal numbers.
So 0x12 = 022 = 18 decimal
The octal notation can be confusing - all numeric values that start with zeros are treated as octal but 08 and 09 are not valid numbers because 8 and 9 are not valid octal digits.
This is often a cause of error when performing date arithmetic. For example SET /a _day=07 will return the value=7, but SET /a _day=09 will return an error.
Permanent Changes
Changes made using the SET command are NOT permanent, they apply to the current CMD prompt only and remain only until the CMD window is closed.
To permanently change a variable at the command line use SetX
or in the GUI - Control Panel, System, Environment, System/User Variables
Changing a variable permanently with SetX will not affect any CMD prompt that is already open.
Only new CMD prompts will get the new setting.
You can of course use SetX in conjunction with SET to change both at the same time, but neither SET or SetX will affect other CMD sessions that are already running. When you think about it - this is a good thing.
It is also possible (although undocumented) to add permanent env variables to the registry [HKEY_CURRENT_USER\Environment]
(using REGEDIT)
System Environment variables can also be found in [HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
Autoexec.bat
Any SET statement in c:\autoexec.bat may be parsed at boot time
Variables set in this way are not available to 32 bit gui programs - they won't appear in the control panel.
They will appear at the CMD prompt.
If autoexec.bat CALLS any secondary batch files, the additional batch files will NOT be parsed at boot.
This behaviour can be useful on a dual boot PC.
If Command Extensions are disabled all SET commands are disabled other than simple assignments like:
_variable=MyText
# I got my mind set on you
# I got my mind set on you... - George Harrison
Related:
CALL - Evaluate environment variables
SETX - Set an environment variable permanently.
SETLOCAL - Begin localisation of environment variable changes
ENDLOCAL - End localisation of environment changes, use to return values
EXIT - Set a specific ERRORLEVEL
Parameters - get a full or partial pathname from a command line variable.
PATH - Change the %PATH% environment variable.
PATHMAN - This Resource Kit utility allows quick modification of both the system and user paths. Pathman can resolve many problems such as duplicate characters, and can improve performance by removing duplicate paths. For details see Pathman.wri in the resource kit.
REGEDIT - Import or export registry settings
WMIC ENVIRONMENT - Set environment vars through WMI
NIST Digital Library of Mathematical Functions
Powershell: Set-Variable - Set a variable and a value (set/sv)
Powershell: Read-Host - Prompt for user input
Equivalent bash command (Linux): env - Display, set, or remove environment variables
SETLOCAL Set options to control the visibility of environment variables in a batch file.
Syntax
SETLOCAL
SETLOCAL EnableDelayedExpansion
SETLOCAL EnableExtensions | DisableExtensions
Key
EnableDelayedExpansion Expand variables at execution time rather than at parse time.
EnableExtensions Attempt to enable Command extensions.
DisableExtensions Attempt to disable Command extensions.
SETLOCAL on it's own, usually at the start of a batch file, will begin localisation of Environment Variables.
Issuing a SETLOCAL command, the batch script will inherit all current variables from the master environment/session.
Issuing an ENDLOCAL command will restore any environment variables present before the SETLOCAL was issued.
If a batch script does not use SETLOCAL and ENDLOCAL then all variables will be Global, i.e. visible and modifiable by other scripts.
Although global variables are easy to work with they are not good practice - for example if you have several batch scripts dealing with filenames (and these scripts may be CALLing one another), the first script may have a variable called _filename, the second script a different variable called file-name (a different name to avoid conflicting with the first script) a third script now needs something like file_name this quickly becomes very difficult to manage.
With local variables you are free to use the same variable names in multiple batch scripts - there is no conflict because the local variables are not visible to any other script.
Local Variables can be passed from one batch routine to another with the ENDLOCAL command.
EnableDelayedExpansion
Setting EnabledDelayedExpansion will cause each variable to be expanded at execution time rather than at parse time.
EnableDelayedExpansion is Disabled by default.
Overloading a variable
SETLOCAL can be used more than once in the same batch file so that multiple values can be stored in the same Environment Variable. To keep track of variable definitions, SETLOCAL and ENDLOCAL statements should be paired.
@echo off
SETLOCAL
::Standard commission
SET _Commission=20
echo %_Commission%
::Premium commission
SETLOCAL
set _Commission=30
echo %_Commission%
::back to Standard commission
ENDLOCAL
echo %_Commission%
DISABLEEXTENSIONS
Command Extensions are enabled by default, there is rarely any need to disable them.
If Command Extensions are permanently disabled or if a script is running under the Windows 95 command processor command.com then SETLOCAL ENABLEEXTENSIONS will not be able to restore them.
A batch file to warn if command extensions are not available:
VERIFY errors 2>nul
SETLOCAL ENABLEEXTENSIONS
IF ERRORLEVEL 1 echo Unable to enable extensions
Errors
SETLOCAL will set an ERRORLEVEL if given an argument: It will be zero if one of the two valid arguments is given and one otherwise.
"A local shop for local people" - The League Of Gentlemen
Related:
ENDLOCAL - End localisation of environment changes in a batch file.
Syntax: Functions - How to package blocks of code
Powershell: Set-PSdebug -strict - Equivalent to 'Option Explicit' in VB
Equivalent bash command (Linux): readonly - Mark variables/functions as readonly
SETX.exe (Resource Kit, Windows 7)
Set environment variables permanently
SETX can be used to set Environment Variables for the machine or currently logged on user:
SETX Variable Value
SETX Variable Value -m
Key:
-m Set the value in the Machine environment (HKLM)
Default is User (HKCU)
SetX can also be used in modes to edit the Registry or edit CR-LF text files, (like win.ini) for most purposes these tasks are better done with other tools in the resource kit, e.g. the REG command.
Because SetX writes variables to the master environment in the registry. Edits will only take effect when a new command window is opened - they do not affect the current command session.
Deleting variables
A value of "" (empty quotes) will appear to delete the variable - it's not shown by SET but the variable name will remain in the registry. Either use the GUI (recommended) or delete the value from the registry with REG
REG delete HKCU\Environment /V _myvar
Deleting a variable with REG does not take effect until next logon due to caching of registry data. The type is REG_EXPAND_SZ.
Examples:
Set the variable _mypc to be COMPAQ in the users permanent environment:
SetX _mypc COMPAQ
Delete the variable _mypc in the users permanent environment:
REG delete HKCU\Environment /V _mypc
Set the variable _myTimeZone in both the immediate user session and the permanent environment:
SET _myTimeZone=GMT
SetX _myTimeZone GMT
Store the value of %my_important_var% in a second environment variable.
SetX _mybackupvar %my_important_var%
Sets the value of _mypath to be equal to the value of the %PATH% environment variable, _mypath will then remain the same even if the PATH variable changes in the future:
SetX _mypath ~PATH~
Machine variables
These are stored on the machine and won't follow a users roaming profile.
To set a machine variable (-m) requires Administrator rights.
Create a machine variable:
SetX _myvar COMPAQ -m
Delete a machine variable:
REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /V _myvar
"You are never dedicated to something you have complete confidence in. No-one is fanatically shouting that the sun is going to rise tomorrow. When people are fanatically devoted to political or religious faiths or any other kind of dogmas or goals, its always because these dogmas or goals are in doubt" - Robert M Pirsig
Related:
SET - Display, set, or remove environment variables
REG - Delete keys or values from the registry
Q104011 - Modify variables by editing the Registry
SETENV - Vincent Fatica's improved version
Powershell: Set-Variable - Set a variable and a value (set/sv)
Equivalent bash command (Linux): env - Display, set, or remove environment variables
SFC (Windows XP, Server 2003, Win 7) System File Checker
Syntax
Sfc [/Scannow] [/Scanonce] [/Scanboot] [/Revert] [/Purgecache] [/Cachesize=x]
Key
/Scannow Scan all protected system files immediately and replace
incorrect versions with correct Microsoft versions.
May require access to the Windows installation source files.
/Scanonce Scan all protected system files one time when you restart your computer.
May require access to the Windows installation source
files when you restart the computer.
The SfcScan DWORD value is set to 2 in the following registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
/Scanboot Scan all protected system files every time you start your computer.
May require access to the Windows installation source files every
time you start the computer.
The SfcScan DWORD value is set to 1 in the following registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
/Revert Return scan to the default setting
(do not scan protected files when you start the computer).
The default cache size is not reset when you run this command.
/Purgecache Purge the file cache and scan all protected system files immediately.
May require access to the Windows installation source files.
/Cachesize=x Set the file cache size to x megabytes (MB).
The default size of the cache is 50 MB.
This command requires you to restart the computer, and then run
the /purgecache command to adjust the size of the on-disk cache.
This command sets the SfcQuota DWORD value to x in the following registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
Under Windows 7, SFC must be run from an elevated command prompt.
“Oh, yes, I've learned from my mistakes and I'm sure I could repeat them exactly” - Sir Arthur Streeb-Greebling (aka Peter Cook)
Related:
SLMGR - Software Licensing Management
WINMSD - Windows system diagnostics
Share.vbs (Resource Kit) List or edit a file share or print share (on any computer)
Although missing from recent Resource Kits, this VBS script does still work under recent versions of Windows. The preferred method for creating shares is the RMTShare command, which can also grant permissions.
Syntax:
List Shares
Share.vbs /L [/S <server>] [/U <username>] [/W <password>] [/O <outputfile>]
Create a Share
Share.vbs /C /N <name> /P <path> [/T <type>] [/V <description>]
[/S <server>] [/U <username>] [/W <password>] [/O <outputfile>]
Delete a Share
Share.vbs /D /N <name>
[/S <server>] [/U <username>] [/W <password>] [/O <outputfile>]
Key:
/L List
/C Create
/D Delete
/N name Name of the share to be created or deleted.
/P path Path of the share to be created.
/v description A description for the share.
/T type Type of the share to be created. (Disk, Printer, IPC or Special)
/S server A machine name.
/U username The current user's name.
/W password Password of the current user.
/O outputfile Output file name.
Examples:
List the shares on the machine \\Frodo
cscript Share.vbs /L /s Frodo
Create a file share called "scratch" on the local machine:
cscript Share.vbs /c /n scratch /p "c:\my shared files" /t Disk /v "project files"
Delete the share named "scratch" on the machine \\Frodo
cscript Share.vbs /d /n scratch /s Frodo
"The inherent vice of capitalism is the unequal sharing of blessings,
the inherent vice of Socialism is the equal sharing of miseries." - Winston Churchill
Related:
CACLS - Display or modify Access Control Lists (ACLs) for files and folders
RMTShare - The preferred method for creating a file system share (it can also grant permissions)
RUNDLL32 - Run a DLL command (add/remove print connections)
Powershell: Get-WmiObject win32_share
Equivalent bash command (Linux): mount - Mount a file system
SHIFT
Change the position of command line parameters in a batch file.
Syntax
SHIFT [/n]
Key
/n Start at the nth argument, where n may be between zero and eight.
Relative pathnames
Examples:
Given %1=the, %2=quick, %3=brown
SHIFT
will result in %1=quick, %2=brown
A second
SHIFT
will result in %1=brown
Given %1=the, %2=quick, %3=brown, %4=fox
SHIFT /2
will result in %1=the, %2=brown, %3=fox
Parse Command Line Arguments
:start
if "%1"=="" (goto :main)
:: Do whatever with token %1
Echo [%1]
:: Shift %2 into %1
SHIFT
goto :start
:main
::
The parameter %0 will initially refer to the path that was used to execute the batch - this could be MyBatch.cmd if in the current directory or a full path like C:\apps\myBatch.cmd
If SHIFT is used to move a text parameter into %0 then any references to %0 will refer instead to the current working directory, unless the new parameter value happens to contain a valid path.
For example:
%0\..\MyExecutable.exe
will run the MyExecutable from the same directory as the Batch file.
If the following parameter is passed to myBatch.cmd
myBatch.cmd D:\utils\
Then the following commands in myBatch will run MyExecutable.exe from the directory D:\utils\
SHIFT
%0\..\MyExecutable.exe
If Command Extensions are disabled, the SHIFT command will not support the /n switch
"If NumLock is on, pressing a key on the numeric keypad while holding SHIFT overrides NumLock and instead generates an arrow key" -OldNewThing
Related:
CALL - Call one batch program from another
SET - Display or edit environment variables
powershell: param( $var1, $var2,... )
Equivalent bash command (Linux): shift - Shift positional parameters
SHORTCUT.exe (NT Server Resource Kit)
Create a windows shortcut (.LNK file)
Syntax
SHORTCUT [options]
Key
Source options
-t target : The path and file name of the application/document to open.
-a arguments : The arguments passed when the shortcut is used.
-d directory : The folder to start the application in.
-i iconfile : The file the icon is in.
-x index : The index into the icon file.
options for the shortcut file to be created
-n name : The path and file name (.LNK) of the shortcut file.
-c : Change existing shortcut.
-r : Resolve broken shortcut.
-f : Force overwrite of an existing short cut.
-s : Make shortcut simple (don't use LinkResolve)
Export options
-u [spec] : ECHO the contents of an existing shortcut.
'all' is the same as 'natdix' but the letters
of 'natdix' specify the options to be exported
(the same option can be specified more than once
e.g. -u natn)
-l logfile : Save any error messages in the specified file
If shortcut.exe fails to create a new shortcut, it does NOT set an errorlevel.
Example
@ECHO off
MD %userprofile%"\start menu\programs\MY APP"
SHORTCUT -f -t C:\MyApp.exe -n %userprofile%"\start menu\programs\MY APP\MY APP"
For Windows XP and more recent systems, you are better off using a little .vbs script, as WSH is built-in from XP onwards, call the script like so:
CSCRIPT C:\myshortcut.vbs
Optional sections in the VBscript below are commented out:
Set oWS = WScript.CreateObject("WScript.Shell")
sLinkFile = "C:\MyShortcut.LNK"
Set oLink = oWS.CreateShortcut(sLinkFile)
oLink.TargetPath = "C:\Program Files\MyApp\MyProgram.EXE"
' oLink.Arguments = ""
' oLink.Description = "MyProgram"
' oLink.HotKey = "ALT+CTRL+F"
' oLink.IconLocation = "C:\Program Files\MyApp\MyProgram.EXE, 2"
' oLink.WindowStyle = "1"
' oLink.WorkingDirectory = "C:\Program Files\MyApp"
oLink.Save
Shortcut: NTFS file system tracking
If a shortcut to a file breaks because the destination file has moved, then by default Windows will attempt to automatically locate the shortcut destination by performing a search (this only applies to NTFS partitions). To turn this off - add a DWORD value of 1 to the registry:
HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
NoResolveTrack=1
Shortcut: Auto LinkResolve
By default shortcuts will include the destination machine, even for a target like C:\MyFile.doc
This is not immediately visible until the shortcut.LNK file is copied to another machine, the shortcut target will then be automatically updated to point back to \\Machine1\c$\MyFile.doc
To turn this behaviour off use shortcut.exe -s or add a DWORD value of 1 to the registry (before creating the shortcut):
HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
"LinkResolveIgnoreLinkInfo"=1
Favourites
Often confused with shortcuts, Internet Explorer Favourite (.URL) files are simple text files which you can create with a few ECHO statements.
"The reasonable man adapts himself to the world: the unreasonable one persists in trying to adapt the world to himself. Therefore all progress depends on the unreasonable man" - George Bernard Shaw
Related:
MD - Create folder(s)
Slow Network browsing (XP)
FSUTIL - Create a Hardlink
Q158682 - Shortcuts created resolve to UNC Path (Link Tracking)
Q150215 - Disable Automatic Shortcut Resolution
Q254493 - Shortcut.exe fails with sub-folder names.
Q263324 - Shortcut.exe truncates path names.
Equivalent bash command (Linux): symlink - Make a new name for a file, ln - Make links between files
SHOWGRPS (Resource Kit) List the Workgroups a user has joined.
Syntax
SHOWGRPS domain\username
SHOWGRPS username
If no username is specified SHOWGRPS will list the workgroups for the currently logged in user.
Example
SHOWGRPS ss64domain\user05
"Justice is such a fine thing that we cannot pay too dearly for it" - Alain-Rene Lesage
Related:
NET - add or remove a user from a workgroup
FINDGRP - List the (global or local) security groups a user has joined (NT 4 Reskit)
SHOWMBRS - List the members of an NT Workgroup
GRPTEST - SMS support tools - enumerate group membership for a user account.
SHOWACCS - Show access profile (Windows 2000)
SHOWMBRS (Resource Kit) List all the users who are members of a Workgroup.
Syntax
SHOWMBRS domain\Workgroup
SHOWMBRS Workgroup
A workgroup must be specified.
Example:
SHOWMBRS wg_finance
Related:
NET GROUP - add or remove a user from a workgroup
SHOWGRPS - List the Workgroups a user is in
SHOWACCS - Show access profile (Windows 2000)
GRPTEST - SMS support tools - enumerate group membership for a user account
WHOAMI /all - List all workgroups
SHUTDOWN.exe (for Terminal Services use: TsShutDn)
Shutdown the computer
Syntax
SHUTDOWN [logoff_option] [/m \\Computer] [options]
logoff_options:
/i Display the GUI (must be the first option)
/l Log off. This cannot be used with /m or /d option
/s Shutdown
/r Shutdown and Restart
/a Abort a system shutdown.
(only during the time-out period)
/p Turn off the local computer with no time-out or warning
(only with /d)
/h Hibernate the local computer (only with /f )
/e Document the reason for an unexpected shutdown of a computer
Options:
/m \\Computer : A remote computer to shutdown.
/t:xxx : Time until system shutdown in seconds.
The valid range is xxx=0-600 seconds. [default=30]
/c "Msg" : An optional shutdown message [Max 127 chars]
/f : Force running applications to close.
This will not prompt for File-Save in any open applications.
so will result in a loss of all unsaved data!!!
/d u:xx:yy : List a USER (unplanned) reason code for the shutdown.
/d P:xx:yy : List a PLANNED reason code for the shutdown.
xx Specifies the major reason code (0-255)
yy Specifies the minor reason code (0-65536)
Options in bold are for Windows 2003 and later
When using this command to reboot a server, the shutdown process will normally allow 30 seconds to ensure each running service has time to stop. Services are shutdown in alphabetical order. The shutdown may be done made faster if the services are first halted in a specific order using NET STOP or SC.
Reason codes:
E = Expected
U = Unexpected
P = Planned (C = customer defined)
Type Major Minor Title
U 0 0 Other (Unplanned)
E 0 0 Other (Unplanned)
E P 0 0 Other (Planned)
U 0 5 Other Failure: System Unresponsive
E 1 1 Hardware: Maintenance (Unplanned)
E P 1 1 Hardware: Maintenance (Planned)
E 1 2 Hardware: Installation (Unplanned)
E P 1 2 Hardware: Installation (Planned)
P 2 3 Operating System: Upgrade (Planned)
E 2 4 Operating System: Reconfiguration (Unplanned)
E P 2 4 Operating System: Reconfiguration (Planned)
P 2 16 Operating System: Service pack (Planned)
2 17 Operating System: Hot fix (Unplanned)
P 2 17 Operating System: Hot fix (Planned)
2 18 Operating System: Security fix (Unplanned)
P 2 18 Operating System: Security fix (Planned)
E 4 1 Application: Maintenance (Unplanned)
E P 4 1 Application: Maintenance (Planned)
E P 4 2 Application: Installation (Planned)
E 4 5 Application: Unresponsive
E 4 6 Application: Unstable
U 5 15 System Failure: Stop error
E 5 19 Security issue
U 5 19 Security issue
E P 5 19 Security issue
E 5 20 Loss of network connectivity (Unplanned)
U 6 11 Power Failure: Cord Unplugged
U 6 12 Power Failure: Environment
P 7 0 Legacy API shutdown
Examples
Shutdown the local system immediately:
SHUTDOWN /s
Restart the local system in 60 seconds time and specify the reason "Application: Installation (Planned)" :
SHUTDOWN /r /t:60 /d P:4:2
Restart the remote system server64 and specify the reason "Security Fix, Planned"
SHUTDOWN /r /m \\server64 /d P:2:17
"I shall go the way of the open sea, To the lands I knew before you came,
And the cool ocean breezes shall blow from me, The memory of your name" - Laurence Hope
Related:
LOGOFF - Log off a user.
BootCFG - Edit Boot.ini settings.
PsShutdown - SysInternals command line tool
TsShutDn - Terminal Services Shutdown
EVENTCREATE - Add a message to the Windows event log
PowerOff - Stefan Kuhr utility (NT / 2K)
JSIFAQ Tip 9130 - log off user after n minutes of inactivity
Powershell:
$os = (Get-WmiObject Win32_OperatingSystem -ComputerName MyServer64)
$os.psbase.Scope.Options.EnablePrivileges = $true
$os.reboot()
SLEEP.exe (Resource Kit) Delay execution for a few seconds/minutes (for use within a batch file.)
Syntax
SLEEP time
Key
time The number of seconds to pause
For example:
To pause for an hour before running the next command in a batch file:
SLEEP 3600
Alternative
A delay can also be produced by the PING command with a loopback address, in tests this consumes less processor time than Sleep.exe or Timeout.exe:
e.g. for a delay of 30 seconds:
PING -n 31 127.0.0.1>nul
See Clay Calvert's newsgroup posting for a full explanation of this technique.
“I think men talk to women so they can sleep with them and women sleep with men so they can talk to them” Jay McInerney
Related:
TIMEOUT - Delay execution for a few seconds/minutes (for use within a batch file.)
WAIT - the same as sleep but with noises
WAITFOR - Wait for or send a signal.
WScript.Sleep - Sleep
Powershell: Start-Sleep - Suspend shell, script, or runspace activity (sleep)
Equivalent Linux bash command: sleep - Delay for a specified time
slmgr.vbs (Windows7/2008)
Software Licensing Management Tool. Windows Activation and Key Management Service (KMS)
Syntax
slmgr [MachineName [Username Password]] [Option]
Key
machinename The machine to administer, by default the current local machine.
username An administrator equivalent user account for the remote computer.
password The password for the user account on the remote computer.
/ato Activate Windows license and product key against Microsoft's server.
/atp Confirmation_ID Activate Windows with user-provided Confirmation ID
/ckms Clear the name of KMS server used to default and port to default.
/cpky Clear product key from the registry (prevents disclosure attacks)
/dli Display the current license information with activation
status and partial product key.
/dlv Verbose, similar to -dli but with more information.
/dti Display Installation ID for offline activation
/ipk Key Enter a new product key supplied as xxxxx-xxxxx-xxxxx-xxxxx-xxxxx
/ilc License_file Install license
/rilc Re-install system license files
/rearm Reset the evaluation period/licensing status and activation state of the machine
/skms activationservername:port
Set the Volume Licensing KMS server and/or the port used for KMS activation
(where supported by your Windows edition)
/skhc Enable KMS host caching (default), this blocks the use of DNS priority and
weight after the initial discovery of a working KMS host.
If the system can no longer contact the working KMS host, discovery will be attempted again.
/ckhc Disable KMS host caching. This setting instructs the client to use DNS auto-discovery
each time it attempts KMS activation (recommended when using priority and weight)
/sai interval
Sets the interval in minutes for unactivated clients to attempt KMS connection.
The activation interval must be between 15 minutes and 30 days, although the default (2 hours)
is recommended.
The KMS client initially picks up this interval from the registry but switches to the KMS
setting after the first KMS response has been received.
/sri interval
Sets the renewal interval in minutes for activated clients to attempt KMS connection.
The renewal interval must be between 15 minutes and 30 days.
This option is set initially on both the KMS server and client sides.
The default is 10080 minutes (7 days).
/spri Set the KMS priority to normal (default).
/cpri Set the KMS priority to low.
Use this option to minimize contention from KMS in a co-hosted environment.
Note that this could lead to KMS starvation, depending on what other applications
or server roles are active. Use with care.
/sprt port
Sets the port on which the KMS host listens for client activation requests. The default TCP port is 1688.
/sdns Enable DNS publishing by the KMS host (default).
/cdns Disable DNS publishing by the KMS host.
/upk Uninstall current installed product key and return license status back to trial state.
/xpr Show the expiry date of current license (if not permanently activated)
Token-based activation:
/lil List the installed token-based activation issuance licenses.
/ril ILID ILvID
Remove an installed token-based activation issuance license.
/stao Set the Token-based Activation Only flag, disabling automatic KMS activation.
/ctao Clear the Token-based Activation Only flag (default), enabling automatic KMS activation.
/ltc List valid token-based activation certificates that can activate installed software.
/fta Certificate Thumbprint [PIN]
Force token-based activation using the identified certificate.
The optional personal identification number (PIN) is provided to unlock the private
key without a PIN prompt when using certificates that are protected by hardware
(for example, smart cards).
All actions (other than displaying status) require elevated administrator privileges.
Slmgr.vbs script is not intended to work across platforms i.e. between Vista and Windows 7
Examples
C:\> cscript C:\windows\system32\slmgr.vbs wkstn64 administrator pa55w0rd1 -dli
C:\> cscript slmgr.vbs -skms 192.168.10.1:8090
C:\> cscript slmgr.vbs -skms KMSServer:8090
"One resolution I have made, and try always to keep, is this: To rise above little things" - John Burroughs
Related:
slui - Software Licensing (Windows 7 Activation)
Activation Error Codes - TechNet
WINVER - Display Licence Activation status
Q921471 - Activation fails when you try to activate Windows Vista, Windows 7...
PERMS - Show permissions for a user
SYSTEMINFO - List system configuration
SOON.exe (Resource Kit) Schedule a command to run in the near future (calls the AT command)
Syntax
SOON [\\computername] delay [/interactive] "command"
SOON /i:[on|off]
Key
delay : When the command should run, in SECONDS from now.
default=5
/interactive : Allows any user to see the job as it runs,
this allows testing and monitoring of the
command.
You can specify /interactive as just /i
computername : the UNC name of a remote machine
/i:on : Make /interactive the default behaviour
use SOON /i:off to restore normal behaviour
SOON schedules jobs to run at a time relative to the current time in "seconds from now"
It is otherwise identical to the AT command but saves calculating an exact start time.
As with all AT jobs you should test your SOON scripts by using the /INTERACTIVE option.
In many cases SCHTASKS may be a better option.
"We want the finest wines available to humanity. And we want them here and we want them now" - Bruce Robinson (Withnail and I )
Related:
SCHTASKS - Create or Edit Scheduled Tasks
Q237840 - Setting a delay of less than 60 seconds.
Powershell: To schedule a PS task call Powershell.exe
Equivalent bash command (Linux): crontab - Schedule a command, watch - Execute/display a program periodically
SORT
Sort will accept a redirected or piped file input and TYPE the file, sorted line by line.
Syntax
SORT [options]
Options
/R : Reverse sort order (Z to A, 9 to 0)
/+n : Sort the file ignoring the first 'n' characters in each row.
The default is to sort using all the chars in each row.
/L[OCALE] locale
Override the system default locale with
The "C" locale yields a faster
collating sequence.
The sort is always case insensitive.
/M[EMORY] kilobytes
The amount of RAM to use for the sort.
The best performance is usually achieved by
not specifying a memory size.
SORT will only create a temporary file
when required by limitations in available memory.
/REC[ORD_MAXIMUM] characters
The maximum number of characters in a row or record
(default 4096, maximum 65535)
[drive:][pathname]
The file to be sorted.
If not specified, the standard input is sorted.
Specifying an input file is faster than
redirecting the same file as standard input.
/T[EMPORARY] [drive:][path]
The path of the directory to hold
SORT's working storage, in case the data
does not fit in RAM. The default is %temp%
/O[UTPUT] [drive:][pathname]
The file where the sorted input is to be stored.
If not specified, the data is written to standard output.
Specifying an output file is faster than redirecting
standard output to a file.
Redirecting a file into SORT
SORT < pathname
Piping a command into SORT
command | SORT
Piping the output from SORT into a file
command | SORT > pathname2
SORT < pathname > pathname2
Piping the output from SORT and appending to an existing file
command | SORT >> pathname2
SORT < pathname >> pathname2
Cultivate peace and order before confusion and disorder - Tao Teh Ching
Related:
TYPE - Display the contents of a text file
Redirection - Redirect files, command output and error messages
Powershell: Sort-Object - Sort objects by property value (sort)
Equivalent bash command (Linux): sort - Sort text files
START
Start a specified program or command in a separate window.
Syntax
START "title" [/Dpath] [options] "command" [parameters]
Key:
title : Text for the CMD window title bar (required)
path : Starting directory
command : The command, batch file or executable program to run
parameters : The parameters passed to the command
Options:
/MIN : Minimized
/MAX : Maximized
/WAIT : Start application and wait for it to terminate
/LOW : Use IDLE priority class
/NORMAL : Use NORMAL priority class
/HIGH : Use HIGH priority class
/REALTIME : Use REALTIME priority class
/B : Start application without creating a new window. In this case
^C will be ignored - leaving ^Break as the only way to
interrupt the application
/I : Ignore any changes to the current environment.
Options for 16-bit WINDOWS programs only
/SEPARATE Start in separate memory space (more robust)
/SHARED Start in shared memory space (default)
Notes:
Always include a TITLE this can be a simple string like "My Script" or just a pair of empty quotes ""
According to the Microsoft documentation, the title is optional, but you may have problems if it is omitted.
Document files may be invoked through their file association just by typing the name of the file as a command.
e.g. START "" WORD.DOC would launch the application associated with the .DOC file extension
Examples
START "My Login Script" /Min Login.cmd
START "" /wait MySlowProgram.exe
Printers
A new printer can be installed very quickly (and the driver downloaded) with the command:
START \\print_server\printer_name
Setting a Working Directory
To start an application and specify where files will be saved:
START /Dc:\Documents\ /MAX "Maximised Notes" notepad.exe
Forcing a Sequence of Programs
If you require your users to run a sequence of 32 bit GUI programs to complete a task, create a batch file that uses the start command:
@echo off
start /wait /b First.exe
start /wait /b Second.exe
start /wait /b Third.exe
Create a shortcut to this batch file and place it on the Start menu or desktop. Set it to run minimized.
When the user double-clicks the shortcut, <First.exe> runs.
When <First.exe> terminates, <Second.exe> runs
When <Second.exe> terminates, <Third.exe> runs
An alternative method is to run a .BAT batch file under command.com (16 bit)
If Command Extensions are disabled, the START command will no longer recognise file Associations, and will not automatically evaluate the COMSPEC variable when starting a second CMD session.
Missing file extensions
When executing a command line whose first token does NOT contain an extension, then CMD.EXE uses the value of the PATHEXT environment variable to determine which extensions to look for and in what order. The default value for the PATHEXT variable is:
.COM;.EXE;.BAT;.CMD
Notice the syntax is the same as the PATH variable, with semicolons separating the different elements.
When executing a command, if there is no match on any extension, then Windows will look to see if the name, without any extension, matches a directory name and if it does, the START command will launch Explorer on that path.
"Do not run; scorn running with thy heels" - Shakespeare, The Merchant of Venice
Related:
CALL - Call one batch program from another
CMD - can be used to call a subsequent batch and ALWAYS return even if errors occur.
Powershell: Invoke-Item - Invoke an executable or open a file (ii)
Q162059 - Opening Office documents
Equivalent bash command (Linux) : open - Open a file in its default application.
SU (Resource Kit) Switch User.
Syntax
SU "[cmdline]" [domain] [[Winsta\]Desktop] [options]
Key
cmdline The command to run (default =%comspec%)
domain The domain for the user account ('.' = local m/c)
Winsta\Desktop The profile to load (default = current)
Options
-cb console bypass
-dn do not switch to new desktop
-g GUI option
-l load the .Default user registry hive
-w use current registry hive
-e Inherit parent environment
-b batch logon
-i interactive logon
-s service logon
-n network logon
-v verbose
All LogOn Types require specific User Rights to be granted...
SeNetworkLogonRight, SeServiceLogonRight, SeInteractiveLogonRight, SeBatchLogonRight
The RUNAS command is a lot easier to use!
“He who reigns within himself, and rules passions, desires, and fears, is more than a king” - Milton
Related:
RUNAS - Execute a program under a different user account.
PsExec - Execute process remotely
Powershell: you can run an entire powershell session via RunAs to elevate your permissions.
Equivalent bash command (Linux): su - Run a command with substitute user and group id
SUBINACL.exe (Resource kit)
Download latest version (2004)
Display or modify Access Control Entries (ACEs) for file and folder Permissions, Ownership and Domain.
Access Control Lists apply only to files stored on an NTFS formatted drive, each ACL determines which users (or groups of users) can read or edit the file. When a new file is created it normally inherits ACL's from the folder where it was created.
Syntax
SUBINACL [/noverbose] /object_type object_name [/action=parameter] [/help]
Key
object_type: service e.g. /service Messenger \\ServerName\Messenger
keyreg e.g. /keyreg HKEY_CURRENT_USER\Software
/keyreg \\Srv\HKEY_LOCAL_MACHINE\KeyPath
file e.g. /file *.obj /file c:\test.txt
/file \\ServerName\Share\Path
subdirectories manipulate files in specified directory and all subdirectories
object_name : This will vary according to the object_type - see the examples above
action : setowner=owner
will change the owner of the object e.g. /setowner=MyDomain\Administrators
replace=SamName\OldAccount=DomainName\New_Account
will replace all ACE (Audit and Permissions) in the object
e.g. /replace=MyOldDomain\Finance=NEWDOM\Finance
changedomain=OldDomainName=NewDomainName
will replace all ACEs with a Sid from OldDomainName
with the equivalent Sid found in NewSamServer
e.g. /changedomain=MyOldDomain=NEWDOMAIN
This option requires a trust relationship with the server containing the object.
When running subinacl against a subfolder, its important to include the trailing backslash, (or \*.*) if they are missed out subinacl may interpret the path as a filename and search the entire drive for it, this can be very slow. (This is the opposite behaviour of Robocopy but you didn't expect consistency did you! )
Examples:
subinacl can do everything that cacls and xcacls can do and more besides.
List permissions to log file:
subinacl /noverbose /nostatistic /outputlog=my.log /subdirectories "C:\Program Files\My Folder\*.*" /display
Restore Permissions:
subinacl /nostatistic /playfile my.log
Change owner :
subinacl /file C:\demofile.doc /setowner=MYDOMAIN\BillG
"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
CACLS - Change file permissions
XCACLS - Display or modify Access Control Lists (ACLs) for files and folders
PERMS - Show permissions for a user
FIXACLS - Restore default privs (Resource Kit supplement 2)
SHOWACL - Show file Access Control Lists (Windows 2000)
XCACLS - Display or modify Access Control Lists (ACLs) for files and folders
Q288129 - Grant users the right to manage services
Powershell: Set-Acl - Set permissions
Equivalent bash command (Linux): chmod - Change access permissions
SUBST
Substitute a drive letter for a network or local path.
Syntax
SUBST drive_letter: path
SUBST
SUBST drive_letter: /D
Key
SUBST with no parameters will display current SUBST drives
/D : Delete the drive_letter substitution.
Compared to mapping a drive with NET USE the SUBST command allows mapping to a subfolder of a drive share - for the storage of user profiles this reduces the number of shares you need to create on the server.
Notes
Under NT 4 SUBST'ed drives could be disconnected using the Explorer GUI - this was fixed in Windows 2000.
In Windows 2000 (and above) you may have problems creating, accessing and deleting drive mappings with SUBST.
However under Win 2K/XP the functionality of the NET USE command is improved so you can now do
NET USE g: \\server\share\folder1\folder2
If the network resource is unavailable (ie the server is down) SUBST will continually retry - unlike NET USE which will try to connect once and fail - depending on your application this may be a good or a bad thing - a subst drive that is not available will badly impact performance of most applications.
Notice that when SUBST is used against a local shared folder, it will create a RECYCLER for that drive. The RECYCLER is not removed when the drive substitution is removed, but can be deleted manually.
"A man should never be ashamed to own he has been in the wrong, which is saying in other words, that he is wiser today than he was yesterday" - Alexander Pope (thoughts on various subjects)
Related:
NET USE - Map a drive letter to a network drive
SYSTEMINFO
List system configuration
Syntax
SYSTEMINFO [/S system [/U username [/P [password]]] ]
[/FO format] [/NH]
Key:
/S system Remote system to connect to.
/U [domain\]user User context under which to execute.
/P [password] Password for the given user (will prompt if omitted)
/FO format Output format: TABLE, LIST or CSV
/NH No "Column Header" in the Table/CSV output
The output includes OS configuration, security info, product ID, RAM, disk space, and network cards.
Examples
SYSTEMINFO
SYSTEMINFO |find "Total Physical Memory:"
SYSTEMINFO /S wkstn6324
SYSTEMINFO /S wkstn6325 /FO CSV /NH >>pcaudit.csv
"A good question is like a miniskirt. Long enough to cover the essentials, but short enough to keep everyone interested" - Charles Halsey
Related:
WINMSD - Windows system diagnostics
WMIC - WMI Commands
PsGetSid - Display the SID of a computer or a user
Powershell: Get-WMIobject - Get WMI information
WMIC PRINTER - Set printing options through WMI.
Bruce Sanderson - Setup shared printers (PrintUI.dll)
DX21.com - A long list of rundll32 options
Q189105 - Add Printers with No User Interaction (Win 2000)
Q314486 - Add Printers with No User Interaction (Win XP)
SC.exe (Resource Kit)
Service Control - Create, Start, Stop, Query or Delete any Windows SERVICE. The command options for SC are case sensitive.
Syntax
SC [\\server] [command] [service_name] [Options]
Key
server : The machine where the service is running
service_name : The KeyName of the service, this is often but not always
the same as the DisplayName shown in Control Panel, Services.
You can get the KeyName by running:
SC GetKeyName <DisplayName>
commands:
query [qryOpt] Show status
queryEx [qryOpt] Show extended info - pid, flags
GetDisplayName Show the DisplayName
GetKeyName Show the ServiceKeyName
EnumDepend Show Dependencies
qc Show config - dependencies, full path etc
start START a service.
stop STOP a service
pause PAUSE a service.
continue CONTINUE a service.
create Create a service. (add it to the registry)
config permanently change the service configuration
delete Delete a service (from the registry)
control Send a control to a service
interrogate Send an INTERROGATE control request to a service
Qdescription Query the description of a service
description Change the description of a service
Qfailure Query the actions taken by a service upon failure
failure Change the actions taken by a service upon failure
sdShow Display a service's security descriptor using SDDL
SdSet Sets a service's security descriptor using SDDL
qryOpt:
driver|service|all
Query specific types of service
state= active|inactive|all
Query services in a particular state only
bufsize= bytes
ri= resume_index_number (default=0)
group= groupname
Query services in a particular group
Misc commands that don't require a service name:
SC QueryLock Query the LockStatus for the ServiceManager Database.
this will show if a service request is running
SC Lock Lock the Service Database
SC BOOT Values are {ok | bad} Indicates whether to save
the last restart configuration as the `last-known-good`
restart configuration
Options
The CREATE and CONFIG commands allow additional options to be set
see the build-in help: 'SC create' and 'SC config'
Note the qryOpt options above are case sensitive - they must be entered in lower case, also the position of spaces and = must be exactly as shown.
The SC command duplicates some aspects of the NET command but adds the ability to create a service.
SC query will display if a service is running, giving output like this:
SERVICE_NAME : messenger
TYPE : 20 WIN32_SHARE_PROCESS
STATE : 4 RUNNING
(STOPPABLE,NOT_PAUSABLE,ACCEPTS_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
To retrieve specific information from SC's output, pipe into FIND or FindStr
e.g.
C:\> SC query messenger | FIND "STATE" | FIND "STOPPED"
C:\> SC query messenger | FIND "STATE" | FIND "RUNNING"
The statements above will return an %ERRORLEVEL% = 1 if the text is not found
IF errorlevel 1 GOTO :my_subroutine
The NET START command can be used in a similar way to check if a service is running:
NET START | FIND "Service name" > nul
IF errorlevel 1 ECHO The service is not running
The service control manager will normally wait up to 30 seconds to allow a service to start - you can modify this time (30,000 milliseconds) in the registry
HKLM\SYSTEM\CurrentControlSet\Control
ServicesPipeTimeout (REG_DWORD)
Some options only take effect at the point when the service is started e.g. the SC config command allows the executable of a service to be changed. When the service next starts up it will run the new executable. Config changes requires the current user to have “permission to configure the service”.
Examples:
SC GetKeyName "task scheduler"
SC GetDisplayName schedule
SC start schedule
SC QUERY schedule
SC QUERY driver
SC QUERY state= all |findstr "DISPLAY_NAME STATE" >svc_installed.txt
SC \\myServer CONFIG myService obj= LocalSystem password= mypassword
SC CONFIG MyService binPath=c:\myprogram.exe obj=".\LocalSystem" password=""
Watch out for extra spaces:
SC QUERY state= all Works
SC QUERY sTate =all Fails!
"There is always room at the top" - Daniel Webster
Related:
DELSRV - Delete a service
INSTSRV - Install a service (run under a specific account)
NET - manage network resources
NETSVC - Command-line Service Controller (Win 2K ResKit)
PsService - View and control services
SCLIST - Display Services
Svcmon - Monitor services and raise an alert if they stop. (Win 2K ResKit)
Svcacls - Service ACL Editor (Win 2K ResKit)
SUBINACL - Set service permissions
WMIC SERVICE - WMI access to services
List of Windows Services
Q251192 - Create a Windows Service using SC
Q166819 - Control Services Remotely
Q170738 - Debug a Windows Service
Powershell: Get-Service - Get a list of services
Equivalent bash command (Linux): nice - Change job scheduling priority
SCHTASKS Create, delete, edit, list, start or stop a scheduled task.
Works on local or remote computers.
Syntax:
SCHTASKS /Create [Connect_Options] Create_Options /TN taskname
SCHTASKS /Delete [Connect_Options] /TN taskname [/F]
SCHTASKS /Query [Connect_Options] [/FO format] [/NH] [/V]
SCHTASKS /Run [Connect_Options] /TN taskname
SCHTASKS /End [Connect_Options] /TN taskname
SCHTASKS /Change [Connect_Options] {[/RU username] [/RP password] [/TR taskrun]} /TN taskname
Connect_Options:
/S system # Remote system (default is local)
[/U username [/P password]] # Submit job under this name
Create_Options:
/TR taskrun # Pathname of the executable to run
/ST starttime # HH:MM:SS (24 hour)
[/RU username [/RP password]] # Run job as this user
/SC schedule [/MO modifier] # When to run, see below
[/D day] # Day = MON,TUE,WED,THU,FRI,SAT,SUN
[/M months] # Month=JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC.
[/I idletime] # 1 - 999 minutes (ONIDLE task only)
[/SD startdate] [/ED enddate] # Start and end date "dd/mm/yyyy"
options:
/TN A name for the task
/F Force delete, ignore warnings even if the task is currently runnning.
/FO Output format: TABLE, LIST, CSV
/NH No header
/V Verbose output
Notes:
For MONTHLY schedules give the DAY as a number 1 - 31 (default=1)
To prompt for the password, specify /RP * or /RP none
The User Account under which the Schedule service runs may require specific file access permissions, user permissions and drive mappings.
If the /RU username and /RP Password parameters match the currently logged-in user, the task will run interactively (visible in the foreground).
For the system account, /RU username can be written as "", "NT AUTHORITY\SYSTEM" or "SYSTEM", a Password is not required. Thesystem account has full access to the local machine but has no permissions on any other machines (or mapped drives) across the Network.
/SC schedule The schedule frequency.
Valid schedules: MINUTE,HOURLY,DAILY,WEEKLY,MONTHLY, ONCE,ONSTART,ONLOGON,ONIDLE.
/MO modifiers allow finer control:
MINUTE: 1 - 1439 minutes.
HOURLY: 1 - 23 hours.
DAILY: 1 - 365 days.
WEEKLY: 1 - 52 weeks.
ONCE: No modifiers.
ONSTART: No modifiers.
ONLOGON: No modifiers.
ONIDLE: No modifiers.
MONTHLY: 1 - 12, or FIRST, SECOND, THIRD, FOURTH, LAST, LASTDAY.
Power Saving
The property for "Wake up the machine to run this task" cannot be set using schtasks, but this property is essential if you need the task to run on a machine that has PowerSaving enabled.
To work around this, create a task on one computer using the control panel GUI. This will create a .job file in C:\%windir%\Tasks\
To replicate the scheduled task onto other machines copy the .JOB file to C:\%windir%\Tasks on each machine.
This techique will not retain any system account credentials, so if you need to run the tasks under System, run the following after copying the .JOB file:
SCHTASKS /CHANGE /RU "NT Authority\System" /TN "Yourtaskname"
Examples:
Create a task to run at 11 pm every weekday
SCHTASKS /Create /SC weekly /D MON,TUE,WED,THU,FRI /TN MyDailyBackup /ST 23:00:00 /TR c:\backup.cmd /RU MyDomain\MyLogin /RP MyPassword
Now delete the task:
SCHTASKS /Delete /TN "MyDailyBackup" /f
Create a daily task to run a script at 5 pm:
SCHTASKS /create /tn "My Script" /tr "\"c:\my folder\script.cmd\" arguments" /sc daily /sd 12/29/2008 /st 17:00
Task Scheduler options are stored in the registry
HKLM\SOFTWARE\Microsoft\SchedulingAgent\
"We don't wake up for less than $10,000 a day" - Linda Evangelista
Related:
Q823093 - Scheduled task does not run when the Path contains a space
WAITFOR - Wait for or send a signal.
Powershell: To schedule a PS task call Powershell.exe
Equivalent bash command (linux): crontab - Schedule a command to run at a later time
SCLIST (Resource Kit) List Services
Syntax
SCLIST [options] [ComputerName]
Key
-r : Display only running services
-s : Display only stopped services
ComputerName : The computer running the services
(default = %ComputerName% )
Related:
NET - Manage network resources
SC - Service Control
NETSVC - Command-line Service Controller (Win 2K ResKit)
Powershell: Get-Service - Get a list of services
Equivalent bash command (Linux): ps - process status
SET
Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.
Syntax
SET variable
SET variable=string
SET /A variable=expression
SET "variable="
SET /P variable=[promptString]
SET "
Key
variable : A new or existing environment variable name
string : A text string to assign to the variable.
expression: : Arithmetic Sum
Also see SetX, VarSearch and VarSubstring for more advanced variable manipulation.
Variable names are not case sensitive but the contents can be. Variables can contain spaces.
The number one problem people run into with SET is having extra spaces around either the variable name or the string, SET is not forgiving of extra spaces like many other scripting languages.
The CMD shell will fail to read an environment variable if it contains more than 8,191 characters.
To display current variables:
Type SET without parameters to display all the current environment variables.
Type SET with a variable name to display that variable SET _department
or use ECHO: ECHO [%_department%]
The SET command invoked with a string (and no equal sign) will display a wildcard list of all matching variables
Display variables that begin with 'P': SET p
Display variables that begin with an underscore SET _
Examples
Storing a text string:
C:\> SET _dept=Sales and Marketing
C:\> set _
_dept=Sales and Marketing
One variable can be based on another, but this is not dynamic
E.g.
C:\> set xx=fish
C:\> set msg=%xx% chips
C:\> set msg
msg=fish chips
C:\> set xx=sausage
C:\> set msg
msg=fish chips
C:\> set msg=%xx% chips
C:\> set msg
msg=sausage chips
Avoid starting variable names with a number, this will avoid the variable being mis-interpreted as a parameter
%123_myvar% < > %1 23_myvar
To display undocumented system variables:
SET "
Prompt for user input
@echo off
Set /P _dept=Please enter Department:
If "%_dept%"=="" goto :sub_error
If /i "%_dept%"=="finance" goto sub_finance
If /i "%_dept%"=="hr" goto sub_hr
goto:eof
:sub_finance
echo You chose the finance dept
goto:eof
:sub_hr
echo You chose the hr dept
The /P switch allows you to set a variable equal to a line of input entered by the user.
The PromptString is displayed before the user input is read. The PromptString can be empty.
The CHOICE command is an alternative to SET /P
To place the first line of a file into a variable:
Set /P _MyVar=<MyFilename.txt
CALL SET
SET can be CALLed allowing a variable substring to be evaluated:
SET
SET length=9
SET string=The quick brown fox jumps over the lazy dog
CALL SET substring=%%string:~%start%,%length%%%
ECHO (%substring%)
Deleting an environment variable
Type SET with just the variable name and an equals sign:
SET _department=
Better still, to be sure there is no trailing space after the = use:
(SET _department=)
or
SET "_department="
Variable names can include Spaces
A variable can contain spaces and also the variable name itself may contain spaces, therefore the following assignment:
SET my var=MyText
will create a variable called "my var"
Similarly
SET _var =MyText
will create a variable called "_var " - note trailing space
To avoid problems with extra spaces appearing in your output, issue SET statements in parentheses, like this
(SET _department=Some Text)
Alternatively you can do
SET "_department=Some Text"
Note: if you wanted to actually include a bracket in the variable you need to use an escape character.
The SET command will set ERRORLEVEL to 1 if the variable name is not found in the current environment.
This can be detected using the IF ERRORLEVEL command
Arithmetic expressions (SET /a)
The expression to be evaluated can include the following operators:
Multiply *
Divide /
Add +
Subtract -
Modulus %
AND &
OR |
XOR ^
LSH <<
RSH >>
Multiply Variable *=
Divide Variable /=
Add Variable +=
Subtract Variable -=
AND Variable &=
OR Variable |=
XOR Variable ^=
LSH Variable <<=
RSH Variable >>=
SET /a calculations
Enclose any logical expressions in "quotes"
Several calculations can be put on one line if separated with commas.
Warning: any SET /A calculation that returns a fractional result will be rounded down to the nearest whole integer.
Examples:
SET /A _result=2+4
(=6)
SET /A _result=5
(=5)
SET /A _result+=5
(=10)
SET /A _result="2<<3"
(=16) { 2 Lsh 3 = binary 10 Lsh 3 = binary 10000 = decimal 16 }
SET /A _result="5%%2"
(=1) { 5/2 = 2 + 2 remainder 1 = 1 }
Modulus operator - note that in a batch script, (as opposed to on the command-line), you need to double up the % to %%
SET /A will treat any character string in the expression as an environment variable name. This allows you to do arithmetic with environment variable values without having to type any % signs to get the values. SET /A _result=5 + _MyVar
Leading Zero will specify Octal
Numeric values are decimal numbers, unless prefixed by
0x for hexadecimal numbers,
0 for octal numbers.
So 0x12 = 022 = 18 decimal
The octal notation can be confusing - all numeric values that start with zeros are treated as octal but 08 and 09 are not valid numbers because 8 and 9 are not valid octal digits.
This is often a cause of error when performing date arithmetic. For example SET /a _day=07 will return the value=7, but SET /a _day=09 will return an error.
Permanent Changes
Changes made using the SET command are NOT permanent, they apply to the current CMD prompt only and remain only until the CMD window is closed.
To permanently change a variable at the command line use SetX
or in the GUI - Control Panel, System, Environment, System/User Variables
Changing a variable permanently with SetX will not affect any CMD prompt that is already open.
Only new CMD prompts will get the new setting.
You can of course use SetX in conjunction with SET to change both at the same time, but neither SET or SetX will affect other CMD sessions that are already running. When you think about it - this is a good thing.
It is also possible (although undocumented) to add permanent env variables to the registry [HKEY_CURRENT_USER\Environment]
(using REGEDIT)
System Environment variables can also be found in [HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
Autoexec.bat
Any SET statement in c:\autoexec.bat may be parsed at boot time
Variables set in this way are not available to 32 bit gui programs - they won't appear in the control panel.
They will appear at the CMD prompt.
If autoexec.bat CALLS any secondary batch files, the additional batch files will NOT be parsed at boot.
This behaviour can be useful on a dual boot PC.
If Command Extensions are disabled all SET commands are disabled other than simple assignments like:
_variable=MyText
# I got my mind set on you
# I got my mind set on you... - George Harrison
Related:
CALL - Evaluate environment variables
SETX - Set an environment variable permanently.
SETLOCAL - Begin localisation of environment variable changes
ENDLOCAL - End localisation of environment changes, use to return values
EXIT - Set a specific ERRORLEVEL
Parameters - get a full or partial pathname from a command line variable.
PATH - Change the %PATH% environment variable.
PATHMAN - This Resource Kit utility allows quick modification of both the system and user paths. Pathman can resolve many problems such as duplicate characters, and can improve performance by removing duplicate paths. For details see Pathman.wri in the resource kit.
REGEDIT - Import or export registry settings
WMIC ENVIRONMENT - Set environment vars through WMI
NIST Digital Library of Mathematical Functions
Powershell: Set-Variable - Set a variable and a value (set/sv)
Powershell: Read-Host - Prompt for user input
Equivalent bash command (Linux): env - Display, set, or remove environment variables
SETLOCAL Set options to control the visibility of environment variables in a batch file.
Syntax
SETLOCAL
SETLOCAL EnableDelayedExpansion
SETLOCAL EnableExtensions | DisableExtensions
Key
EnableDelayedExpansion Expand variables at execution time rather than at parse time.
EnableExtensions Attempt to enable Command extensions.
DisableExtensions Attempt to disable Command extensions.
SETLOCAL on it's own, usually at the start of a batch file, will begin localisation of Environment Variables.
Issuing a SETLOCAL command, the batch script will inherit all current variables from the master environment/session.
Issuing an ENDLOCAL command will restore any environment variables present before the SETLOCAL was issued.
If a batch script does not use SETLOCAL and ENDLOCAL then all variables will be Global, i.e. visible and modifiable by other scripts.
Although global variables are easy to work with they are not good practice - for example if you have several batch scripts dealing with filenames (and these scripts may be CALLing one another), the first script may have a variable called _filename, the second script a different variable called file-name (a different name to avoid conflicting with the first script) a third script now needs something like file_name this quickly becomes very difficult to manage.
With local variables you are free to use the same variable names in multiple batch scripts - there is no conflict because the local variables are not visible to any other script.
Local Variables can be passed from one batch routine to another with the ENDLOCAL command.
EnableDelayedExpansion
Setting EnabledDelayedExpansion will cause each variable to be expanded at execution time rather than at parse time.
EnableDelayedExpansion is Disabled by default.
Overloading a variable
SETLOCAL can be used more than once in the same batch file so that multiple values can be stored in the same Environment Variable. To keep track of variable definitions, SETLOCAL and ENDLOCAL statements should be paired.
@echo off
SETLOCAL
::Standard commission
SET _Commission=20
echo %_Commission%
::Premium commission
SETLOCAL
set _Commission=30
echo %_Commission%
::back to Standard commission
ENDLOCAL
echo %_Commission%
DISABLEEXTENSIONS
Command Extensions are enabled by default, there is rarely any need to disable them.
If Command Extensions are permanently disabled or if a script is running under the Windows 95 command processor command.com then SETLOCAL ENABLEEXTENSIONS will not be able to restore them.
A batch file to warn if command extensions are not available:
VERIFY errors 2>nul
SETLOCAL ENABLEEXTENSIONS
IF ERRORLEVEL 1 echo Unable to enable extensions
Errors
SETLOCAL will set an ERRORLEVEL if given an argument: It will be zero if one of the two valid arguments is given and one otherwise.
"A local shop for local people" - The League Of Gentlemen
Related:
ENDLOCAL - End localisation of environment changes in a batch file.
Syntax: Functions - How to package blocks of code
Powershell: Set-PSdebug -strict - Equivalent to 'Option Explicit' in VB
Equivalent bash command (Linux): readonly - Mark variables/functions as readonly
SETX.exe (Resource Kit, Windows 7)
Set environment variables permanently
SETX can be used to set Environment Variables for the machine or currently logged on user:
SETX Variable Value
SETX Variable Value -m
Key:
-m Set the value in the Machine environment (HKLM)
Default is User (HKCU)
SetX can also be used in modes to edit the Registry or edit CR-LF text files, (like win.ini) for most purposes these tasks are better done with other tools in the resource kit, e.g. the REG command.
Because SetX writes variables to the master environment in the registry. Edits will only take effect when a new command window is opened - they do not affect the current command session.
Deleting variables
A value of "" (empty quotes) will appear to delete the variable - it's not shown by SET but the variable name will remain in the registry. Either use the GUI (recommended) or delete the value from the registry with REG
REG delete HKCU\Environment /V _myvar
Deleting a variable with REG does not take effect until next logon due to caching of registry data. The type is REG_EXPAND_SZ.
Examples:
Set the variable _mypc to be COMPAQ in the users permanent environment:
SetX _mypc COMPAQ
Delete the variable _mypc in the users permanent environment:
REG delete HKCU\Environment /V _mypc
Set the variable _myTimeZone in both the immediate user session and the permanent environment:
SET _myTimeZone=GMT
SetX _myTimeZone GMT
Store the value of %my_important_var% in a second environment variable.
SetX _mybackupvar %my_important_var%
Sets the value of _mypath to be equal to the value of the %PATH% environment variable, _mypath will then remain the same even if the PATH variable changes in the future:
SetX _mypath ~PATH~
Machine variables
These are stored on the machine and won't follow a users roaming profile.
To set a machine variable (-m) requires Administrator rights.
Create a machine variable:
SetX _myvar COMPAQ -m
Delete a machine variable:
REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /V _myvar
"You are never dedicated to something you have complete confidence in. No-one is fanatically shouting that the sun is going to rise tomorrow. When people are fanatically devoted to political or religious faiths or any other kind of dogmas or goals, its always because these dogmas or goals are in doubt" - Robert M Pirsig
Related:
SET - Display, set, or remove environment variables
REG - Delete keys or values from the registry
Q104011 - Modify variables by editing the Registry
SETENV - Vincent Fatica's improved version
Powershell: Set-Variable - Set a variable and a value (set/sv)
Equivalent bash command (Linux): env - Display, set, or remove environment variables
SFC (Windows XP, Server 2003, Win 7) System File Checker
Syntax
Sfc [/Scannow] [/Scanonce] [/Scanboot] [/Revert] [/Purgecache] [/Cachesize=x]
Key
/Scannow Scan all protected system files immediately and replace
incorrect versions with correct Microsoft versions.
May require access to the Windows installation source files.
/Scanonce Scan all protected system files one time when you restart your computer.
May require access to the Windows installation source
files when you restart the computer.
The SfcScan DWORD value is set to 2 in the following registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
/Scanboot Scan all protected system files every time you start your computer.
May require access to the Windows installation source files every
time you start the computer.
The SfcScan DWORD value is set to 1 in the following registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
/Revert Return scan to the default setting
(do not scan protected files when you start the computer).
The default cache size is not reset when you run this command.
/Purgecache Purge the file cache and scan all protected system files immediately.
May require access to the Windows installation source files.
/Cachesize=x Set the file cache size to x megabytes (MB).
The default size of the cache is 50 MB.
This command requires you to restart the computer, and then run
the /purgecache command to adjust the size of the on-disk cache.
This command sets the SfcQuota DWORD value to x in the following registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
Under Windows 7, SFC must be run from an elevated command prompt.
“Oh, yes, I've learned from my mistakes and I'm sure I could repeat them exactly” - Sir Arthur Streeb-Greebling (aka Peter Cook)
Related:
SLMGR - Software Licensing Management
WINMSD - Windows system diagnostics
Share.vbs (Resource Kit) List or edit a file share or print share (on any computer)
Although missing from recent Resource Kits, this VBS script does still work under recent versions of Windows. The preferred method for creating shares is the RMTShare command, which can also grant permissions.
Syntax:
List Shares
Share.vbs /L [/S <server>] [/U <username>] [/W <password>] [/O <outputfile>]
Create a Share
Share.vbs /C /N <name> /P <path> [/T <type>] [/V <description>]
[/S <server>] [/U <username>] [/W <password>] [/O <outputfile>]
Delete a Share
Share.vbs /D /N <name>
[/S <server>] [/U <username>] [/W <password>] [/O <outputfile>]
Key:
/L List
/C Create
/D Delete
/N name Name of the share to be created or deleted.
/P path Path of the share to be created.
/v description A description for the share.
/T type Type of the share to be created. (Disk, Printer, IPC or Special)
/S server A machine name.
/U username The current user's name.
/W password Password of the current user.
/O outputfile Output file name.
Examples:
List the shares on the machine \\Frodo
cscript Share.vbs /L /s Frodo
Create a file share called "scratch" on the local machine:
cscript Share.vbs /c /n scratch /p "c:\my shared files" /t Disk /v "project files"
Delete the share named "scratch" on the machine \\Frodo
cscript Share.vbs /d /n scratch /s Frodo
"The inherent vice of capitalism is the unequal sharing of blessings,
the inherent vice of Socialism is the equal sharing of miseries." - Winston Churchill
Related:
CACLS - Display or modify Access Control Lists (ACLs) for files and folders
RMTShare - The preferred method for creating a file system share (it can also grant permissions)
RUNDLL32 - Run a DLL command (add/remove print connections)
Powershell: Get-WmiObject win32_share
Equivalent bash command (Linux): mount - Mount a file system
SHIFT
Change the position of command line parameters in a batch file.
Syntax
SHIFT [/n]
Key
/n Start at the nth argument, where n may be between zero and eight.
Relative pathnames
Examples:
Given %1=the, %2=quick, %3=brown
SHIFT
will result in %1=quick, %2=brown
A second
SHIFT
will result in %1=brown
Given %1=the, %2=quick, %3=brown, %4=fox
SHIFT /2
will result in %1=the, %2=brown, %3=fox
Parse Command Line Arguments
:start
if "%1"=="" (goto :main)
:: Do whatever with token %1
Echo [%1]
:: Shift %2 into %1
SHIFT
goto :start
:main
::
The parameter %0 will initially refer to the path that was used to execute the batch - this could be MyBatch.cmd if in the current directory or a full path like C:\apps\myBatch.cmd
If SHIFT is used to move a text parameter into %0 then any references to %0 will refer instead to the current working directory, unless the new parameter value happens to contain a valid path.
For example:
%0\..\MyExecutable.exe
will run the MyExecutable from the same directory as the Batch file.
If the following parameter is passed to myBatch.cmd
myBatch.cmd D:\utils\
Then the following commands in myBatch will run MyExecutable.exe from the directory D:\utils\
SHIFT
%0\..\MyExecutable.exe
If Command Extensions are disabled, the SHIFT command will not support the /n switch
"If NumLock is on, pressing a key on the numeric keypad while holding SHIFT overrides NumLock and instead generates an arrow key" -OldNewThing
Related:
CALL - Call one batch program from another
SET - Display or edit environment variables
powershell: param( $var1, $var2,... )
Equivalent bash command (Linux): shift - Shift positional parameters
SHORTCUT.exe (NT Server Resource Kit)
Create a windows shortcut (.LNK file)
Syntax
SHORTCUT [options]
Key
Source options
-t target : The path and file name of the application/document to open.
-a arguments : The arguments passed when the shortcut is used.
-d directory : The folder to start the application in.
-i iconfile : The file the icon is in.
-x index : The index into the icon file.
options for the shortcut file to be created
-n name : The path and file name (.LNK) of the shortcut file.
-c : Change existing shortcut.
-r : Resolve broken shortcut.
-f : Force overwrite of an existing short cut.
-s : Make shortcut simple (don't use LinkResolve)
Export options
-u [spec] : ECHO the contents of an existing shortcut.
'all' is the same as 'natdix' but the letters
of 'natdix' specify the options to be exported
(the same option can be specified more than once
e.g. -u natn)
-l logfile : Save any error messages in the specified file
If shortcut.exe fails to create a new shortcut, it does NOT set an errorlevel.
Example
@ECHO off
MD %userprofile%"\start menu\programs\MY APP"
SHORTCUT -f -t C:\MyApp.exe -n %userprofile%"\start menu\programs\MY APP\MY APP"
For Windows XP and more recent systems, you are better off using a little .vbs script, as WSH is built-in from XP onwards, call the script like so:
CSCRIPT C:\myshortcut.vbs
Optional sections in the VBscript below are commented out:
Set oWS = WScript.CreateObject("WScript.Shell")
sLinkFile = "C:\MyShortcut.LNK"
Set oLink = oWS.CreateShortcut(sLinkFile)
oLink.TargetPath = "C:\Program Files\MyApp\MyProgram.EXE"
' oLink.Arguments = ""
' oLink.Description = "MyProgram"
' oLink.HotKey = "ALT+CTRL+F"
' oLink.IconLocation = "C:\Program Files\MyApp\MyProgram.EXE, 2"
' oLink.WindowStyle = "1"
' oLink.WorkingDirectory = "C:\Program Files\MyApp"
oLink.Save
Shortcut: NTFS file system tracking
If a shortcut to a file breaks because the destination file has moved, then by default Windows will attempt to automatically locate the shortcut destination by performing a search (this only applies to NTFS partitions). To turn this off - add a DWORD value of 1 to the registry:
HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
NoResolveTrack=1
Shortcut: Auto LinkResolve
By default shortcuts will include the destination machine, even for a target like C:\MyFile.doc
This is not immediately visible until the shortcut.LNK file is copied to another machine, the shortcut target will then be automatically updated to point back to \\Machine1\c$\MyFile.doc
To turn this behaviour off use shortcut.exe -s or add a DWORD value of 1 to the registry (before creating the shortcut):
HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
"LinkResolveIgnoreLinkInfo"=1
Favourites
Often confused with shortcuts, Internet Explorer Favourite (.URL) files are simple text files which you can create with a few ECHO statements.
"The reasonable man adapts himself to the world: the unreasonable one persists in trying to adapt the world to himself. Therefore all progress depends on the unreasonable man" - George Bernard Shaw
Related:
MD - Create folder(s)
Slow Network browsing (XP)
FSUTIL - Create a Hardlink
Q158682 - Shortcuts created resolve to UNC Path (Link Tracking)
Q150215 - Disable Automatic Shortcut Resolution
Q254493 - Shortcut.exe fails with sub-folder names.
Q263324 - Shortcut.exe truncates path names.
Equivalent bash command (Linux): symlink - Make a new name for a file, ln - Make links between files
SHOWGRPS (Resource Kit) List the Workgroups a user has joined.
Syntax
SHOWGRPS domain\username
SHOWGRPS username
If no username is specified SHOWGRPS will list the workgroups for the currently logged in user.
Example
SHOWGRPS ss64domain\user05
"Justice is such a fine thing that we cannot pay too dearly for it" - Alain-Rene Lesage
Related:
NET - add or remove a user from a workgroup
FINDGRP - List the (global or local) security groups a user has joined (NT 4 Reskit)
SHOWMBRS - List the members of an NT Workgroup
GRPTEST - SMS support tools - enumerate group membership for a user account.
SHOWACCS - Show access profile (Windows 2000)
SHOWMBRS (Resource Kit) List all the users who are members of a Workgroup.
Syntax
SHOWMBRS domain\Workgroup
SHOWMBRS Workgroup
A workgroup must be specified.
Example:
SHOWMBRS wg_finance
Related:
NET GROUP - add or remove a user from a workgroup
SHOWGRPS - List the Workgroups a user is in
SHOWACCS - Show access profile (Windows 2000)
GRPTEST - SMS support tools - enumerate group membership for a user account
WHOAMI /all - List all workgroups
SHUTDOWN.exe (for Terminal Services use: TsShutDn)
Shutdown the computer
Syntax
SHUTDOWN [logoff_option] [/m \\Computer] [options]
logoff_options:
/i Display the GUI (must be the first option)
/l Log off. This cannot be used with /m or /d option
/s Shutdown
/r Shutdown and Restart
/a Abort a system shutdown.
(only during the time-out period)
/p Turn off the local computer with no time-out or warning
(only with /d)
/h Hibernate the local computer (only with /f )
/e Document the reason for an unexpected shutdown of a computer
Options:
/m \\Computer : A remote computer to shutdown.
/t:xxx : Time until system shutdown in seconds.
The valid range is xxx=0-600 seconds. [default=30]
/c "Msg" : An optional shutdown message [Max 127 chars]
/f : Force running applications to close.
This will not prompt for File-Save in any open applications.
so will result in a loss of all unsaved data!!!
/d u:xx:yy : List a USER (unplanned) reason code for the shutdown.
/d P:xx:yy : List a PLANNED reason code for the shutdown.
xx Specifies the major reason code (0-255)
yy Specifies the minor reason code (0-65536)
Options in bold are for Windows 2003 and later
When using this command to reboot a server, the shutdown process will normally allow 30 seconds to ensure each running service has time to stop. Services are shutdown in alphabetical order. The shutdown may be done made faster if the services are first halted in a specific order using NET STOP or SC.
Reason codes:
E = Expected
U = Unexpected
P = Planned (C = customer defined)
Type Major Minor Title
U 0 0 Other (Unplanned)
E 0 0 Other (Unplanned)
E P 0 0 Other (Planned)
U 0 5 Other Failure: System Unresponsive
E 1 1 Hardware: Maintenance (Unplanned)
E P 1 1 Hardware: Maintenance (Planned)
E 1 2 Hardware: Installation (Unplanned)
E P 1 2 Hardware: Installation (Planned)
P 2 3 Operating System: Upgrade (Planned)
E 2 4 Operating System: Reconfiguration (Unplanned)
E P 2 4 Operating System: Reconfiguration (Planned)
P 2 16 Operating System: Service pack (Planned)
2 17 Operating System: Hot fix (Unplanned)
P 2 17 Operating System: Hot fix (Planned)
2 18 Operating System: Security fix (Unplanned)
P 2 18 Operating System: Security fix (Planned)
E 4 1 Application: Maintenance (Unplanned)
E P 4 1 Application: Maintenance (Planned)
E P 4 2 Application: Installation (Planned)
E 4 5 Application: Unresponsive
E 4 6 Application: Unstable
U 5 15 System Failure: Stop error
E 5 19 Security issue
U 5 19 Security issue
E P 5 19 Security issue
E 5 20 Loss of network connectivity (Unplanned)
U 6 11 Power Failure: Cord Unplugged
U 6 12 Power Failure: Environment
P 7 0 Legacy API shutdown
Examples
Shutdown the local system immediately:
SHUTDOWN /s
Restart the local system in 60 seconds time and specify the reason "Application: Installation (Planned)" :
SHUTDOWN /r /t:60 /d P:4:2
Restart the remote system server64 and specify the reason "Security Fix, Planned"
SHUTDOWN /r /m \\server64 /d P:2:17
"I shall go the way of the open sea, To the lands I knew before you came,
And the cool ocean breezes shall blow from me, The memory of your name" - Laurence Hope
Related:
LOGOFF - Log off a user.
BootCFG - Edit Boot.ini settings.
PsShutdown - SysInternals command line tool
TsShutDn - Terminal Services Shutdown
EVENTCREATE - Add a message to the Windows event log
PowerOff - Stefan Kuhr utility (NT / 2K)
JSIFAQ Tip 9130 - log off user after n minutes of inactivity
Powershell:
$os = (Get-WmiObject Win32_OperatingSystem -ComputerName MyServer64)
$os.psbase.Scope.Options.EnablePrivileges = $true
$os.reboot()
SLEEP.exe (Resource Kit) Delay execution for a few seconds/minutes (for use within a batch file.)
Syntax
SLEEP time
Key
time The number of seconds to pause
For example:
To pause for an hour before running the next command in a batch file:
SLEEP 3600
Alternative
A delay can also be produced by the PING command with a loopback address, in tests this consumes less processor time than Sleep.exe or Timeout.exe:
e.g. for a delay of 30 seconds:
PING -n 31 127.0.0.1>nul
See Clay Calvert's newsgroup posting for a full explanation of this technique.
“I think men talk to women so they can sleep with them and women sleep with men so they can talk to them” Jay McInerney
Related:
TIMEOUT - Delay execution for a few seconds/minutes (for use within a batch file.)
WAIT - the same as sleep but with noises
WAITFOR - Wait for or send a signal.
WScript.Sleep - Sleep
Powershell: Start-Sleep - Suspend shell, script, or runspace activity (sleep)
Equivalent Linux bash command: sleep - Delay for a specified time
slmgr.vbs (Windows7/2008)
Software Licensing Management Tool. Windows Activation and Key Management Service (KMS)
Syntax
slmgr [MachineName [Username Password]] [Option]
Key
machinename The machine to administer, by default the current local machine.
username An administrator equivalent user account for the remote computer.
password The password for the user account on the remote computer.
/ato Activate Windows license and product key against Microsoft's server.
/atp Confirmation_ID Activate Windows with user-provided Confirmation ID
/ckms Clear the name of KMS server used to default and port to default.
/cpky Clear product key from the registry (prevents disclosure attacks)
/dli Display the current license information with activation
status and partial product key.
/dlv Verbose, similar to -dli but with more information.
/dti Display Installation ID for offline activation
/ipk Key Enter a new product key supplied as xxxxx-xxxxx-xxxxx-xxxxx-xxxxx
/ilc License_file Install license
/rilc Re-install system license files
/rearm Reset the evaluation period/licensing status and activation state of the machine
/skms activationservername:port
Set the Volume Licensing KMS server and/or the port used for KMS activation
(where supported by your Windows edition)
/skhc Enable KMS host caching (default), this blocks the use of DNS priority and
weight after the initial discovery of a working KMS host.
If the system can no longer contact the working KMS host, discovery will be attempted again.
/ckhc Disable KMS host caching. This setting instructs the client to use DNS auto-discovery
each time it attempts KMS activation (recommended when using priority and weight)
/sai interval
Sets the interval in minutes for unactivated clients to attempt KMS connection.
The activation interval must be between 15 minutes and 30 days, although the default (2 hours)
is recommended.
The KMS client initially picks up this interval from the registry but switches to the KMS
setting after the first KMS response has been received.
/sri interval
Sets the renewal interval in minutes for activated clients to attempt KMS connection.
The renewal interval must be between 15 minutes and 30 days.
This option is set initially on both the KMS server and client sides.
The default is 10080 minutes (7 days).
/spri Set the KMS priority to normal (default).
/cpri Set the KMS priority to low.
Use this option to minimize contention from KMS in a co-hosted environment.
Note that this could lead to KMS starvation, depending on what other applications
or server roles are active. Use with care.
/sprt port
Sets the port on which the KMS host listens for client activation requests. The default TCP port is 1688.
/sdns Enable DNS publishing by the KMS host (default).
/cdns Disable DNS publishing by the KMS host.
/upk Uninstall current installed product key and return license status back to trial state.
/xpr Show the expiry date of current license (if not permanently activated)
Token-based activation:
/lil List the installed token-based activation issuance licenses.
/ril ILID ILvID
Remove an installed token-based activation issuance license.
/stao Set the Token-based Activation Only flag, disabling automatic KMS activation.
/ctao Clear the Token-based Activation Only flag (default), enabling automatic KMS activation.
/ltc List valid token-based activation certificates that can activate installed software.
/fta Certificate Thumbprint [PIN]
Force token-based activation using the identified certificate.
The optional personal identification number (PIN) is provided to unlock the private
key without a PIN prompt when using certificates that are protected by hardware
(for example, smart cards).
All actions (other than displaying status) require elevated administrator privileges.
Slmgr.vbs script is not intended to work across platforms i.e. between Vista and Windows 7
Examples
C:\> cscript C:\windows\system32\slmgr.vbs wkstn64 administrator pa55w0rd1 -dli
C:\> cscript slmgr.vbs -skms 192.168.10.1:8090
C:\> cscript slmgr.vbs -skms KMSServer:8090
"One resolution I have made, and try always to keep, is this: To rise above little things" - John Burroughs
Related:
slui - Software Licensing (Windows 7 Activation)
Activation Error Codes - TechNet
WINVER - Display Licence Activation status
Q921471 - Activation fails when you try to activate Windows Vista, Windows 7...
PERMS - Show permissions for a user
SYSTEMINFO - List system configuration
SOON.exe (Resource Kit) Schedule a command to run in the near future (calls the AT command)
Syntax
SOON [\\computername] delay [/interactive] "command"
SOON /i:[on|off]
Key
delay : When the command should run, in SECONDS from now.
default=5
/interactive : Allows any user to see the job as it runs,
this allows testing and monitoring of the
command.
You can specify /interactive as just /i
computername : the UNC name of a remote machine
/i:on : Make /interactive the default behaviour
use SOON /i:off to restore normal behaviour
SOON schedules jobs to run at a time relative to the current time in "seconds from now"
It is otherwise identical to the AT command but saves calculating an exact start time.
As with all AT jobs you should test your SOON scripts by using the /INTERACTIVE option.
In many cases SCHTASKS may be a better option.
"We want the finest wines available to humanity. And we want them here and we want them now" - Bruce Robinson (Withnail and I )
Related:
SCHTASKS - Create or Edit Scheduled Tasks
Q237840 - Setting a delay of less than 60 seconds.
Powershell: To schedule a PS task call Powershell.exe
Equivalent bash command (Linux): crontab - Schedule a command, watch - Execute/display a program periodically
SORT
Sort will accept a redirected or piped file input and TYPE the file, sorted line by line.
Syntax
SORT [options]
Options
/R : Reverse sort order (Z to A, 9 to 0)
/+n : Sort the file ignoring the first 'n' characters in each row.
The default is to sort using all the chars in each row.
/L[OCALE] locale
Override the system default locale with
The "C" locale yields a faster
collating sequence.
The sort is always case insensitive.
/M[EMORY] kilobytes
The amount of RAM to use for the sort.
The best performance is usually achieved by
not specifying a memory size.
SORT will only create a temporary file
when required by limitations in available memory.
/REC[ORD_MAXIMUM] characters
The maximum number of characters in a row or record
(default 4096, maximum 65535)
[drive:][pathname]
The file to be sorted.
If not specified, the standard input is sorted.
Specifying an input file is faster than
redirecting the same file as standard input.
/T[EMPORARY] [drive:][path]
The path of the directory to hold
SORT's working storage, in case the data
does not fit in RAM. The default is %temp%
/O[UTPUT] [drive:][pathname]
The file where the sorted input is to be stored.
If not specified, the data is written to standard output.
Specifying an output file is faster than redirecting
standard output to a file.
Redirecting a file into SORT
SORT < pathname
Piping a command into SORT
command | SORT
Piping the output from SORT into a file
command | SORT > pathname2
SORT < pathname > pathname2
Piping the output from SORT and appending to an existing file
command | SORT >> pathname2
SORT < pathname >> pathname2
Cultivate peace and order before confusion and disorder - Tao Teh Ching
Related:
TYPE - Display the contents of a text file
Redirection - Redirect files, command output and error messages
Powershell: Sort-Object - Sort objects by property value (sort)
Equivalent bash command (Linux): sort - Sort text files
START
Start a specified program or command in a separate window.
Syntax
START "title" [/Dpath] [options] "command" [parameters]
Key:
title : Text for the CMD window title bar (required)
path : Starting directory
command : The command, batch file or executable program to run
parameters : The parameters passed to the command
Options:
/MIN : Minimized
/MAX : Maximized
/WAIT : Start application and wait for it to terminate
/LOW : Use IDLE priority class
/NORMAL : Use NORMAL priority class
/HIGH : Use HIGH priority class
/REALTIME : Use REALTIME priority class
/B : Start application without creating a new window. In this case
^C will be ignored - leaving ^Break as the only way to
interrupt the application
/I : Ignore any changes to the current environment.
Options for 16-bit WINDOWS programs only
/SEPARATE Start in separate memory space (more robust)
/SHARED Start in shared memory space (default)
Notes:
Always include a TITLE this can be a simple string like "My Script" or just a pair of empty quotes ""
According to the Microsoft documentation, the title is optional, but you may have problems if it is omitted.
Document files may be invoked through their file association just by typing the name of the file as a command.
e.g. START "" WORD.DOC would launch the application associated with the .DOC file extension
Examples
START "My Login Script" /Min Login.cmd
START "" /wait MySlowProgram.exe
Printers
A new printer can be installed very quickly (and the driver downloaded) with the command:
START \\print_server\printer_name
Setting a Working Directory
To start an application and specify where files will be saved:
START /Dc:\Documents\ /MAX "Maximised Notes" notepad.exe
Forcing a Sequence of Programs
If you require your users to run a sequence of 32 bit GUI programs to complete a task, create a batch file that uses the start command:
@echo off
start /wait /b First.exe
start /wait /b Second.exe
start /wait /b Third.exe
Create a shortcut to this batch file and place it on the Start menu or desktop. Set it to run minimized.
When the user double-clicks the shortcut, <First.exe> runs.
When <First.exe> terminates, <Second.exe> runs
When <Second.exe> terminates, <Third.exe> runs
An alternative method is to run a .BAT batch file under command.com (16 bit)
If Command Extensions are disabled, the START command will no longer recognise file Associations, and will not automatically evaluate the COMSPEC variable when starting a second CMD session.
Missing file extensions
When executing a command line whose first token does NOT contain an extension, then CMD.EXE uses the value of the PATHEXT environment variable to determine which extensions to look for and in what order. The default value for the PATHEXT variable is:
.COM;.EXE;.BAT;.CMD
Notice the syntax is the same as the PATH variable, with semicolons separating the different elements.
When executing a command, if there is no match on any extension, then Windows will look to see if the name, without any extension, matches a directory name and if it does, the START command will launch Explorer on that path.
"Do not run; scorn running with thy heels" - Shakespeare, The Merchant of Venice
Related:
CALL - Call one batch program from another
CMD - can be used to call a subsequent batch and ALWAYS return even if errors occur.
Powershell: Invoke-Item - Invoke an executable or open a file (ii)
Q162059 - Opening Office documents
Equivalent bash command (Linux) : open - Open a file in its default application.
SU (Resource Kit) Switch User.
Syntax
SU "[cmdline]" [domain] [[Winsta\]Desktop] [options]
Key
cmdline The command to run (default =%comspec%)
domain The domain for the user account ('.' = local m/c)
Winsta\Desktop The profile to load (default = current)
Options
-cb console bypass
-dn do not switch to new desktop
-g GUI option
-l load the .Default user registry hive
-w use current registry hive
-e Inherit parent environment
-b batch logon
-i interactive logon
-s service logon
-n network logon
-v verbose
All LogOn Types require specific User Rights to be granted...
SeNetworkLogonRight, SeServiceLogonRight, SeInteractiveLogonRight, SeBatchLogonRight
The RUNAS command is a lot easier to use!
“He who reigns within himself, and rules passions, desires, and fears, is more than a king” - Milton
Related:
RUNAS - Execute a program under a different user account.
PsExec - Execute process remotely
Powershell: you can run an entire powershell session via RunAs to elevate your permissions.
Equivalent bash command (Linux): su - Run a command with substitute user and group id
SUBINACL.exe (Resource kit)
Download latest version (2004)
Display or modify Access Control Entries (ACEs) for file and folder Permissions, Ownership and Domain.
Access Control Lists apply only to files stored on an NTFS formatted drive, each ACL determines which users (or groups of users) can read or edit the file. When a new file is created it normally inherits ACL's from the folder where it was created.
Syntax
SUBINACL [/noverbose] /object_type object_name [/action=parameter] [/help]
Key
object_type: service e.g. /service Messenger \\ServerName\Messenger
keyreg e.g. /keyreg HKEY_CURRENT_USER\Software
/keyreg \\Srv\HKEY_LOCAL_MACHINE\KeyPath
file e.g. /file *.obj /file c:\test.txt
/file \\ServerName\Share\Path
subdirectories manipulate files in specified directory and all subdirectories
object_name : This will vary according to the object_type - see the examples above
action : setowner=owner
will change the owner of the object e.g. /setowner=MyDomain\Administrators
replace=SamName\OldAccount=DomainName\New_Account
will replace all ACE (Audit and Permissions) in the object
e.g. /replace=MyOldDomain\Finance=NEWDOM\Finance
changedomain=OldDomainName=NewDomainName
will replace all ACEs with a Sid from OldDomainName
with the equivalent Sid found in NewSamServer
e.g. /changedomain=MyOldDomain=NEWDOMAIN
This option requires a trust relationship with the server containing the object.
When running subinacl against a subfolder, its important to include the trailing backslash, (or \*.*) if they are missed out subinacl may interpret the path as a filename and search the entire drive for it, this can be very slow. (This is the opposite behaviour of Robocopy but you didn't expect consistency did you! )
Examples:
subinacl can do everything that cacls and xcacls can do and more besides.
List permissions to log file:
subinacl /noverbose /nostatistic /outputlog=my.log /subdirectories "C:\Program Files\My Folder\*.*" /display
Restore Permissions:
subinacl /nostatistic /playfile my.log
Change owner :
subinacl /file C:\demofile.doc /setowner=MYDOMAIN\BillG
"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
CACLS - Change file permissions
XCACLS - Display or modify Access Control Lists (ACLs) for files and folders
PERMS - Show permissions for a user
FIXACLS - Restore default privs (Resource Kit supplement 2)
SHOWACL - Show file Access Control Lists (Windows 2000)
XCACLS - Display or modify Access Control Lists (ACLs) for files and folders
Q288129 - Grant users the right to manage services
Powershell: Set-Acl - Set permissions
Equivalent bash command (Linux): chmod - Change access permissions
SUBST
Substitute a drive letter for a network or local path.
Syntax
SUBST drive_letter: path
SUBST
SUBST drive_letter: /D
Key
SUBST with no parameters will display current SUBST drives
/D : Delete the drive_letter substitution.
Compared to mapping a drive with NET USE the SUBST command allows mapping to a subfolder of a drive share - for the storage of user profiles this reduces the number of shares you need to create on the server.
Notes
Under NT 4 SUBST'ed drives could be disconnected using the Explorer GUI - this was fixed in Windows 2000.
In Windows 2000 (and above) you may have problems creating, accessing and deleting drive mappings with SUBST.
However under Win 2K/XP the functionality of the NET USE command is improved so you can now do
NET USE g: \\server\share\folder1\folder2
If the network resource is unavailable (ie the server is down) SUBST will continually retry - unlike NET USE which will try to connect once and fail - depending on your application this may be a good or a bad thing - a subst drive that is not available will badly impact performance of most applications.
Notice that when SUBST is used against a local shared folder, it will create a RECYCLER for that drive. The RECYCLER is not removed when the drive substitution is removed, but can be deleted manually.
"A man should never be ashamed to own he has been in the wrong, which is saying in other words, that he is wiser today than he was yesterday" - Alexander Pope (thoughts on various subjects)
Related:
NET USE - Map a drive letter to a network drive
SYSTEMINFO
List system configuration
Syntax
SYSTEMINFO [/S system [/U username [/P [password]]] ]
[/FO format] [/NH]
Key:
/S system Remote system to connect to.
/U [domain\]user User context under which to execute.
/P [password] Password for the given user (will prompt if omitted)
/FO format Output format: TABLE, LIST or CSV
/NH No "Column Header" in the Table/CSV output
The output includes OS configuration, security info, product ID, RAM, disk space, and network cards.
Examples
SYSTEMINFO
SYSTEMINFO |find "Total Physical Memory:"
SYSTEMINFO /S wkstn6324
SYSTEMINFO /S wkstn6325 /FO CSV /NH >>pcaudit.csv
"A good question is like a miniskirt. Long enough to cover the essentials, but short enough to keep everyone interested" - Charles Halsey
Related:
WINMSD - Windows system diagnostics
WMIC - WMI Commands
PsGetSid - Display the SID of a computer or a user
Powershell: Get-WMIobject - Get WMI information
TASKLIST
TaskList displays all running applications and services with their Process ID (PID) This can be run on either a local or a remote computer.
Syntax
tasklist options
Options:
/s computer Name or IP address of a remote computer
don't use backslashes. Default = local computer.
/u domain\user [/p password]]
Run under a different account
/svc List information for each process without truncation.
Valid when /fo=TABLE. Cannot be used with /m or /v
/m [ModuleName]
Show the processes that include the given module.
/v Verbose task information
/fo {TABLE|LIST|CSV}]
Output format, the default is TABLE.
/nh No Headers in the output (does not apply to LIST output)
/fi FilterName [/fi FilterName2 [ ... ]]
Apply one of the Filters below:
Imagename eq, ne String
PID eq, ne, gt, lt, ge, le Positive integer.
Session eq, ne, gt, lt, ge, le Any valid session number.
SessionName eq, ne String
Status eq, ne RUNNING | NOT RESPONDING
CPUTime eq, ne, gt, lt, ge, le Time hh:mm:ss
MemUsage eq, ne, gt, lt, ge, le Any valid integer.
Username eq, ne User name ([Domain\]User).
Services eq, ne String
Windowtitle eq, ne String
Modules eq, ne String
Examples:
List the services running under each process:
TASKLIST /svc
List the services running under each SvcHost process:
TASKLIST /FI "imagename eq svchost.exe" /svc
List the services running now:
TASKLIST /v /fi "STATUS eq running"
List the services running under a specific user account:
TASKLIST /v /fi "username eq SERVICE_ACCT05"
“Here's to the success of our impossible task!” - Soviet dissidents, 1975
Related:
PsList - List detailed information about processes
TLIST - Task list with full path
PSTAT - display running tasks including all Process Threads.
MEM - Display memory usage
WINMSD - Windows NT Diagnostics (including Physical Memory)
WMIC /OUTPUT:C:\Procs.txt PROCESS get Caption,Commandline,Processid
Powershell: Get-Process - Get a list of processes on a machine (ps/gps)
Equivalent bash command (Linux): ps - Process status, information about processes running in memory.
TASKLIST End one or more processes (by process id or image name).
Syntax
TASKKILL [/S system [/U username [/P [password]]]]
{ [/FI filter] [/PID processid | /IM imagename] } [/F] [/T]
Options
/S system The remote system to connect to.
/U [domain\]user The user context under which
the command should execute.
/P [password] The password. Prompts for input if omitted.
/F Forcefully terminate the process(es).
/FI filter Display a set of tasks that match a
given criteria specified by the filter.
/PID process id The PID of the process to be terminated.
/IM image name The image name of the process to be terminated.
Wildcard '*' can be used to specify all image names.
/T Tree kill: terminates the specified process
and any child processes which were started by it.
Filters Apply one of the Filters below:
Imagename eq, ne String
PID eq, ne, gt, lt, ge, le Positive integer.
Session eq, ne, gt, lt, ge, le Any valid session number.
Status eq, ne RUNNING | NOT RESPONDING
CPUTime eq, ne, gt, lt, ge, le Time hh:mm:ss
MemUsage eq, ne, gt, lt, ge, le Any valid integer.
Username eq, ne User name ([Domain\]User).
Services eq, ne String The service name
Windowtitle eq, ne String
Modules eq, ne String The DLL name
Examples:
Examples:
TASKKILL /S system /F /IM notepad.exe /T
TASKKILL /PID 1230 /PID 1241 /PID 1253 /T
TASKKILL /F /IM notepad.exe /IM mspaint.exe
TASKKILL /F /FI "PID ge 1000" /FI "WINDOWTITLE ne untitle*"
TASKKILL /F /FI "USERNAME eq NT AUTHORITY\SYSTEM" /IM notepad.exe
TASKKILL /S system /U domain\username /FI "USERNAME ne NT*" /IM *
TASKKILL /S system /U username /P password /FI "IMAGENAME eq note*"
“Here's to the success of our impossible task!” - Soviet dissidents, 1975
Related:
PsKill - Kill processes by name or process ID
Powershell: Stop-Process - Kill a process
Equivalent bash command (Linux): kill - Kill a process
TIME Display or set the system time.
Syntax
TIME [new_time]
TIME
TIME /T
key
new_time : The time as HH:MM
TIME with no parameters will display the current time and prompt
for a new value. Pressing ENTER will keep the same time.
/T : Just display the time, formatted according to the current Regional settings.
Time Formatting
In Control Panel, Regional settings a Time Appearance can be set. This can be used to change the separator, and the number of characters used to display hours and minutes.
To display the time including Seconds:
ECHO.| TIME will display the time, including seconds and hundredths of a second
The time separator and the Country Code are user settings in the registry:
The time separator can be read using REG as follows
@echo off
FOR /F "TOKENS=3" %%D IN ('REG QUERY ^"HKEY_CURRENT_USER\Control Panel\International^" /v sTime ^| find ^"REG_SZ^"') DO (
SET _time_sep=%%D)
echo %_time_sep%
To read the Country Code replace sTime in the above with iCountry.
The time formats for different country codes are as follows:
Country or language CountryCode Date format Time format
United States 001 01/03/1994 5:35:00.00p
Czechoslovakia 042 03.01.1994 17:35:00
France 033 03.01.1994 17:35:00
Germany 049 03.01.1994 17:35:00
Latin America 003 03/01/1994 5:35:00.00p
International English 061 03/01/1994 17:35:00.00
Portugal 351 03-01-1994 17:35:00
Finland 358 3.1.1994 17.35.00
Switzerland 041 03.01.94 17 35.00
Norway 047 03.01.94 17:35:00
Belgium 032 03/01/94 17:35:00
Brazil 055 03/01/94 17:35:00
Italy 039 03/01/94 17.35.00
United Kingdom 044 03/01/94 17:35:00.00
Denmark 045 03-01-94 17.35.00
Netherlands 031 03-01-94 17:35:00
Spain 034 3/01/94 17:35:00
Hungary 036 1994.01.03 17:35:00
Canadian-French 002 1994-01-03 17:35:00
Poland 048 1994-01-03 17:35:00
Sweden 046 1994-01-03 17.35.00
If Command Extensions are disabled TIME will not support the /T switch
“Time is like money, the less we have of it to spare, the further we make it go” - Josh Billings
Related:
%TIME% - variable containing current time
DATE - Display or change the date
NOW - Display Message with Current Date and Time
TIMESERV - Time Service (resource kit)
W32TIME - Time Service (y2K compliant update for TIMESERV)
Timethis - Time how long it takes the system to run a command. (Win 2K ResKit)
Uptime - Time since last reboot. (Win 2K ResKit)
GetTime.cmd - Script to get current time
GMT.cmd - Current time in GMT (World Time)
Q307938 - Change Date and Time display (remove leading zeros)
Powershell: Get-Date - Get current date and time
Equivalent bash command (Linux): date - Display or change the date & time
TIMEOUT.exe (Resource Kit)
Delay execution for a few seconds/minutes (for use within a batch file.)
Syntax
TIMEOUT delay
Key
delay Delay in seconds (between -1 and 100000) to wait before continuing.
The value -1 causes the computer to wait indefinitely for a keystroke
(like the PAUSE command)
Timeout will pause command execution for a number of seconds, after which it continues without requiring a user keystroke. If the user does press a key at any point, execution will resume immediately.
Alternative
A delay can also be produced by the PING command with a loopback address, in tests this consumes less processor time than Sleep.exe or Timeout.exe:
e.g. for a delay of 40 seconds:
PING -n 41 127.0.0.1>nul
See Clay Calvert's newsgroup posting for a full explanation of this technique.
“It is awful work this love and prevents all a mans projects of good or glory” - Lord Byron
Related:
PAUSE - Suspend processing of a batch file and display a message
SLEEP - Delay execution for a few seconds/minutes (for use within a batch file.)
WAITFOR - Wait for or send a signal.
Powershell: Start-Sleep - Suspend shell, script, or runspace activity (sleep)
TITLE Change the title displayed above the CMD window.
Syntax
TITLE [string]
Key
string : The title for the command prompt window.
The default title is %comspec% however, since the title can also be defined in a program shortcut, the title is usually set to "Command Prompt"
To change the title for the duration of a command use:
TITLE This is the initial title text
CMD /c MyBatchFile.cmd
...
If MyBatchFile.cmd contains a different TITLE command it will revert when the second command session ends.
The START command, used to start a program in a separate window also has an option to specify a title for the new Window.
"The longer the title, the less important the job." - George McGovern.
Related:
MODE - change the size of the CMD window
COLOR - change the colour of the CMD window
PROMPT - change the CMD window prompt
START - start a program in a separate window
QuickEdit mode - also changes the title (temporarily)
Powershell: Set the console title to current working dir (save in Profile.ps1 to make permanent)
TLIST (Resource Kit & Windows 2000 support tools) Task List.
Show the command, command line, working directory, memory usage and DLLs for each running task. This command is no longer supplied with recent versions of the Windows resource kit, having been replaced by TASKLIST, however if you can find a copy Tlist does have the advantage of showing the full path of the process.
Syntax
TLIST
TLIST -t
TLIST pid
TLIST -t pid
TLIST pattern
TLIST -t pattern
Key
-t : Show Task dependencies in Tree form
pid : List module information for this task
if no PID is given - all Tasks are listed
pattern : A complete task name or expression pattern (e.g. CMD.*)
if a pattern is given it will match against
task names or window titles.
Example:
The following batch file will show the full path of all running programs.
@ECHO off
FOR /f "tokens=1" %%G in ('tlist') DO (call :s_item %%G)
GOTO :eof
:s_item
tlist %1 | find "CmdLine"
"When I first started running, I was so embarrassed, I'd walk when cars passed me. I'd pretend I was looking at the flowers" - Joan Benoit Samuelson, 1984 Olympic Marathon gold medalist
Related:
PsList - List detailed information about processes
TASKLIST - List running applications and services
MEM - Display memory usage
WINMSD - Windows NT Diagnostics (including Physical Memory)
Powershell: Get-Process - Get a list of processes on a machine (ps/gps)
Equivalent bash command (Linux): ps - Process status, information about processes running in memory.
TOUCH (Windows 2000 Resource Kit) Change file timestamps
Syntax
TOUCH [option]... files ...
Key
/t year month day hour minute second
This is a POSIX utility.
Use the optional argument /t to specify a date other than the current time.
( four-digit years, two-digit months, days, hours, minutes, seconds)
Example
To set the date to 7:30 am 1st October 2015
TOUCH /t 2015 10 01 07 30 00 MyFile.txt
#And smiles you'll give and tears you'll cry
And all you touch and all you see
Is all your life will ever be# - Pink Floyd (Breathe)
Related:
Q299648 - Date and Time Stamps for Files and Folders
COPY - Copy one or more files to another location
Equivalent PowerShell Script: touch - Change file timestamps
Equivalent bash command (Linux): touch - Change file timestamps
TRACERT Trace Route - Find the IP address of any remote host. TRACERT is useful for troubleshooting large networks where several paths can be taken to arrive at the same point, or where many intermediate systems (routers or bridges) are involved.
Syntax
TRACERT [options] target_name
Key
target_name The HTTP or UNC name of the host
Options:
-d Do not resolve addresses to hostnames.
(avoids performing a DNS lookup)
-h max_hops Maximum number of hops to search for target.(default=30)
-j host-list Trace route along given host-list.
up to 9 hosts in dotted decimal notation, separated by spaces.
-w timeout Wait timeout milliseconds for each reply.
The functionality of TRACERT is the same under all versions of windows but the output is cosmetically improved under XP.
Tracert uses the IP TTL field and ICMP error messages to determine the route from one host to another through a network.
Care must be taken with tracert as it shows the optimal route, not necessarily the actual route. To be accurate, it is possible to ping from a UNIX machine back to the PC using the -R option to record the route taken - but only if the particular network devices support it.
This diagnostic tool determines the path taken to a destination by sending ICMP Echo Request messages with varying Time to Live (TTL) values to the destination.
TTL (Time to Live) calculation
TTL is effectively a count of the (maximum) number of links to the destination host. Each router along the path decrements the TTL in an IP packet by at least 1 before forwarding it.
When the TTL on a packet reaches 0, the router is expected to return an ICMP Time Exceeded message to the source computer.
Tracert determines the path by sending the first Echo Request message with a TTL of 1 and incrementing the TTL by 1 on each subsequent transmission until either the target host responds or the maximum number of hops is reached.
This process relys on intermediate routers to return ICMP Time Exceeded messages. However, some routers do not return Time Exceededmessages for packets with expired TTL values and are invisible to the tracert command. In this case, a row of asterisks (*) is displayed for that hop.
Firewalls
Many firewalls will block ICMP traffic by default. If an attacker is able to forge ICMP redirect packets, he or she can alter the routing tables on the host and possibly subvert the security of the host by causing traffic to flow via a path you didn't intend.
Examples
TRACERT www.doubleclick.net
TRACERT 123.45.67.89
TRACERT local_server
Get your kicks on ROUTE 66 - Jack Kerouac.
Related:
NSLOOKUP - Name server lookup
PING - Test a network connection
PATHPING - Trace route and provide network latency and packet loss for each router and link in the path.
ROUTE - Manipulate network routing tables
Q314868 - How to use TRACERT to troubleshoot TCP/IP
TRACE.bat - PCHelp's handy report on any given Internet address
tracert.com - trace routes from remote locations
Equivalent bash command (Linux): traceroute - Print the route packets take to network host.
TsShutDn
Remotely shut down or reboot a terminal server. If the computer supports software control of AC power this command may be used to power off the server.
Syntax
TSSHUTDN [WaitTime] [/server:ServerName] [/reboot] [/powerdown]
[/delay:LogOffDelay] [/v]
Key
WaitTime An amount of time (in seconds) to wait after notifying users before logging off
all users from their sessions. Default = 60 seconds.
/server The terminal server to shut down.
If unspecified, the current terminal server is shut down.
/reboot Reboot the terminal server after user sessions are ended.
/powerdown Turn off the terminal server if the computer supports software control of AC power.
/delay The amount of time to wait after logging off users from their sessions,
before ending all processes and shutting down the terminal server.
Default = 30 seconds.
/v Display verbose information about the actions being performed.
/? Display help.
You must have administrative privileges run tsshutdn.
Using Start Menu | ShutDown is not recommended for shutting down a terminal server as that method does not notify users before ending their sessions.
All connected sessions are notified. Sessions that have applications with open files will prompt the user to save the files. After initiating the logoff command, tsshutdn waits a specified interval, before ending all processes.
Tsshutdn does not reboot the terminal server unless the /reboot option is specified.
Examples
End all client sessions 60 seconds after notification, and then 30 seconds after all the users are logged off, shutdown the current terminal server:
TSSHUTDN /v
End all client sessions 5 minutes after notification, and then 1 minute after all the users are logged off, shutdown and restart the terminal server:
TSSHUTDN 300 /reboot /delay:60 /v
On the terminal server named "Server64", end all client sessions 2 minutes after notification, and then 20 seconds after all the users are logged off, shutdown and restart the terminal server:
TSSHUTDN 120 /server:server64 /delay:20 /v
“Perhaps I'm old and tired, but I always think that the chances of finding out what really is going on are so absurdly remote that the only thing to do is to say hang the sense of it and just keep yourself occupied” - Douglas Adams
Related:
PsShutdown - SysInternals command line tool
SHUTDOWN - Shutdown the computer
TYPE
Display the contents of one or more text files, convert Unicode to ANSI.
Syntax
TYPE [drive:]pathname(s)
If more than one file is specified the filenames are included in the output.
If a wildcard is used the filenames are not displayed.
Output can be redirected into a new file:
TYPE file.txt > Newfile.txt
Output can be appended to an existing file:
TYPE file.txt >> ExistingFile.txt
To do the same with user console input :
TYPE CON > Newfile.txt
This will require typing a CTRL-Z to indicate the end of file.
When using redirection to SORT a file the TYPE command is used implicitly
For example:
SORT < MyFile.txt
Create an empty (zero byte) file:
TYPE nul >filename.log
If you TYPE a Unicode text file, the output will be Ascii (Windows1252). This behaviour is more a limitation of the CMD shell than a designed feature, any extended characters will be discarded. To work with Unicode files use PowerShell.
eg:
TYPE UnicodeFile.txt > Ascii.txt
“Writing is easy; all you do is sit staring at a blank sheet of paper until the drops of blood form on your forehead” - Gene Fowler
Related:
FOR /F
SORT
Powershell: Get-Content - Get content from item (cat / type / gc)
Equivalent bash command (Linux): cat - Display the contents of a file
TypePerf.exe Write performance data to the command window or to a log file.To stop Typeperf, press CTRL+C.
Syntax
typeperf counter [counter ...] [options]
typeperf -cf filename [options]
typeperf -q [object] [options]
typeperf -qx [object] [options]
Key
counter The Performance counters to monitor.
-f {CSV|TSV|BIN|SQL} Output file format. Default is CSV.
-cf filename File containing performance counters to monitor, one per line.
-si [[hh:]mm:]ss Time between samples. Default is 1 second.
-o filename Path of output file or SQL database.
Default is STDOUT.
-q [object] List installed counters (no instances).
To list counters for one object,
include the object name, such as Processor.
-qx [object] List installed counters with instances.
To list counters for one object,
include the object name, such as Processor.
-sc samples Number of samples to collect. Default is
to sample until CTRL+C.
-config filename Settings file containing command options.
-s computer_name Server to monitor if no server is specified in the counter path.
-y Answer yes to all questions without prompting.
-? Display context sensitive help.
Counter is the full name of a performance counter in the format:"\\Computer\Object(Instance)\Counter"
e.g. "\\Server1\Processor(0)\% User Time".
Examples
Display % Processor time until interrupted:
C:\> typeperf "\Processor(_Total)\% Processor Time"
Gather 600 samples of % Processor time on the local computer (this will take 10 minutes):
C:\> typeperf "\processor(_Total)\% Processor Time" -O C:\SS64demo1.csv -SC 600
Gather samples of all the counters listed in counters.txt :
C:\> typeperf -cf counters.txt -si 5 -sc 50 -o C:\SS64demo2.csv
“Weekends don't count unless you spend them doing something completely pointless” - Bill Watterson
Related:
LOGMAN - Manage Performance Monitor
Powershell: New-Object System.Diagnostics.PerformanceCounter
Powershell: Get-WmiObject Win32_Process -Filter "Name='System idle process'" | Format-List Name, KernelModeTime
VER Display the current operating system version.
Syntax
VER
Use ver to find specific operating systems like this:
@Echo off
Setlocal
:: Get windows Version numbers
For /f "tokens=2 delims=[]" %%G in ('ver') Do (set _version=%%G)
For /f "tokens=2,3,4 delims=. " %%G in ('echo %_version%') Do (set _major=%%G& set _minor=%%H& set _build=%%I)
Echo Major version: %_major% Minor Version: %_minor%.%_build%
if "%_major%"=="5" goto sub5
if "%_major%"=="6" goto sub6
Echo unsupported version
goto:eof
:sub5
::Winxp or 2003
if "%_minor%"=="2" goto sub_2003
Echo Windows XP [%PROCESSOR_ARCHITECTURE%]
goto:eof
:sub_2003
Echo Windows 2003 or XP 64 bit [%PROCESSOR_ARCHITECTURE%]
goto:eof
:sub6
if "%_minor%"=="1" goto sub7
Echo Windows Vista or Windows 2008 [%PROCESSOR_ARCHITECTURE%]
goto:eof
:sub7
Echo Windows 7 or Windows 2008 R2 [%PROCESSOR_ARCHITECTURE%]
goto:eof
Service Pack Version
This Batch script will give the Service Pack level.
Works for NT, Win2K or WinXP
“Always be a first-rate version of yourself, instead of a second-rate version of somebody else” - Judy Garland
Related:
Q190899 - How to Determine the OS Type in a Logon Script
WINVER.exe - Opens the GUI Version dialogue box (Help, About)
FILEVER - DLL version information (Resource Kit, XP Support tool)
Wikipedia - Microsoft Windows Version Numbers
Powershell: Get OS and Service pack
Equivalent bash command (Linux): uname -r - Print system information
VERIFY To check that files are saved to disk correctly; the system can re-read the disk when saving and verify (compare) with the data in memory.
Syntax
VERIFY [ON | OFF]
By default the CMD shell has verify OFF
Windows Explorer will always copy with verify ON
Copying files can be up to twice as fast with verify OFF.
VERIFY without a parameter will display the current setting.
"VERIFY dummy_text" will set %ERRORLEVEL% to 1
"Women might be able to fake orgasms. But men can fake whole relationships" - Sharon Stone
Related:
MOVE - Move files from one folder to another
EXIT - Quit the current script/routine, optionally setting an errorlevel.
Equivalent bash command (Linux): cksum - Print CRC checksum and byte counts
VOL Display the volume label of a disk.
Syntax
VOL [drive:]
If the drive exists, VOL will display it's disk label and serial number and will return an %ERRORLEVEL% of 0.
If the drive does not exist VOL will return an %ERRORLEVEL% of 1.
If the drive is a CD/DVD drive with no disk loaded then VOL will return "The device is not ready" and will return an %ERRORLEVEL% of 1.
"I've found the Nobel label very handy because who'd want to hear anything from Betty Williams, ordinary housewife?" - Betty Williams Nobel Prize 1976
Related:
LABEL - Edit the volume label of a disk
BootCFG - Edit Boot.ini settings.
powershell: Get-WmiObject Win32_LogicalDisk $label
Equivalent bash command (Linux): hostname - Print or set system name
WAITFOR.exe (2003 Resource Kit, standard in Windows 7/2008)
Wait for or send a signal. Waitfor is used to synchronize events between one or more networked computers.
Syntax
Wait for a signal:
waitfor [/t Timeout] SignalName
Send a signal:
waitfor [/s Computer [/u [Domain\]User [/p [Password]]]] /si SignalName
Key
/s Computer The name or IP address of the computer to signal
(do not include backslashes).
/u User Run the script using the credentials of the specified user account.
By default, waitfor uses the current user's credentials.
/p [Password] The password of the user account specified with /u
/si Send the signal across the network to waiting machines.
/t Timeout Number of seconds to wait for a signal.
The valid range is 1 - 99999 (27.7 hours)
default = wait indefinitely.
SignalName The signal that waitfor waits for or sends.
SignalName is not case-sensitive.
/? Display help.
Signal names cannot exceed 225 characters. Valid characters include a-z, A-Z, 0-9, the SignalName is not case-sensitive.
If the command line includes /s Computer, the signal will be broadcast only to the specified system rather than all the computers across the domain. On large domains or wide area networks this will reduce unnecessary network traffic.
To cancel WAITFOR before its timeout has been reached, either launch Waitfor /si signal from a separate command-prompt or KILLthe session.
You can run multiple instances of WAITFOR on a single computer, but each instance must wait for a different signal. Only one instance of WAITFOR can wait for a given signal on a given computer. Computers can only receive signals if they are in the same domain as the computer sending the signal.
Batch scripts including WAITFOR may be run as Scheduled tasks under the SYSTEM account.
Typical WAITFOR applications include waiting for large ROBOCOPY jobs to complete, restarting services across a cluster/farm, FTP or BITS downloads, compiling software builds etc.
Examples
Wait for 60 seconds or until the "simon" signal is received on the local computer:
C:\> waitfor /t 60 simon
Activate the "simon" signal on the local computer:
C:\> waitfor /s %computername% /si simon
Wait for 1 hour or until the "backupComplete" signal is received on the local computer:
C:\> waitfor /t 3600 BackupComplete
Activate the "backupComplete" signal on the computer Server64:
C:\> waitfor /s Server64 /si backupComplete
“Non-violence is not inaction. It is not discussion. It is not for the timid or weak... Non-violence is hard work. It is the willingness to sacrifice. It is the patience to win” - Cesar Chavez
Related:
PAUSE - Suspend processing of a batch file and display a message
SLEEP - Delay execution for a few seconds/minutes (for use within a batch file.)
TIMEOUT - Delay execution for a few seconds/minutes (for use within a batch file.)
Powershell: Start-Sleep - Suspend shell, script, or runspace activity (sleep)
Bash: wait - Wait for a process to complete
WHERE (2K Resource Kit / Windows 2003) Locate and display files in a directory tree.
The WHERE command is roughly equivalent to the UNIX 'which' command. By default, the search is done in the current directory and in thePATH.
Syntax
WHERE [/r Dir] [/q] [/f] [/t] Pattern ...
key
/r A recursive search, starting with the specified Dir directory.
/q Don't display the files but return either an exit code of 0 for success
or 1 for failure.
/f Display the output file name in quotation marks.
/t Display the size, time stamp, and date stamp of the file.
/e Report the executable type.
pattern The name of a folder, file, or set of files to be found.
you can use wildcard characters ( ? * ) and UNC paths.
As an alternative to this command you can use this 90-character batch file:
@for %%e in (%PATHEXT%) do @for %%i in (%1%%e) do @if NOT "%%~$PATH:i"=="" echo %%~$PATH:i
(from the OldNewthing blog)
Examples
Find all files named 'Zappa' in drive C: (including subdirectories)
WHERE /r c:\ Zappa
Find all files named 'Zappa' on the remote computer 'Server1' searching its subdirectories, and reporting the executable type for executable files
WHERE /r \\Server1\Share1 /e Zappa.*
“Who never walks, save where he sees men's tracks, makes no discoveries” - Josiah Gilbert Holland
Related:
CD - Change Directory
TYPE - Display the contents of a text file
Equivalent bash command (Linux): which - Show full path of commands
Equivalent Powershell command: (get-command $file).Definition
Equivalents in Batch/Perl/VBScript - WHICH Scripts, which.cmd
WHOAMI.exe (Resource kit)
Displays the username and domain for the currently logged in user.
The whoami output is the same as the 2 environment variables %USERDOMAIN% and %USERNAME%.
So the same output can usually be achieved with
ECHO %USERDOMAIN%\%USERNAME%
One exception to this is when using RUNAS /env , e.g. if my username is Simon:
c:>RunAs /env /user:JDoe cmd.exe
c:>ECHO %USERDOMAIN%\%USERNAME%
ss64\Simon
c:>whoami
ss64\JDoe
WHOAMI /all - shows all permissions and group memberships.
"We can now manipulate images to such an extrodinary extent that there's no lie you cannot tell" - Sir David Attenborough
Related:
SET - Display, set, or remove Windows environment variables
VER - Display version information
VOL - Display a disk label
Whereami.cmd - Display user information
Powershell: "env:userdomain" "env:username"
Equivalent bash command (Linux): whoami - Print the current user id and name (`id -un')
WinDiff (Windows SDK) Compare the contents of two files or sets of files with a graphical interface.
Syntax
windiff [path1] [path2]
Key
path Individual files to compare
or a directory of files to compare
If either path is not specified it will default to the current directory (or a matching file in the current directory)
If nothing is specified, the GUI will appear - select files to compare with the menus.
White background = parts common to both files.
Red background = parts that belong to the file listed on the left .
Yellow background = parts that belong to the file listed on the right .
Registry files (exported with regedit) can also be compared. Also see the help file Windiff.hlp.
Downloads
Microsoft Windows 2003 SDK (large download)
Microsoft Windows 2008 SDK (large download)
WinDiff - Grigsoft (3rd party) download 75 Kb
"Shall I compare thee to a summer's day? Thou art more lovely and more temperate.
Rough winds do shake the darling buds of May, And summer's lease hath all too short a date" - Shakespeare
Related:
COMP - Compare two files and display any characters which do NOT match
FC - Compare two files
FIND - Search for a text string in a file
FINDSTR - Search for strings in files
WinMerge - Free compare utility
Beyond Compare - not free
Q171780 - Use WinDiff to compare registry files
Equivalent bash command (Linux): diff - Display the differences between two files
WINMSDP.exe (Resource Kit) Windows NT diagnostics II
Reports: Memory use, Services, Devices, IRQ's Ports, Environment variables,
Network (rights, transport, stats), Hardware including Display adapter.
Syntax
WINMSDP option
Key (only one option can be used)
/a : ALL prints everything
/e : environment
/d : drives
/i : interrupt resources
/m : memory
/n : network
/o : OS version
/p : port resources
/r : drivers
/s : services
/u : DMA resources
/w : hardware
/y : memory resources
The output is very similar to WINMSD if a little more detailed.
The output will appear in a text file called msdrpt.TXT
"The best is the enemy of the good" - Voltaire
Related:
WINMSD - Windows NT Diagnostics
Q102468 - How to use WINMSDP
Q231368 - IIS/Site Server vulnerability via WINMSDP
Q310747 - System File Checker (Sfc.exe)
WINRM
Windows Remote Management
Secure communication with local and remote computers using web services.
Syntax
winrm g[et] | s[et] | c[reate] | d[elete] | e[numerate] |
i[nvoke] | id[entify] | quickconfig | configSDDL | helpmsg
Retrieve instances of RESOURCE_URI:
winrm get RESOURCE_URI [-SWITCH:VALUE [-SWITCH:VALUE] ...]
winrm get winrm/config
winrm get winrm/config/client
winrm get winrm/config/service
Modify settings in RESOURCE_URI:
winrm set RESOURCE_URI [-SWITCH:VALUE [-SWITCH:VALUE] ...]
[@{KEY="VALUE"[;KEY="VALUE"]}]
[-file:VALUE]
Spawn an instance of RESOURCE_URI:
winrm create RESOURCE_URI [-SWITCH:VALUE [-SWITCH:VALUE] ...]
[@{KEY="VALUE"[;KEY="VALUE"]}]
[-file:VALUE]
Control remote access to WinRM resources, launch a GUI to edit security settings.
winrm configsddl RESOURCE_URI
Enable this machine for remote management.
winrm quickconfig [-quiet] [-transport:VALUE]
This will start the WinRM service, set the service to auto start, create
a listener and enable an http firewall exception for WS-Management traffic
-q[uiet] Don't prompt for confirmation.
-transport:VALUE Perform quickconfig for either http or https. Default = http.
List instances of RESOURCE_URI:
winrm enumerate RESOURCE_URI [-ReturnType:Value] [-Shallow]
[-BasePropertiesOnly] [-SWITCH:VALUE [-SWITCH:VALUE] ...]
Remove an instance of RESOURCE_URI:
winrm delete RESOURCE_URI [-SWITCH:VALUE [-SWITCH:VALUE] ...]
Execute method specified by ACTION on target object specified by RESOURCE_URI
winrm invoke ACTION RESOURCE_URI [-SWITCH:VALUE [-SWITCH:VALUE] ...]
[@{KEY="VALUE"[;KEY="VALUE"]}]
[-file:VALUE]
Display error message associate with the error code.
winrm helpmsg errorcode
Key
-a[uthentication]:VALUE
The authentication mechanism to use when communicating
with the remote machine.
-defaultCreds Allow implicit credentials when Negotiate is used.
Remote HTTPS operations for trusted machines.
-dialect:VALUE Dialect of the filter expression for enumeration or fragment.
Example: Use a WQL query
-dialect:http://schemas.microsoft.com/wbem/wsman/1/WQL
Example: Use XPATH for filtering with enumeration or fragment get/set.
-dialect:http://www.w3.org/TR/1999/REC-xpath-19991116
-encoding:VALUE The encoding type when talking to remote machine (see -remote).
Possible options are "utf-8" (the default) or "utf-16".
-f[ormat]:FORMAT The format of output. FORMAT can be "xml",
"pretty" (better formatted XML), or "text".
-r[emote]:VALUE Specify the identifier of a remote endpoint/system.
This may be a simple host name or a complete URL.
-skipCAcheck The certificate issuer need not be a trusted root authority.
Remote HTTPS operations for trusted machines.
-skipCNcheck The certificate common name (CN) of the server need not match
the hostname of the server. HTTPS operations for trusted machines.
-skipRevocationcheck Do not check the revocation status of the server certificate.
Remote HTTPS operations for trusted machines.
-SPNPort Append port number to the Service Principal Name (SPN) of the
remote server.
Service principal name is used when Negotiate or Kerberos authentication
mechanism is in use.
-timeout:MS Timeout in milliseconds. Limits duration of corresponding operation.
Default timeout can be configured by:
winrm set winrm/config @{MaxTimeoutms="XXXXXX"}
Where XXXXXX is an integer indicating milliseconds.
-file:VALUE
@{KEY="VALUE"[;KEY="VALUE"]}
Input from an XML file or via key/value pairs.
Applies to set, create, and invoke operations
-fragment:VALUE Specify a section inside the instance XML that is to be updated or
retrieved for the given operation.
Example: Get the status of the spooler service
winrm get wmicimv2/Win32_Service?name=spooler -fragment:Status/text()
-options:{KEY="VALUE"[;KEY="VALUE"]}
Key/value pairs for provider-specific options.
Example:
-options:{key1="value1";key2=$null}
WinRM is the Microsoft implementation of WS-Management Protocol, a standard Simple Object Access Protocol (SOAP)-based, firewall-friendly protocol that allows hardware and operating systems, from different vendors, to interoperate.
To improve security, WinRM 2.0 uses HTTP/HTTPS ports 5985/5986 by default.
If the computer name is passed using r:<Computername> , then the default client port will be used (by default, 5985/5986).
If the computer name is passed as a URI, such as r:http://Mycomputer/wsman, then the IE default ports will be used (ports 80/443 by default).
Examples
Configure Windows Remote Management on the server (DemoServer2), run this from an elevated CMD (or powershell) prompt:
C:\> winrm quickconfig
On a client you can then open a remote shell connected to DemoServer2 with:
winrs -r:DemoServer2 cmd
Retrieve current configuration in XML format:
winrm get winrm/config -format:pretty
Retrieve spooler instance of Win32_Service class:
winrm get wmicimv2/Win32_Service?Name=spooler
Modify a configuration property of WinRM:
winrm set winrm/config @{MaxEnvelopeSizekb="100"}
Disable a listener on this machine:
winrm set winrm/config/Listener?Address=*+Transport=HTTPS @{Enabled="false"}
Create instance of HTTP Listener on IPv6 address:
winrm create winrm/config/Listener?Address=IP:3ffe:8311:ffff:f2c1::5e61+Transport=HTTP
Delete the HTTP listener on this machine for given IP address:
winrm delete winrm/config/Listener?Address=IP:192.168.2.1+Transport=HTTP
Call StartService method on Spooler service:
winrm invoke StartService wmicimv2/Win32_Service?Name=spooler
Call Create method of Win32_Process class with specified parameters:
winrm invoke Create wmicimv2/Win32_Process @{CommandLine="notepad.exe";CurrentDirectory="C:\"}
Display error message associated with the error code 0x5:
winrm helpmsg 0x5
“Start where you are. Distant fields always look greener, but opportunity lies right where you are. Take advantage of every opportunity of service” - Robert Collier
Related:
WINRS - Windows Remote Shell
Powershell: New-PSSession - this cmdlet now takes on two different parameter sets: ComputerName and ConnectionURI.
WINRS Windows Remote Shell
Syntax
winrs [-/SWITCH[:VALUE]] COMMAND
Key
COMMAND Any string that can be executed as a command in the cmd.exe shell.
(All switches accept both short form or long form. For example both -r and
-remote are valid.)
-r[emote]:ENDPOINT The target endpoint using a NetBIOS name or the standard
connection URL: [TRANSPORT://]TARGET[:PORT].
If not specified -r:localhost is used.
-un[encrypted] Messages to the remote shell will not be encrypted. This is useful for
troubleshooting, or when the network traffic is already encrypted using
ipsec, or when physical security is enforced.
By default the messages are encrypted using Kerberos or NTLM keys.
This switch is ignored when HTTPS transport is selected.
-u[sername]:USERNAME Username. If -username is specified, -password must be as well.
If not specified Winrs will negotiate authentication or prompt.
-p[assword]:PASSWORD Password. If not specified winrs will prompt for it.
-d[irectory]:PATH The starting directory for remote shell.
If not specified the remote shell will start in %USERPROFILE%.
-env[ironment]:STRING=VALUE
A single environment variable to be set when shell starts.
This allows changing default environment for the shell.
Multiple occurrences of this switch may be used.
-noe[cho] Disable echo. This may be necessary to ensure that user's answers
to remote prompts are not displayed locally. By default echo is "on".
-nop[rofile] Do not load the user's profile. By default the server will attempt to load
the user profile. If the remote user is not a local administrator on the
target system then this option will be required.
-comp[ression] Turn on compression. Older installations on remote machines may
not support compression so it is off by default.
-[use]ssl Use an SSL connection when using a remote endpoint. Specifying this instead
of the transport "https:" will use the default WinRM default port.
-? Help
To terminate the remote command press Ctrl-C or Ctrl-Break, which will be sent to the remote shell. The second Ctrl-C will force termination of winrs.exe.
The URI alias to manage active shells is shell/cmd. The URI alias for WinRS configuration is winrm/config/winrs.
Examples
Configure Windows Remote Management on the server (DemoServer2), run this from an elevated CMD (or powershell) prompt:
C:\> winrm quickconfig
On a client you can then open a remote shell connected to DemoServer2 with:
winrs -r:DemoServer2 cmd
Batch file to quickly open a remote cmd shell:
[rshell.cmd]
@echo off
winrs -r:%1 cmd
Run a dir command on a remote machine:
C:\> winrs -r:DemoServer3 dir
Run an install package on a remote server:
C:\> winrs -r:Server25 msiexec.exe /i c:\install.msi /quiet
Run a powershell script on the remote box:
C:\> winrs /r:DemoServer2 powershell.exe -nologo -noprofile -command d:\test\test.ps1
Note that you can't open a full interactive remote powershell console, but as remoting functionality is built-in to Powershell 2.0 there isn't any need.
Connecting to the remote server 'myserver'
winrs -r:https://myserver.com command
winrs -r:myserver.com -usessl command
winrs -r:myserver command
winrs -r:http://127.0.0.1 command
winrs -r:http://169.51.2.101:80 -unencrypted command
winrs -r:https://[::FFFF:129.144.52.38] command
winrs -r:http://[1080:0:0:0:8:800:200C:417A]:80 command
winrs -r:https://myserver.com -t:600 -u:administrator -p:$%fgh7 ipconfig
winrs -r:myserver -env:PATH=^%PATH^%;c:\tools -env:TEMP=d:\temp config.cmd
winrs -r:myserver netdom join myserver /domain:testdomain /userd:johns /passwordd:$%fgh789
“Perhaps when distant people on other planets pick up some wavelength of ours all they hear is a continuous scream” - Iris Murdoch
Related:
WINRM - Windows Remote Management, manage active remote shells & WinRS configuration.
Powershell: New-PSSession - this cmdlet now takes on two different parameter sets: ComputerName and ConnectionURI.
WMIC.exe Windows Management Instrumentation Command.
Read a huge range of information about local or remote computers. Also provides a way to make configuration changes to multiple remote machines.
Syntax
Retrieve information about <Alias>:
WMIC [global_switches] [/locale:ms_409] <alias> [options] [format]
Interactive mode:
WMIC
Aliases:
ALIAS - Access local system aliases [CALL]
BASEBOARD - Base board management (motherboard or system board)
BIOS - BIOS management (Basic input/output services)
BOOTCONFIG - Boot configuration
CDROM - CD-ROM
COMPUTERSYSTEM - Computer system [CALL/SET]
CPU - CPU
CSPRODUCT - Computer system product information from SMBIOS.
DATAFILE - DataFiles [CALL]
DCOMAPP - DCOM Applications.
DESKTOP - User's Desktop
DESKTOPMONITOR - Desktop Monitor
DEVICEMEMORYADDRESS - Device memory addresses
DISKDRIVE - Physical disk drive
DISKQUOTA - Disk space usage for NTFS volumes.[SET]
DMACHANNEL - Direct memory access (DMA) channel
ENVIRONMENT - System environment settings [SET]
FSDIR - Filesystem directory entry [CALL]
GROUP - Group account [CALL]
IDECONTROLLER - IDE Controller
IRQ - Interrupt request line
JOB - Jobs scheduled using the schedule service.[CALL]
LOADORDER - System services that define execution dependencies.
LOGICALDISK - Local storage devices [CALL/SET]
LOGON - LOGON Sessions.
MEMCACHE - Cache memory
MEMLOGICAL - System memory, layout and availability
MEMPHYSICAL - Physical memory management
NETCLIENT - Network Client management.
NETLOGIN - Network login information for a particular user.
NETPROTOCOL - Protocols (and their network characteristics).
NETUSE - Active network connection.
NIC - Network Interface Controller (NIC)
NICCONFIG - Network adapter. [CALL]
NTDOMAIN - NT Domain. [SET]
NTEVENT - NT Event Log.
NTEVENTLOG - NT eventlog file [CALL/SET]
ONBOARDDEVICE - Common adapter devices built into the motherboard.
OS - Operating System/s [CALL/SET]
PAGEFILE - Virtual memory file swapping
PAGEFILESET - Page file settings [SET]
PARTITION - Partitioned areas of a physical disk.
PORT - I/O ports
PORTCONNECTOR - Physical connection ports
PRINTER - Printer device [CALL/SET]
PRINTERCONFIG - Printer device configuration
PRINTJOB - Print job [CALL]
PROCESS - Processes [CALL]*
PRODUCT - Windows Installer [CALL]
QFE - Quick Fix Engineering (patches)
QUOTASETTING - Setting information for disk quotas on a volume. [SET]
REGISTRY - Computer system registry [SET]
SCSICONTROLLER - SCSI Controller [CALL]
SERVER - Server information
SERVICE - Service application [CALL]
SHARE - Shared resourcees [CALL]
SOFTWAREELEMENT - Elements of a software product*
SOFTWAREFEATURE - Subsets of SoftwareElement. [CALL]*
SOUNDDEV - Sound Devices
STARTUP - Commands that run automatically when users logon
SYSACCOUNT - System account
SYSDRIVER - System driver for a base service. [CALL]
SYSTEMENCLOSURE - Physical system enclosure
SYSTEMSLOT - Physical connection points including ports,
slots and peripherals, and proprietary connections points.
TAPEDRIVE - Tape drives
TEMPERATURE - Temperature sensor (electronic thermometer).
TIMEZONE - Time zone data
UPS - Uninterruptible power supply (UPS)
USERACCOUNT - User accounts [CALL/SET]
VOLTAGE - Voltage sensor (electronic voltmeter) data
VOLUME - Local storage volume [CALL/SET]
VOLUMEQUOTASETTING - Associates the disk quota setting with a specific disk volume. [SET]
WMISET - WMI service operational parameters [SET]
New aliases in Windows 2003:
MEMORYCHIP - Memory chip information.
RDACCOUNT - Remote Desktop connection permission [CALL]
RDNIC - Remote Desktop connection on a specific network adapter [CALL/SET]
RDPERMISSIONS - Permissions to a specific Remote Desktop connection [CALL]
RDTOGGLE - Turn Remote Desktop listener on or off remotely[CALL]
RECOVEROS - Blue Screen Information [SET]
SHADOWCOPY - Shadow copy management [CALL]
SHADOWSTORAGE - Shadow copy storage areas [CALL/SET]
VOLUMEUSERQUOTA - Per user storage volume quotas [SET]
Options
By default an alias will return a standard LIST of information, you can also choose to GET one or more specific properties.
Configuration changes can be made, where indicated above with: [CALL or SET ]
The CREATE and DELETE options allow you to change the WMI schema itself.
alias
alias LIST [BRIEF | FULL | INSTANCE | STATUS |SYSTEM | WRITEABLE]
[/TRANSLATE:BasicXml|NoComma ]
[/EVERY:no_secs] [/FORMAT:format]
alias GET [property list]
[/VALUE ] [/ALL ] [/TRANSLATE:BasicXml|NoComma ]
[/EVERY:no_secs] [/FORMAT:format]
alias CALL method_name [parameters]
alias SET [assignments]
alias CREATE
alias DELETE
alias ASSOC [/RESULTCLASS:classname] [/RESULTROLE:rolename][/ASSOCCLASS:assocclass]
For more help
WMIC /locale:ms_409 /alias /?
WMIC /locale:ms_409 /alias option /?
e.g.
WMIC /locale:ms_409 /BIOS /CALL /?
WMIC /locale:ms_409 /MEMLOGICAL /SET /?
The order of the /FORMAT and /TRANSLATE switches is significant: if /TRANSLATE follows /FORMAT, the output is formatted first and then translated.
All the options above can be extended with a WHERE clause, best shown by the examples below:
Format:
Format defines the layout of the information, XML output is automatically formatted using a default style sheet, while other formats (HTML, Table, MOF, Raw XML etc) can be specified using /FORMAT: stylesheet_name
Stylesheets supplied with WMIC:
csv.xsl, hform.xsl, htable-sortby.xsl, htable.xsl
texttable.xsl, textvaluelist.xsl, xml.xsl
All output files are unicode text (convert to ASCII with TYPE) Tab Separated Values (.tsv) can be opened in excel
The PROCESS alias can be used to start a new installation process, if doing this across the network, place the installer files on a share with permissions EVERYONE : Read Only. This is because network credentials will be dropped when jumping from one remote machine to another (unless you have kerberos configured).
Examples
WMIC /locale:ms_409 OS
WMIC OS LIST BRIEF
WMIC OS GET csname, locale, bootdevice
WMIC OS GET osarchitecture /value
WMIC /locale:ms_409 NTEVENT where LogFile='system'
WMIC NTEVENT where "LogFile='system' and Type>'0'"
WMIC SERVICE where (state=”running”) GET caption, name, state > services.tsv
WMIC SERVICE where caption='TELNET' CALL STARTSERVICE
WMIC PRINTER LIST STATUS
WMIC PRINTER where PortName="LPT1:" GET PortName, Name, ShareName
WMIC /INTERACTIVE:ON PRINTER where PortName="LPT1:" DELETE
WMIC PROCESS where name='evil.exe' delete
WMIC /output:"%computername%.txt" MEMORYCHIP where "memory" get Capacity
WMIC /node:@workstns.txt /failfast:on PROCESS call create "\\server\share\installer.cmd"
Interactive mode:
C:>START "Windows Management" WMIC
wmic:root\cli>/locale:ms_409
wmic:root\cli>OS get csname
wmic:root\cli>quit
Notes
WMIC is available on XP Professional and Windows 2003 or later versions of Windows.
The availability of WMI information does vary across different versions of Windows
e.g. ODBC, SNMP, Windows Installer.
To run WMIC requires administrator rights.
In Windows 2000, around 4,000 properties can be monitored, and around 40 can be configured.
In Windows XP around 6,000 properties can be monitored, and around 140 can be configured.
Windows 2003 offers a few improvements and bug fixes: the global option /locale:ms_409 is not required (it defaults to English US.)
When you type WMIC for the first time in Windows 2003 all the aliases are compiled. The second, and subsequent times you run WMIC, it will start immediately. Under XP WMIC is slower to initialise, therefore to run several WMI queries it can be quicker to use interactive mode.
* WMI information for installed software packages (PACKAGE and SOFTWAREFEATURE) is often incomplete and inconsistent for a variety of historical reasons. A more reliable method is to retrieve a list of installed programs directly from the Add/Remove list in the registry, with a WSH script like this from Torgeir Bakken.
“Life is like a game of cards. The hand you are dealt is determinism; the way you play it is free will” - Jawaharial Nehru
Related:
SYSTEMINFO List system configuration
The Grammar of WMIC - ISC
Get-WMIobject - Get WMI class information (Powershell)
MOF (Managed Object Format) - A language that describes management information.
Q824223 - WMIC command runs slowly with /FAILFAST switch.
Q875605 - Troubleshoot WMI-related issues
Sample commands - Windows 2003
MSDN full WMI reference - Classes, providers etc
WUAUCLT Windows Update Agent, download new Windows Update files.
Syntax
wuauclt Options
Options:
/a or /ResetAuthorization Initiate an asynchronous background search for applicable updates.
If Automatic Updates are disabled, this has no effect.
/r or /ReportNow Send all queued reporting events to the server asynchronously.
/DetectNow Initiate detection right away, Query the WSUS server immediately
to see if any new updates are needed.
WSUS uses a cookie on client computers to store computer group membership when client-side targeting is used. By default this cookie expires an hour after WSUS creates it. If you are using client-side targeting and change group membership, use /ResetAuthorization /detectnow to expire the cookie, initiate detection, and have WSUS update computer group membership.
Examples:
C:\> wuauclt /a /DetectNow
C:\> wuauclt /r /DetectNow
“We must always change, renew, rejuvenate ourselves; otherwise we harden” - Johann Wolfgang von Goethe
Related:
wuauserv - The Windows Update Service
%systemroot%\WindowsUpdate.log
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate
XCACLS.exe (Resource Kit)
Display or modify Access Control Lists (ACLs) for files and folders.
Syntax
XCACLS filename [options]
XCACLS filename
Key
If no options are specified XCACLS will display the ACLs for the file(s)
options can be any combination of:
/T Traverse all subfolders and change all matching files found.
/E Edit ACL instead of replacing it.
/x Edit ACL instead of replacing it; affect only ACEs that this user already owns*
/R user Revoke all access rights from the given user.
/D user Deny specified user access, this will over-ride
all other permissions the user has.
/C Continue on access denied errors.
/Y Replace user's rights without verify
/P user:permision[;FolderSpec]
Replace user's rights. see /G option below
/G user:permision[;FolderSpec]
Grant specified user access rights, permision can be:
r Read
c Change (write)
f Full control
p Change Permissions (Special access)
o Take Ownership (Special access)
x EXecute (Special access)
e REad (Special access)
w Write (Special access)
d Delete (Special access)
t Used only by FolderSpec. see below
* Option only valid in Windows 2003
FolderSpec is a permission applied to a folder. If FolderSpec is not specified then permission will apply to both files and folders.
This allows you to set different permissions that will apply (through inheritance) when new files are added to the folder.
FolderSpec = ;T@ where @ is one of the rights above, when this is specified new files will inherit FolderSpec instead of permission. At least one folder access right must follow the T For example ;TF will apply full control (but ;FT is not valid)
Wildcards can be used to specify more that one file in a command. You can specify more than one user in a command. You can combine access rights.
Although taking ownership is listed as an option it does not work, use SUBINACL for this.
Inheritance Errors
"Permissions incorrectly ordered" - the quickest way to resolve or avoid these errors is to use the newer iCACLS command instead of XCACLS.
Inherited folder permissions are displayed as:
OI - Object inherit - This folder and files. (no inheritance to subfolders)
CI - Container inherit - This folder and subfolders.
IO - Inherit only - The ACE does not apply to the current file/directory
These can be combined as folllows:
(OI)(CI) This folder, subfolders, and files.
(OI)(CI)(IO) Subfolders and files only.
(CI)(IO) Subfolders only.
(OI) (IO) Files only.
So BUILTIN\Administrators:(OI)(CI)F means that both files and Subdirectories will inherit 'F' (Fullcontrol)
similarly (CI)R means Directories will inherit 'R' (Read folders only = List permission)
When xcacls is applied to the current folder only there is no inheritance and so no output.
Versions:
NTFS standards have changed with different versions of Windows and XCACLS has been updated to suit, early versions of Xcacls may give unpredictable results against an NTFS v5 partition.
xcacls.vbs is described in Q825751 and can be downloaded here - xcacls.vbs is an unsupported utility that addresses a limitation with the original xcacls.exe, specifically the inability to append permissions to a folder whose child objects have the inheritance flag set. The .vbs version does not suppport unc paths and is very slow to update multiple ACLs.
Examples:
:: Allow guests the right to read and execute in MyFolder
XCACLS MyFolder /E /G guests:rx
:: Allow guests the Full Control permission in MyFolder and all subfolders
XCACLS MyFolder /T /E /G guests:f
:: Grant guests only read access to all files in and below MyFolder,
:: new folders created will be Read Access only, new files will not inherit any rights.
XCACLS MyFolder /T /P guests:R;Tr
:: Grant guests only execute access to all files in and below MyFolder
XCACLS MyFolder /T /P guests:x
“I spent most of the eighties, most of my life, riding around in somebody else's car, in possession of, or ingested of, something illegal, on my way from something illegal to something illegal with many illegal things happening all around me” - Iggy Pop
Related:
CACLS - Change file and folder permissions (ACLs)
iCACLS - Change file and folder permissions (ACLs)
SUBINACL - Edit file and folder Permissions, Ownership and/or Domain
DIR /Q - Display the owner for a list of files (try it for Program files)
AccessEnum - GUI to browse a tree view of user privs
NTRIGHTS - Edit user account rights
PERMS - Show permissions for a user
SHOWACL - Show file Access Control Lists (win 2000)
SHOWACCS - Show ACLs on the registry, file system, file and print shares
SUBINACL - Change an ACL's user/domain
ATTRIB - Display or change file attributes
Permissions & Local/Global Workgroups
Permissions explained - Microsoft.com
Access-based Enumeration - Set file listing to only display files you can read (Win 2003)
Q318754 - How to use Xcacls (includes download)
Q245031 - Change Registry Permissions from the command line
Q822790 - Xcacls /E - Objects do not inherit permissions as expected.
ACL utils: SetAcl or FileACL
Powershell: Set-Acl - Set permissions
Equivalent bash command (Linux):chmod - Change access permissions, chown - Change file owner and group
XCOPY Copy files and/or directory trees to another folder. XCOPY is similar to the COPY command except that it has additional switches to specify both the source and destination in detail.
NOTE: Xcopy is now deprecated under Vista and Windows 2008 - use Robocopy instead
XCOPY is particularly useful when copying files from CDROM to a hard drive, as it will automatically remove the read-only attribute.
Syntax
XCOPY source [destination] [options]
Key
source : Pathname for the file(s) to be copied.
destination : Pathname for the new file(s).
[options] can be any combination of the following:
Source Options
/A Copy files with the archive attribute set (default=Y)
/M Copy files with the archive attribute set and
turn off the archive attribute, use this option
when making regular Backups (default=Y)
/H Copy hidden and system files and folders (default=N)
/D:mm-dd-yyyy
Copy files changed on or after the specified date.
If no date is given, copy only files whose
source date/time is newer than the destination time.
/U Copy only files that already exist in destination.
/S Copy folders and subfolders
/E Copy folders and subfolders, including Empty folders.
May be used to modify /T.
/EXCLUDE:file1[+file2][+file3]...
(Windows 2000 only) The files can each contain one
or more full or partial pathnames to be excluded.
When any of these match any part of the absolute path
of a SOURCE file, then that file will be excluded.
For example, specifying a string like \obj\ or .obj will exclude
all files underneath the directory obj or all files with the
.obj extension respectively.
Copy Options
/W Prompt you to press a key before starting to copy.
/P Prompt before creating each file.
/Y (Windows 2000 only) Suppress prompt to confirm overwriting a file.
may be preset in the COPYCMD env variable.
/-Y (Windows 2000 only) Prompt to confirm overwriting a file.
/V Verify that the new files were written correctly.
/C Continue copying even if an error occurs.
/I If in doubt always assume the destination is a folder
e.g. when the destination does not exist.
/Z Copy files in restartable mode. If the copy is interrupted part
way through, it will restart if possible. (use on slow networks)
/Q Do not display file names while copying.
/F Display full source and destination file names while copying.
/L List only - Display files that would be copied.
Destination Options
/R Overwrite read-only files.
/T Create folder structure, but do not copy files. Do not
include empty folders or subfolders.
/T /E will include empty folders and subfolders.
/K Copy attributes. XCOPY will otherwise reset read-only attributes.
/N If at all possible, use only a short filename (8.3) when creating
a destination file. This may be necessary when copying between disks
that are formatted differently e.g NTFS and VFAT, or when archiving
data to an ISO9660 CDROM.
/O (Windows 2000 only) copy file Ownership and ACL information.
/X Copy file audit settings (implies /O).
XCOPY will accept UNC pathnames
Examples:
To copy a file:
XCOPY C:\utils\MyFile D:\Backup\CopyFile
To copy a folder:
XCOPY C:\utils D:\Backup\utils /i
To copy a folder including all subfolders.
XCOPY C:\utils\* D:\Backup\utils /s /i
The /i defines the destination as a folder.
Notes
In many cases the functionality of XCOPY is superseded by ROBOCOPY.
To force the overwriting of destination files under both NT4 and Windows2000 use the COPYCMD environment variable:
SET COPYCMD=/Y
This will turn off the prompt in Win2000 and will be ignored by NT4 (which overwrites by default).
When comparing Dates/Times the granularity (the finest increment of the timestamp) is 2 seconds for a FAT volume and 0.1 microsecond for an NTFS volume.
The WinXP version of XCOPY will accept wildcards for the source e.g. *.txt
It is also more forgiving with trailing backslashes
"It is easier to copy than to think, hence fashion" - Wallace Stevens
Related:
COPY - Copy one or more files to another location
DEL - Delete files
MOVE - Move a file from one folder to another
ROBOCOPY - Robust File and Folder Copy
Fcopy - File Copy for MMQ (copy changed files & compress. (Win 2K ResKit)
Permcopy - Copy share & file ACLs from one share to another. (Win 2K ResKit)
MTC - XCopy and create a log file. (Win 2K ResKit)
Q240268 - XCOPY changes in Win 2K
PowerShell: Copy-Item - Copy an item from one location to another
Equivalent bash command (Linux): cp - Copy one or more files to another location