cac lenh trong run

348
An A-Z Index of the Windows NT/XP command line ADDUSERS Add or list users to/from a CSV file ARP Address Resolution Protocol ASSOC Change file extension associations ASSOCIAT One step file association AT Schedule a command to run at a later time ATTRIB Change file attributes BOOTCFG Edit Windows boot settings BROWSTAT Get domain, browser and PDC info 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 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 CSVDE Import or Export Active Directory data DATE Display or set the date Dcomcnfg DCOM Configuration Utility DEFRAG Defragment hard drive DEL Delete one or more files

Upload: vanlydochanh

Post on 12-Nov-2014

2.666 views

Category:

Documents


6 download

TRANSCRIPT

An A-Z Index of the Windows NT/XP command line

ADDUSERS Add or list users to/from a CSV fileARP Address Resolution ProtocolASSOC Change file extension associationsASSOCIAT One step file associationAT Schedule a command to run at a later timeATTRIB Change file attributes

BOOTCFG Edit Windows boot settingsBROWSTAT Get domain, browser and PDC info

CACLS Change file permissionsCALL Call one batch program from anotherCD Change Directory - move to a specific FolderCHANGE Change Terminal Server Session propertiesCHKDSK Check Disk - check and repair disk problemsCHKNTFS Check the NTFS file systemCHOICE Accept keyboard input to a batch fileCIPHER Encrypt or Decrypt files/foldersCleanMgr Automated cleanup of Temp files, recycle binCLEARMEM Clear memory leaksCLIP Copy STDIN to the Windows clipboard.CLS Clear the screenCLUSTER Windows ClusteringCMD Start a new CMD shellCOLOR Change colors of the CMD windowCOMP Compare the contents of two files or sets of filesCOMPACT Compress files or folders on an NTFS partitionCOMPRESS Compress individual files on an NTFS partitionCON2PRT Connect or disconnect a PrinterCONVERT Convert a FAT drive to NTFS.COPY Copy one or more files to another locationCSVDE Import or Export Active Directory data

DATE Display or set the dateDcomcnfg DCOM Configuration UtilityDEFRAG Defragment hard driveDEL Delete one or more filesDELPROF Delete NT user profilesDELTREE Delete a folder and all subfoldersDevCon Device Manager Command Line Utility DIR Display a list of files and foldersDIRUSE Display disk usageDISKCOMP Compare the contents of two floppy disksDISKCOPY Copy the contents of one floppy disk to anotherDNSSTAT DNS StatisticsDOSKEY Edit command line, recall commands, and create macros

DSADD Add user (computer, group..) to active directoryDSQUERY List items in active directoryDSMOD Modify user (computer, group..) in active directory

ECHO Display message on screenENDLOCAL End localisation of environment changes in a batch fileERASE Delete one or more filesEXIT Quit the CMD shellEXPAND Uncompress filesEXTRACT Uncompress CAB files

FC Compare two filesFDISK Disk Format and partitionFIND Search for a text string in a fileFINDSTR Search for strings in filesFOR /F Loop command: against a set of filesFOR /F Loop command: against the results of another commandFOR Loop command: all options Files, Directory, ListFORFILES Batch process multiple filesFORMAT Format a diskFREEDISK Check free disk space (in bytes)FSUTIL File and Volume utilitiesFTP File Transfer ProtocolFTYPE Display or modify file types used in file extension associations

GLOBAL Display membership of global groupsGOTO Direct a batch program to jump to a labelled line

HELP Online HelpHFNETCHK Network Security Hotfix Checker

IF Conditionally perform a commandIFMEMBER Is the current user in an NT WorkgroupIPCONFIG Configure IP

KILL Remove a program from memory

LABEL Edit a disk labelLOCAL Display membership of local groupsLOGEVENT Write text to the NT event viewer.LOGOFF Log a user offLOGTIME Log the date and time in a file

MAPISEND Send email from the command lineMEM Display memory usageMD Create new foldersMODE Configure a system device

MORE Display output, one screen at a timeMOUNTVOL Manage a volume mount pointMOVE Move files from one folder to anotherMOVEUSER Move a user from one domain to anotherMSG Send a messageMSIEXEC Microsoft Windows InstallerMSINFO Windows NT diagnosticsMSTSC Terminal Server Connection (Remote Desktop Protocol)MUNGE Find and Replace text within file(s)MV Copy in-use files

NET Manage network resourcesNETDOM Domain ManagerNETSH Configure network protocolsNETSVC Command-line Service ControllerNBTSTAT Display networking statistics (NetBIOS over TCP/IP)NETSTAT Display networking statistics (TCP/IP)NOW Display the current Date and Time NSLOOKUP Name server lookupNTBACKUP Backup folders to tapeNTRIGHTS Edit user account rights

PATH Display or set a search path for executable filesPATHPING Trace route plus network latency and packet lossPAUSE Suspend processing of a batch file and display a messagePERMS Show permissions for a userPERFMON Performance MonitorPING Test a network connectionPOPD Restore the previous value of the current directory saved by PUSHDPORTQRY Display the status of ports and servicesPRINT Print a text filePRNCNFG Display, configure or rename a printerPRNMNGR Add, delete, list printers set the default printerPROMPT Change the command promptPsExec Execute process remotelyPsFile Show files opened remotelyPsGetSid Display the SID of a computer or a userPsInfo List information about a systemPsKill Kill processes by name or process IDPsList List detailed information about processesPsLoggedOn Who's logged on (locally or via resource sharing)PsLogList Event log recordsPsPasswd Change account passwordPsService View and control servicesPsShutdown Shutdown or reboot a computerPsSuspend Suspend processesPUSHD Save and then change the current directory

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

RASDIAL Manage RAS connectionsRASPHONE Manage RAS connectionsRECOVER Recover a damaged file from a defective disk.REG Read, Set or Delete registry keys and valuesREGEDIT Import or export registry settingsREGSVR32 Register or unregister a DLLREGINI Change Registry PermissionsREM Record comments (remarks) in a batch fileREN Rename a file or files.REPLACE Replace or update one file with anotherRD Delete folder(s)RDISK Create a Recovery DiskRMTSHARE Share a folder or a printerROBOCOPY Robust File and Folder CopyROUTE Manipulate network routing tablesRUNAS Execute a program under a different user accountRUNDLL32 Run a DLL command (add/remove print connections)

SC Service ControlSCHTASKS Create or Edit Scheduled Tasks SCLIST Display NT ServicesScriptIt Control GUI applicationsSET Display, set, or remove environment variablesSETLOCAL Control the visibility of environment variablesSETX Set environment variables permanently SHARE List or edit a file share or print shareSHIFT Shift the position of replaceable parameters in a batch fileSHORTCUT Create a windows shortcut (.LNK file)SHOWGRPS List the NT Workgroups a user has joinedSHOWMBRS List the Users who are members of a WorkgroupSHUTDOWN Shutdown the computerSLEEP Wait for x secondsSOON Schedule a command to run in the near futureSORT Sort inputSTART Start a separate window to run a specified program or commandSU Switch UserSUBINACL Edit file and folder Permissions, Ownership and DomainSUBST Associate a path with a drive letterSYSTEMINFO List system configuration

TASKLIST List running applications and servicesTIME Display or set the system timeTIMEOUT Delay processing of a batch file

TITLE Set the window title for a CMD.EXE sessionTOUCH Change file timestamps TRACERT Trace route to a remote hostTREE Graphical display of folder structureTYPE Display the contents of a text file

USRSTAT List domain usernames and last login

VER Display version informationVERIFY Verify that files have been savedVOL Display a disk label

WHERE Locate and display files in a directory treeWHOAMI Output the current UserName and domainWINDIFF Compare the contents of two files or sets of filesWINMSD Windows system diagnosticsWINMSDP Windows system diagnostics IIWMIC WMI Commands

XCACLS Change file permissionsXCOPY Copy files and folders

Microsoft Help pages: Windows XP - 2003 Server

Links to other Sites, books etc...

ADDUSERS.exe (Resource Kit)

ADDUSERS - Automate the creation of a large number of users

Syntax

Create Users: AddUsers /c filename [/s:x] [/?] Domain Password_options Dump to file: AddUsers /d{:u} filename [/s:x] [/?] Domain Password_options Erase Users: AddUsers /e filename [/s:x] [/?] Domain Password_optionskey

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.ExampleCreate 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, Scripte.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 commandAddUsers MyDomain /c c:\Users.txt /p:eRelated Commands:

Q199878 - further examples of ADDUSERSDSADD - Add user (computer, group..) in active directoryCSVDE - Import and export from Active Directory.

Equivalent Linux BASH commands:

useradd - Create new user accounts

ARP.exe

ARP - Address Resolution Protocol

Display and modify the 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.ExamplesDisplay the ARP cache tables for all interfaces:arp -aDisplay the ARP cache table for the interface on IP address 10.1.4.99:arp -a -N 10.1.4.99Add a static ARP cache entry on IP addr 10.1.4.77 to the physical address 00-AA-21-4A-2F-9A:arp -s 10.1.4.77 00-AA-21-4A-2F-9A"One resolution I have made, and try always to keep, is this: To rise above little things" - John Burroughs

Related Commands:

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

ASSOC

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

Syntax ASSOC .ext = [fileType] ASSOC ASSOC .ext ASSOC .ext =

Key .ext : The file extension fileType : The type of file A file extension is the last few characters in a FileName after the period. So a file called JANUARY.HTML has the file extension .HTML

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

More than one file extension may be associated with the same File Type.e.g. both the extension .JPG and the extension .JPEG may be associated with the File Type "jpegfile"

At any one time a given file extension may only be associated with one File Type.e.g. If you change the extension .JPG so it is associated with the File Type "txtfile" then it's normal association with "jpegfile" will disappear. Removing the association to "txtfile" does not restore the association to "jpegfile"

File Types can be displayed in the Windows Explorer GUI: [View, Options, File Types] however the spelling is usually different to that expected by the ASSOC command e.g. the File Type "txtfile" is displayed in the GUI as "Text Document"and "jpegfile" is displayed as "image/jpeg"

The command ASSOC followed by just a file extension will display the current File Type for that extension.

ASSOC without any parameters will display all the current file associations.

ASSOC with ".ext=" will delete the association for that file extension.Did you leave the Always Use This Program To Open This File option turned on? To change it back so it prompts you to specify a program each time, just delete the association for that file typeASSOC .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 .txtASSOC .docASSOC >backup.txt

Editing file associations:

ASSOC .txt=txtfileASSOC .DIC=txtfileASSOC .html=Htmlfile

Deleting a file association:

ASSOC .html=Repair .REG and .EXE file associations:ASSOC .EXE=exefileASSOC .REG=regfileDigging 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 extensionASSOCIAT - One step file association (Resource Kit)Q162059 - Associate Internet Explorer with MS Office filesJSIFAQ - Tip 9715 - List File Types with executable path

ASSOCIATE.exe (Resource Kit)

One step file association.

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

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

Key .ext : Extension to be associated. filename : Executable program to associate .ext with. /q : Quiet - Suppress interactive prompts. /f : Force - Force overwrite or delete without questions. /d : Delete - Delete the association.A file extension is the last few characters in a FileName after the period. So a file called JANUARY.HTML has the file extension .HTML

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

Example: adding a File Association

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

ASSOCIATE .SQL Notepad.exe

Example: Removing a File Association

ASSOCIATE .SQL /d

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

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

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

Related Commands:

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

Equivalent Linux BASH commands:

export - Set an environment variable

AT.exe

Schedule a batch file to run on a computer at a specific date and time. This command is available for backwards compatibility with NT 4 but has been superseded by SCHTASKS.

Syntax Create an AT job: AT [\\computername] hh:mm [/INTERACTIVE] [ /EVERY:day(s) | /NEXT:day(s) ] "command"

Delete an AT job: AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]]

Key \\computername : Execute the AT command on a remote computer.

id : An id number AT assigns to each scheduled job.

/delete : Cancel a scheduled job. If id is omitted, all jobs are deleted.

/yes : Use with /delete to supress the confirmation message.

hh:mm : The time to run the command.

/interactive : Allow the job to interact with the desktop of the current user when the job runs.

/every:day(s) : Run the command every day(s) of the week or month. (default: dd=today)

/next:day(s) : Run the command on the next occurrence of the day. (default: dd=today)

"command" : The batch program or command to run. If the path to this includes spaces, put double quotation marks around the path. "C:\Program Files\My Batch.cmd"Day(s) are in this format: (English Locale EN)

Monday = mTuesday = tWednesday = wThursday = thFriday = fSaturday = sSunday = su

or a specific day of the month: e.g. 5th of every month = 5

Examples:

Running a command every dayAT_DAILY.cmd::::::::::::AT 23:30 /EVERY:m,t,w,th,f,s,su c:\backups\every_day.cmd::::::::::::

Running a command every FridayAT_WEEKLY.cmd::::::::::::AT 23:30 /EVERY:f c:\backups\weekly.cmd::::::::::::

Resetting the above AT commandsRESET_AT_JOBS.cmd::::::::::::AT /delete /yesCALL AT_DAILY CALL AT_WEEKLY::::::::::::

Running a command this evening (once only)AT_TODAY.cmd::::::::::::AT 23:30 /NEXT: c:\backups\today.cmd::::::::::::

Rights needed to issue an AT command

By default only a Local Administrator can issue an AT command, a Domain Admin can direct the command at any machine.

To configure an AT job as part of a users login script - the user must be a member of the local Administrators group.Schedule vs Task Sheduler

The "Schedule" service must be running to use the AT command. If you have Internet Explorer 5.0 or greater this is renamed as the "Task Scheduler" service. Task Scheduler initially had a bad reputation due to a security vulnerability it introduced - however this was fixed with IE 5.01

The "Schedule" service (ATSVC) rather than the "Task Scheduler" service must be running to use SOON with a delay of less than 60 seconds. - see Q237840 You can use the Scheduled Tasks folder to view or modify the settings of a task that was created by using the AT command. When you schedule a task using the at command, the task is listed in the Scheduled Tasks folder, with a name such as:At3478. However, if you modify an AT task through the Scheduled Tasks folder, it is upgraded to a normal scheduled task. The task is no longer visible to the at command, and the at account setting no longer applies to it. You must explicitly enter a user account and password for the task.

Commands to ProcessAt does not automatically load Cmd.exe, the command interpreter. If you are not running an executable (.exe) file, you must explicitly load Cmd.exe at the beginning of the command e.g. cmd /c dir Don't try to pass more than one command into AT, put everything you want to achieve in one batch file and then call the batch file from AT.User Rights needed for the AT command to perform it's task

The User Account under which the Schedule service runs may require specific file access permissions, user permissions and drive mappings.

The User Account is selected under MyComputer, ScheduledTasks, Advanced (Menu), AT Service Account. You also need to stop and restart the service before the change in UserAccount will take effect.

Here's how to check if a user account has sufficent rights for a particular task:

AT hh:mm /interactive %comspec% /k

Setting hh:mm for one minute from now will open a cmd window at the specified time. In this window you can check the following settings:

The PATH Environment variables (particularly TEMP). Drive mappings - you can add these by putting appropriate NET USE...

commands at the beginning of your batch file.

Next, go ahead and run your batch file in this console window, note the errors, and fix them. Once the errors have been fixed, you can remove the /interactive switch and schedule the batch file with some confidence that it will work as intended.

Bugs

If you change the system time after scheduling a command with AT, synchronize the scheduler with the revised system time by typing AT without any command-line options.By default, AT jobs will stop running after 72 hours. You can modify this in the registry.HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ScheduleAdd Value:AtTaskMaxHours Data type: REG_DWORD Decimal Value Data: 0. A value of 0 indicates no limit, does not stop. Values from 1 through 99 indicate the number of hours.See Q226370 for bugs related to the Task Scheduler under NT4. Other Task Scheduler options are stored in the registryHKLM\SOFTWARE\Microsoft\SchedulingAgent\"We don't wake up for less than $10,000 a day" - Linda Evangelista

Related commands:

SOON - Schedule a command to run in the near future CALL - Call one batch program from another.JT - Win 2000 Task Scheduler Command Line UtilitySchTasks - Task Scheduler WMIC JOB - WMI access to scheduled tasks. Scheduling Windows 2000’s Disk Defragmenter

Equivalent Linux BASH commands:

cron - Daemon to execute scheduled commandscrontab - Schedule a command to run at a later timewatch - Execute/display a program periodically

ATTRIB.exe

Display or change file attributes. Find Filenames.

Syntax ATTRIB [ + attribute | - attribute ] [pathname] [/S]

Key + : Turn an attribute ON

- : Clear an attribute OFF

pathname : Drive and/or filename e.g. C:\*.txt /S : Search the pathname including all subfolders.

attributes: H Hidden S System R Read-only A ArchiveIf no attributes are specified attrib will return the current attribute settings. Used with just the /S option ATTRIB will quickly search for a particular filename.

Combining the Hidden and System attributes.

If a file has both the Hidden and System attributes set, you can clear both attributes only with a single ATTRIB command.

For example, to clear the Hidden and System attributes for the RECORD.TXT file, you would type: ATTRIB -S -H RECORD.TXT

Using ATTRIB with groups of files

You can use wildcards (? and *) with the filename parameter to display or change the attributes for a group of files.

Remember that, if a file has the System or Hidden attribute set, you must clear that attribute before you can change any other attributes.

Changing the attributes for a directory

You can display or change the attributes for a directory. To use ATTRIB with a directory, you must explicitly specify the directory name; you cannot use wildcards to work with directories.

For example, to hide the directory C:\SECRET, you would type the following:

ATTRIB +H C:\SECRET

The following command would affect only files, not directories: ATTRIB +H C:*.*

Viewing archive attributes

The Archive attribute (A) is used to mark files that have changed since they were previously backed up. The (A) flag is automatically updated by Windows as the file is saved.

If the (A) flag is present - the file is new or has been changed since the last backup.

The MSBACKUP, RESTORE, and XCOPY commands use these Archive attributes, as do many (but not all) 3rd party backup solutions.New attributes in Windows XPIn addition to A,H,R,S, the latest version of NTFS includes the following new attributesE = Encrypted, C = Compressed, T = Temporary, O = Offline"The moral sense of conscience is by far the most important..it is the most noble of all the attributes of man" - Charles Darwin

Related Commands:

CACLS - Change file permissions

Equivalent Linux BASH commands:

chflags - Change a file or folder's flags.chmod - Change access permissionschown - Change file owner and group

BOOTCFG.exe

Edit the Windows boot settings stored in Boot.ini

Syntax BOOTCFG /addsw Add OS load options for an OS entry in boot.ini

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 = /FastdetectLoad 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 FixbootThe 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 sectorQ291980 - The XP Bootcfg commandQ317521 - The 2003 Bootcfg commandRecovery console

BROWSTAT.exe (Resource Kit)

Get domain, browser and PDC info.

Syntax BROWSTAT sta : Status Displays Transport,Primary DNS and Backup DNS servers.

BROWSTAT sta -v domain : Status Display (Verbose) includes Server OS and active browsers.

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

BROWSTAT gm Transport Domain : List the remote Master Browser name (using NetBIOS) BROWSTAT gb Transport : List of backup DNS Servers BROWSTAT wfw : List WFW servers that are running browser.

BROWSTAT sts \\ServerName : Dump browser statistics

BROWSTAT TICKLE : Force remote master to stop. BROWSTAT ELECT : Force election on remote domain

The VIEW options below can enumerate all the server servicesrunning across a server or domain:

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

In the list displays, the following flags are used:

W = Workstation NT = Windows NT S = Server W95 = Windows95SQL = SQLServer WFW = WindowsForWorkgroupsSS = StandardServer MFPN= MS NetwarePDC = PrimaryDomainController NV = NovellBDC = BackupDomainController XN = Xenix

TS=TimeSourceMBC=MemberServerPQ=PrintServerDL=DialinServerAFP=AFPServerOSF=OSFServerVMS=VMSServer

PBR=PotentialBrowserBBR=BackupBrowser,MBR=MasterBrowserDMB=DomainMasterBrowserDFS=DistributedFileSystemA mission statement is defined as "a long awkward sentence that demonstrates management's inability to think clearly." All good companies have one. - Scott Adams The Dilbert Principle, 1996

Related Commands:

Q188305 - Troubleshooting the Browser Service

DNSSTAT - DNS StatisticsNETSTAT - Display networking statistics (TCP/IP) SETPRFDC - Set preferred Domain Controller

CACLS.exe

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

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

Syntax CACLS pathname [options]

Key options can be any combination of:

/T Search the pathname including all subfolders. /E Edit ACL (leave existing rights unchanged) /C Continue on access denied errors.

/G user:permission Grant access rights, permision can be: R Read W Write C Change (read/write) F Full control

/R user Revoke specified user's access rights (only valid with /E).

/P user:permission Replace access rights, permission can be: N None R Read W Write C Change (read/write) F Full control

/D user Deny access to user.

In all the options above "user" can be a UserName or a Workgroup (either local or global)

If a UserName or WGname includes spaces then it must

be surrounded with quotes e.g. "Authenticated Users"

If no options are specified CACLS will display the ACLs for the file(s)Other features to try

Wildcards can be used to specify multiple files.You can specify more than one user:permission in a single command.The /D option will deny access to a user even if they belong to a group that does have access.

Using CACLS

The CACLS command does not provide a /Y switch to automatically answer 'Y' to the Y/N prompt. However, you can pipe the 'Y' character into the CACLS command using ECHO, use the following syntax:

ECHO Y| CACLS /g <username>:<permission>

To edit a file you must have the "Change" ACL (or be the file's owner) To use the CACLS command and change an ACL requires "FULL Control" File "Ownership" will always override all ACL's - you always have Full Control

over files that you create. If CACLS is used without the /E switch all existing rights on [pathname] will be

replaced, any attempt to use the /E switch to change a [user:permission] that already exists will raise an error. To be sure the CALCS command will work without errors use /E /R to remove ACL rights for the user concerned, then use /E to add the desired rights.

The /T option will only traverse subfolders below the current directory. Windows NT 4.0 does not support the Grant Write option (CACLS

<Folder> /G <UserName>:W) grant the Change permission instead.

If no options are specified CACLS will display the current ACLse.g. To display the current folderCACLS .Display permissions for one file CACLS MyFile.txtDisplay permissions for multiple files CACLS *.txt

Inherited folder permissions are displayed as follows: OI This folder and files. (nO Inheritance to subfolders) CI This folder and subfolders. (Cascade Inherititance) IO Inherit Only (Do not apply this ACE to the current folder) No output This folder only. (OI)(CI) This folder, subfolders, and files.

(OI)(CI)(IO) Subfolders and files only. (CI)(IO) Subfolders only. (OI) (IO) Files only. Errors when changing permissionsIf 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":RAdd Full Control permission to a second group of usersCACLS myfile.txt /E /G "FinanceUsers":FNow revoke the Read permissions from the first groupCACLS myfile.txt /E /R "Power Users"

Now give the first group Full-control:CACLS myfile.txt /E /G "Power Users":FGive 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 attributesAccessEnum - GUI to browse a tree view of user privsDIR /Q - Display the owner for a list of files (try it for Program files) PERMS - Show permissions for a userFIXACLS - Restore default privs (Resource Kit supplement 2)FSUTIL - File System OptionsNTRIGHTS - Edit user account rightsSHOWACL - Show file Access Control Lists (Windows 2000)TAKEOWN - Take ownership of sharesXCACLS - Display or modify Access Control Lists (ACLs) for files and foldersQ237701 - Cacls cannot apply security to rootQ834721 - Permissions on Folder are incorrectly ordered Q135268 - How to use CACLS.EXE in a Batch FileQ245031 - Error when using the | pipe symbolNT Permissions explained

ACL utils: SuperCACLS (costs) or FileACL (free)

Equivalent Linux BASH commands:

chmod - Change access permissionschown - Change file owner and group

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 this can be a network (UNC) pathname

parameters Any command-line arguments.

:label Jump to a label in the current batch script.

internal_cmd Any internal command CALLing a command in this way (rather than simply running it) will evaluate any environment variable parametersPassing Parameters

When calling a secondary batch file or subroutine, you will often want the routine to manipulate some data, the data (usually a variable) should be passed as a parameter CALL OtherScript.cmd "1234"or CALL OtherScript.cmd %_MyVariable%

Use a label to CALL a subroutine

A label is defined by a single colon followed by a name.CALL :s_display_result 123 ECHO Done GOTO :eof:s_display_resultECHO The result is %1GOTO :eof

When you jump to a subroutine with CALL, all statements after the label are executed until either the end of the script is reached, or a GOTO :eof command.At the end of the subroutine, GOTO :eof will return to the position where you used CALL.

Example @ECHO OFF

SETLOCAL CALL :s_staff SMITH 100 GOTO s_last_bit

:s_staff ECHO Name is %1 ECHO Rate is %2 GOTO :eof

:s_last_bit ECHO The end of the scriptReturning Parameters

When a subroutine contains local variables (SETLOCAL) you will need a method of returning values, i.e. setting a variable that is passed back to the calling routine.

This is done by executing the ENDLOCAL command on the same line as a SET statement(s)

For example @ECHO OFF SETLOCAL CALL :s_calc 200 100 ECHO %_return% GOTO :eof

:s_calc SETLOCAL SET _sum=0 IF %1 GTR %2 SET _sum=5 ENDLOCAL & SET _return=%_sum% GOTO :eofThe use of SETLOCAL and ENDLOCAL is roughly equivalent to option explicit in Visual Basic, it's use is strongly recommended.You should also use SETLOCAL and ENDLOCAL when passing values from one batch file to another.

Advanced usage : CALLing internal commands

As well as running a subroutine, CALL can also be used to run any internal command (SET, ECHO etc) and cruicially will evaluate any environment variables passed on the same line. Each CALL does one substitution of the variables. (You can also do CALL CALL... for multiple substitutions)

For example

@ECHO off SETLOCAL set pc1=frodo3 set pc2=gandalf4 set pc3=ascom5 set pc4=qwerty2 set pc5=last1 ::Loop through all the PCs FOR /L %%n IN (1,1,5) DO (call :loop %%n) goto :s_next_bit :loop set _pc_name=pc%1 :: Evaluate the PC's name CALL SET _pc_name=%%%_pc_name%%% echo The pc is %_pc_name% goto :eof :s_next_bit :: continue below

:: Notice that to evaluate the contents of %pc1%:: requires triple '%' symbols i.e CALL SET _pc_name=%%%_pc_name%%%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 commands:

CMD - can be used to call a subsequent batch and ALWAYS return even if errors occur.GOTO - jump to a label or GOTO :eof START - Start a separate window to run a specified program or command

Equivalent Linux BASH commands:

. (dot operator) - Include (run) commands from another file builtin - Run a shell builtinchroot - Run a command with a different root directory

CD

Change Directory - Select a Folder (and drive)

Syntax CD [/D] [drive:][path] CD [..]

Key /D : change the current DRIVE in addition to changing folder. Examples To change to the parent directory. CD .. To change to the grant-parent directory. CD ..\.. To change to the ROOT directory. CD \ To display the current directory in the specified drive. Type CD <drive>: To display the current drive and directory. CD Moving down the folder tree with a full path reference to the ROOT folder... C:\winnt> CD \winnt\java C:\winnt\java> Moving down the folder tree with a reference RELATIVE to the current folder... C:\winnt> CD java C:\winnt\java> Moving up and down the folder tree in one command... C:\winnt\java> CD ..\system32 C:\winnt\system32>

If Command Extensions are enabled the CD command is enhanced as follows:

1) The current directory string is converted to use the correct CASE. So CD C:\wiNnt would actually set the current directory to C:\Winnt

2) CD does not treat spaces as delimiters, so it is possible to CD into a subfolder name

that contains a space without surrounding the name with quotes.

For example: cd \My folder

is the same as: cd "\My folder" 3)An asterisk can be used to complete a folder namee.g. from C:\

CD pro* will move toC:\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:00000009Changing 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 switchC:> cd /D E:\utilsE:\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. KennedyRelated commands:

You can also change directory using the pushd commandQ156276 - Cmd does not support UNC names as the current directory JSIFaq Tip 4757 - cd Folder navigation

Equivalent Linux BASH commands:

cd - Change Directorypwd - Print Working Directory

CHANGE

Change Terminal Server Session properties.

Syntax CHANGE USER /options CHANGE LOGON /options CHANGE PORT /options

Options: To change .INI file mapping: (administrator rights required)

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 Commands:

Other Terminal Server commandsINSTSRV - Install an NT ServiceLOGOFF - Log a user off MSIEXEC - Microsoft Windows InstallerQ243202 - TS Session Management Tools

The Microsoft NT4 'Automated Installation Framework' (MSIF) - also included a grep-like command called CHANGE.

Equivalent Linux BASH commands:

who - Print all usernames currently logged in

chkdsk.exe

Check Disk - check and repair disk problems

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

Key [drive:] Specify the drive to check. filename Specify the 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)For 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

To issue chkdsk on a hard drive you must be a member of the Administrators group.

If you specify the /f switch, chkdsk will show an error if open files are found on the disk. Chkdsk /f will lock the volume, making data unavailable until chkdsk is finished.

If you use chkdsk /f on a very large disk or a disk with a very large number of files (millions), chkdsk may take a long time to complete. The computer will not be available during this time, as chkdsk does not relinquish control until it is done.

Scan only (without /f switch)

If a file needs to be fixed chkdsk will alert you with a message but will not fix the error(s).

chkdsk may report lost allocation units on the disk - it will produce this report even if the files are 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. As a rule, run chkdsk only on volumes that are known to be corrupt.On computers running Windows 2003 SP1, chkdsk automatically creates a shadow copy, so you can check volumes that are 'in use' by another program or process. This enables an accurate report against a live file server. On earlier versions of Windows, chkdsk would always lock the volume, making data unavailable. Run at BootupUse the chkntfs or the FSUTIL dirty commands to set or query the volume's dirty bit (indicating corruption) so that Windows runs chkdsk when the computer is restarted.On volumes marked as "dirty," Windows automatically runs chkdsk when the computer is restarted. Prior to Win2003 SP1, running at bootup is often the easiest way to close all open file handles. Event LogsChkdsk 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 sizetypically: "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 found1 Errors were found and fixed.2 Could not check the disk, did not or could not fix errors. Notes:Consider the time required to run Chkdsk to repair any errors that occur. Chkdsk times are determined by the number of files on the volume and by the number of files in the largest folder. Chkdsk performance under Windows 2003 is around 30% faster than previous versions.

When CHKDSK is set to run at 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 ManagerREG_DWORD:AutoChkTimeOutDataThe value is the time in seconds that you want CHKDSK to wait (0 = no delay) default is 10 seconds.The file system structure on the disk is corrupt and unusable. If you have disk corruption, run the drive manufacturers diagnostics: fujitsu | ibm | maxtor | seagate | western digitalAlso: memtest.org and ubcd.sourceforge.net

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

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

Related commands:

CHKNTFS - schedule CHKDSK to run at boot time.FSUTIL dirty query C: - Is the drive dirty Cleanmgr.exe - Windows 2000 disk cleanupQ187941 - New /C and /I SwitchesQ283340 - Windows XP does not detect corruptionQ303079 - Locate and correct NTFS problems.Q310747 - System File Checker (Sfc.exe) Q327009 - Chkdsk Finds Incorrect Security IDs Q329394 - Long Delays Occur When You Run Chkdsk.exe Q873437 - Windows 2000 incorrectly identifies security descriptorsJSIFAQ - Cleaning unused security descriptors

Equivalent Linux BASH commands:

cksum - Print CRC checksum and byte countsfsck - 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 fileQ160963 - ChkNTFS What you can use it forScheduling Windows 2000’s Disk Defragmenter

CHOICE.exe (Resource Kit)

Accept user input to a batch file.

Choice allows single key-presses to be captured from the keyboard.

Syntax CHOICE [/C[:]choiceKeys] [/N] [/S] [/T[:]k,nn] [text]

Key /C[:]choiceKeys : One or more keys the user can press. Default is YN /N : Do not display choiceKeys at end of prompt string. /S : case Sensitive. /T[:]k,dd : Default the choice to k after dd seconds text : Message string to display the choices available

The Windows 2003 version has some slight differences:

CHOICE [/c [choiceKeys]] [/N] [/CS] [/t Timeout /d Choice] [/m Text]

key /C[:]choiceKeys : One or more keys the user can press. Default is YN

/N : Do not display choiceKeys at end of prompt string. /CS : Case Sensitive. /T dd : Timeout in dd seconds /d choiceKey : Choice made on Timeout /m text : Message string to describe the choices available

ERRORLEVEL will return the numerical offset of choiceKeys.AvailabilityChoice.com was originally supplied on the Windows 95 install CD, however there are some issues with this version under NT - multiple concurrent invocations of CHOICE will clobber each other. CHOICE.com will also burn a lot of CPU's when in a wait state. The NT and 2000 Resource Kits contain CHOICE.EXE which behaves a lot better.In Windows 2003 CHOICE became a built-in command so it is no longer in the resource kit.Examples:

CHOICE /C:FH /N select [F] Floppy or [H] Hard drive IF errorlevel 2 goto s_hard IF errorlevel 1 goto s_floppy

Note the order of the IF statements above, IF errorlevel 1 will return TRUE for an errorlevel of 2

CHOICE can be used to set a specific %errorlevel% for example to set the %errorlevel% to 6 :ECHO 6| CHOICE /C:123456 /N >NUL

I saw a woman wearing a sweatshirt with "Guess" on it. I said, "Thyroid problem?" - Arnold Schwarzenegger

Related Commands:

IF - Conditionally perform a command

Equivalent Linux BASH commands:

case - Conditionally perform a commandselect - 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:\reportsTo back up the certificate and private key currently used to encrypt and decrypt EFS files to a file named c:\myefsbackup.pfx, type:CIPHER /x c:\myefsbackup"He that would make his own liberty secure must guard even his enemy from oppression; for if he violates this duty he establishes a precedent that will reach to himself" - Thomas Paine

Related Commands:

FSUTIL - File and Volume utilities

CLEANMGR.exe

Automated cleanup of Temp files, Internet files, downloaded files, recycle bin (XP).

Syntax CLEANMGR option

Options /d driveletter: - Select the drive that you want Disk Cleanup to clean.

/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:64Options that can be chosen for cleanup:

Temporary Internet FilesTemporary Setup FilesDownloaded Program FilesOld Chkdsk FilesRecycle BinTemporary FilesTemporary Offline FilesOffline FilesCompress Old FilesCatalog 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 thise.g.REGEDIT /S cleanmgr.reg CLEANMGR /sagerun:64Other 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 filesTo 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 applicationsOpen a command promptClick Start, and then Shut DownSimultaneously 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 cacheDEFRAG - Defragment hard drive (XP)Q253597 - Automating Disk Cleanup in WindowsQ315246 - Automating Disk Cleanup in Windows XP Q812248 - Disk Cleanup stops responding while compressing old files

Equivalent Linux BASH commands:

watch - Execute/display a program periodically

CLIP.exe (Resource Kit)

Copy the result of any command to the Windows clipboard.

Syntax command | CLIP

CLIP < filename.txtWhen 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 Commands:

cmdtools.com - clip.zip - copy clipboard to a fileScript-It - Control GUI applicationsSET - Display, set, or remove Windows NT environment variables

Equivalent Linux BASH commands:

export - Set an environment variable xsel - get and set the contents of an 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 NT command, program or batch script to be run. This can even be several commands separated with '&&' (the whole should also be surrounded by "quotes")

/T:fg Sets the foreground/background colours /X Enable extensions to CMD.EXE under Windows 2000 you can also use /E:ON

/Y Disable extensions to CMD.EXE under Windows 2000 you can also use /E:OFF

/A Output ANSI Characters /U Output UNICODE Characters These 2 swiches are useful when piping or redirecting to a file Most common text files under WinNT are ANSI, use these switches when you need to convert the character set.

more below

Win2K / XP switches

The CMD switches below were first introduced with Windows 2000 /D Ignore registry AutoRun commands HKLM | HKCU \Software\Microsoft\Command Processor\AutoRun /F:ON Enable auto-completion of pathnames entered at the CMD prompt /F:OFF Disable auto-completion of pathnames entered at the CMD prompt (default)

At the command prompt Ctrl-D gives folder name completion and Ctrl-F gives file and folder name completion.

These ctrl keys build up a list of paths that match and display the first matching path. Thereafter, repeated pressing of the same control key will cycle through the list of matching paths. Pressing SHIFT with the control key will move through the list backwards.

/Q Turn echo off

/S Strip quote characters from the command_line

/V:ON Enable delayed environment variable expansion this allows a FOR loop to specify !variable! instead of %variable% expanding the variable at execution time instead of at input time. /V:OFF Disable delayed environment expansion.

Environment expansion preference can be set permanently in the registry HKLM | HKCU \Software\Microsoft\Command Processor\DelayedExpansion Set to either 0x1 or 0x0

/knetdiag /debug /knetdiag /fix

The knetdiag switches are undocumented and work in XP only they list and (may) fix these networking issues.

If /C or /K is specified, then the remainder of the command line is processed as an immediate command in the new shell. Multiple commandsseparated by the command separator '&&' are accepted if surrounded by quotes.

The following logic is used to process quote (") characters:

1. If all of the following conditions are met, then quote characters on the command line are preserved:

- no /S switch - exactly two quote characters - no special characters between the two quote characters, where special is one of: &<>()@^| - there are one or more whitespace characters between the the two quote characters - the string between the two quote characters is the name of an executable file.

2. Otherwise, old behavior is to see if the first character is a quote character and if so, strip the leading character and remove the last quote character on the command line, preserving any text after the last quote character.Command.com vs cmd.exe

All the commands on these pages assume you are running the 32 bit command line (cmd.exe)

CMD.exe is the NT/XP equivalent of Command.com in previous operating systems. The older 16 bit command processor command.com is supplied to provide backward compatibility for 16 bit DOS applications. e.g. command.com will fail to set %errorlevel% after certain commands.

To ensure that a batch file will not run if accidentally copied to a Windows 95/98 machine you should use the extension .CMD rather than .BAT

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

Subject to licensing issues, it is possible to run the Windows 2000 or Win XP version

of CMD.EXE under NT. This is not true of all commands, e.g. any command that involves NTFS disk access (such as cacls) should not be moved between OS versions.

Opening CMD from Windows Explorer

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

Related Registry Keys:;Allow UNC paths at command prompt[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]"DisableUNCCheck"=dword:00000001Previous 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 PasteQuickEdit mode allows the use of cut and paste functions at the Command Prompt.

Open Control Panel, Console and check the QuickEdit Mode box.COPY:With your left-mouse button, select a line of text, now right-click anywhere in the window to COPY. (in NT 4 there is no popup menu)This saves the selected text to the clipboard. PASTE:Now right-click again anywhere in the CMD window to PASTE the text to the command line.Note: moving the cursor and toggling Insert/Overwrite is also possible.Press ESC to cancel the selection and return to editing mode.

Using CMD in a batch script

In a batch script CMD will start a new instance of CMD.exe which will appear in the same window. The EXIT command will close the second CMD instance and return to the previous shell.

A method of calling one Batch script from another is to run a command like

CMD /c C:\docs\myscript.cmd

The output of CMD can be redirected into a text file. Notice that where CMD /c is used, the EXIT command is not required.

The environment Variable %CMDCMDLINE% will expand into the original command line passed to CMD.EXE

Pausing a batch scriptExecution of any batch script can be paused by pressing CTRL-S

This also works for pausing a single command such as a DIR listingPressing any key will resume the operation.

Stopping a batch script from runningExecution 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 CommandsUnder Windows NT, the command line is limited to 256 characters.Under Windows 2000, the command line is limited to 2046 characters. Under Windows XP, the command line is limited to 8190 characters. For all OS's NTFS and FAT allows pathnames of up to 260 characters.

A workaround for the limited pathname length is to prefix \\?\ for example:\\?\C:\TEMP\Long_Directory\Long_Filename.txt

The above limits are often encountered when using long share names or drag and dropping files onto a batch script.Full ScreenThe key combination ALT and ENTER will switch a CMD window to full screen mode.press ALT and ENTER again to return to a normal Window. Command Extensions

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

Related commands:

EXIT - Use this to close a CMD shell and return. CALL - Call one batch program from anotherSTART - Start a separate window to run a specified program or command DOSKEY Edit command line, recall commands Q156276 - Cmd does not support UNC names as the current directory Equivalent Linux BASH commands:

builtin - Run a shell builtinbash - run the bash shell csh - run the C shell ksh - run the Korn shellsh - run the Bourne shell

COLOR

Sets the default console foreground and background colours.

Syntax COLOR [background][foreground]Colour attributes are specified by 2 of the following hex digits. Each digit can be any of the following values:

0 = Black 8 = Gray

1 = Blue 9 = Light Blue

2 = Green A = Light Green

3 = Aqua B = Light Aqua

4 = Red C = Light Red

5 = Purple D = Light Purple

6 = Yellow E = Light Yellow

7 = White F = Bright White

If no argument is given, COLOR restores the colour to what it was when CMD.EXE started.

Colour values are assigned in the following order:

The DefaultColor registry value. The CMD /T command line switchThe current colour settings when cmd was launched

The COLOR command sets ERRORLEVEL to 1 if an attempt is made to execute the COLOR command with a foreground and background colour that are the same.

Examples:

COLOR 07, white on black is the default.

"COLOR 00" is an invalid option and will set %ERRORLEVEL% to 1 (this fails on some early builds of NT 4 - see verify for an alternative method of raising an error)

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

Related commands:

CMD - Start a new CMD shell

Equivalent Linux BASH commands:

dircolors - Colour setup for `ls'

COMP.exe

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

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

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

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) promptto suppress this: ECHO n|COMP <options>"Shall I compare thee to a summer's day" - William Shakespeare

Related Commands:

FC - Compare two files and display any LINES which do not match

Equivalent Linux BASH commands:

comm - Compare two sorted files line by line cmp - Compare two filesdiff - Display the differences between two filesdiff3 - Show differences among three filessdiff - merge two files interactively

CON2PRT.exe (Zero Admin Kit)

Add a network printer to the Control Panel - Printers folder, and/or Disconnect a printer.

All commands issued using this utility will affect only the user currently logged in. Con2prt is therefore ideal for managing NETWORK printer connections when used in a login script.

Syntax CON2PRT /f CON2PRT /c \\PrintServer\PrintShare CON2PRT /cd \\PrintServer\PrintShare

Key /f - remove all network printer connections /c - connect to \\PrintServer\PrintShare /cd - connect to and set PrintShare as the default printer

Several switches can be combined in one command line. So you can remove all connections before adding new ones all in one command, you can only specify one default printer.

Available for free download at: http://www.microsoft.com/windows/zak/Also the freeware utility AdPrintX is very similar to Con2Prt but has additional functionality, including compatibility with Windows 9x systems. (it's also a smaller download)"I think you know as well as I do what the problem is, Dave. You and Dr. Poole were planning to disconnect me. I cannot allow this to happen" - HAL

Related:PRINT - Print a text fileNET VIEW - to view a list of printersNET 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 jobsPRNMNGR - Add, delete, or list printers / connections, set the default printer. PRNPORT - Create, delete, or list TCP/IP printer ports, change port configuration. PRNQCTL - Print a test page, pause or resume a printer, clear a printer queue.RUNDLL32 - Install/Remove Printers (plus advanced options)WMIC PRINTER - Set printing options through WMINetwork Printing - Advice & Tips including printcon.vbs (Change print connection) Q189105 - Add Printers with No User Interaction (Win 2000)Q314486 - Add Printers with No User Interaction (Win XP)

WSH Commands:Add printer - WshNetwork.AddPrinterConnection Add Network printer - WshNetwork.AddWindowsPrinterConnection List printers - WshNetwork.EnumPrinterConnections Set default printer - WshNetwork.SetDefaultPrinter

Equivalent Linux BASH commands:

lpc - Line printer control programlpr - Off line print lprint - Print a filelprintd - Abort a print joblprintq - List the print queuelprm - Remove jobs from the print queue

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 fileNNT 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 dest1COPY will accept UNC pathnames

Examples:

In the current folderCOPY oldfile.wp newfile.doc

Full path specifiedCOPY g:\department\oldfile.wp "c:\Files to Convert\newfile.doc"

Specify the drive and filename (assumes the current folder on both drives is correct)COPY a:oldfile.wp c:newfile.doc

Specify source only (will copy the file to current folder, keeping the same filename)COPY g:\department\oldfile.wp

Quiet copy (no feedback on screen)COPY oldfile.wp newfile.doc >nul

"I've been going to Bible classes. They're teaching me to be more judgmental" - Flanders' wife

Related Commands:

ROBOCOPY - Robust File and Folder Copy SCOPY - File Copy with SecurityXCOPY - Copy files and folders MOVE - Move a file from one folder to another Mcopy - Copy and create a log file (Win 2K ResKit)Fcopy - File Copy for MMQ (copy changed files & compress. (Win 2K ResKit)Permcopy - Copy share & file ACLs from one share to another. (Win 2K ResKit)

Equivalent Linux BASH commands:

cp - Copy one or more files to another locationinstall - Copy files and set attributes

CSVDE / LDIFDE (Directory Exchange)

Import or Export Active Directory data to a file. The syntax of these two commands is identical, the difference being that one works with CSV files and one with LDIF files.

Syntax

Export to file: CSVDE [-f FileName] [options] LDIFDE [-f FileName] [options]

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\LogFile Logfile location -t Port Number (default = 389) -? Help Export options -d RootDN The root of the LDAP search (Default to Naming Context) -r Filter LDAP search filter (Default to "(objectClass=*)") -p SearchScope Search Scope (Base/OneLevel/Subtree) -l list Attributes to look for in an LDAP search (comma separated List) -o list Attributes to omit from input (comma separated list) -g Disable Paged Search -m Enable the SAM logic on export -n Do not export binary values Import options -k Ignore 'Constraint Violation' and 'Object Already Exists' errors.

Note to successfully import a file it must contain as a minimum The DN(distinguished name), DisplayName and ObjectClass

Username/Password credentials -a Sets the command to run using the supplied user distinguished name

and password. For example: "cn=yourname,dc=yourcompany,dc-com password" -b Sets the command to run as username domain password. The default is to run using the credentials of the currently logged on user.CSV (comma-separated value) format files can be read with MS Excel and are easily modified with a batch script. LDIF files (Ldap Data Interchange Format) are a cross-platform standard. This provides a method to populate Active Directory with data from other directory services. (e.g. Netscape NDS, Novell NDS/eDirectory, Oracle Internet Directory)PasswordsFor 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)CompatibilityCSVDE 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.)ExamplesExport the whole domainCSVDE -f MyDomain.csv

Export all users with a particular surname: CSVDE -f MyUsers.csv -r (and(objectClass=User)(sn=Surname))Import the whole domainCSVDE -i -f MyDomain.csv -j C:\MyLogfile.txt"Give me your tired, your poor,Your huddled masses yearning to breathe free,The wretched refuse of your teeming shore.Send these, the homeless, 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 CSVDEQ263991 - How to set a user's password with Ldifde Q276440 - Backup and Restore Connection Agreements with CSVDE

Equivalent Linux BASH commands:

ldapadd - Add LDAP information

DATE

Display or change the date

Syntax

to display the date DATE /T

to set the system date DATEor 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 followsFOR /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 followsFOR /F "TOKENS=3 delims= " %%G IN ('REG QUERY "HKEY_CURRENT_USER\Control Panel\International\sDate"') DO SET _date_sep=%%GIf Command Extensions are disabled DATE will not support the /T switch

"Carpe Diem - Seize the day" - Horace

Related Commands:

GetDate.cmd - Get todays Date (any region, any OS)datetime.vbs - Get Date, Time and daylight savings

NOW - Display Message with Current Date and TimeNET 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 timeTOUCH - Change file timestamps

Equivalent Linux BASH commands:

cal - Display a calendardate - Display or change the datetime - Measure Program Resource Usetimes - User and system times touch - Change file timestamps

DEFRAG (Windows XP)

Defragment hard drive.

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

Options volume drive letter or mount point (d: or d:\vol\mountpoint) -a Analyze only -f Force defragmentation even if free space is low -v Verbose outputExample:

DEFRAG c: -f"How can you expect to govern a country that has two hundred and forty-six kinds of cheese?" - Charles de GaulleRelated Commands:

CleanMgr - Automated cleanup of Temp files, Internet files, downloaded files, recycle binDISKPART - Partition managerpagefileconfig.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 characterExamples:

To delete HelloWorld.TXTDEL HelloWorld.TXT

To delete "Hello Big World.TXT"DEL "Hello Big World.TXT"

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

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

To delete all files with a .DOC extensionDEL *.DOC

To delete all read only filesDEL /a:R *

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

FoldersIf 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 FilesYou 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.txtDEL C:\examples\MyFile.txtUndeletable FilesFiles 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\LPT1Alternatively 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 applicationsOpen a command promptClick Start, and then Shut DownSimultaneously 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 filesRD /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 offpushd %1del /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 FeissRelated Commands:

DELPROF Delete NT user profilesDelrp - 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 binINUSE - updated file replacement utility (may not preserve file permissions)

Q120716 - Delete in-use files with rmQ320081 - Cannot delete a file or folderQ159199 - A file cannot be deleted (NTFS)Delete files older than X days

How to change the Windows NT recycle bin

Equivalent Linux BASH commands:

rm - Remove filesrmdir - Remove folder(s)

DELPROF (Resource Kit)

Delete NT user profiles.

Syntax DELPROF [options]

Key /Q Quiet, no confirmation.

/I Ignore errors and continue deleting.

/P Prompts for confirmation before deleting each profile.

/C:\\computer_name Delete profiles on a remote computer.

/D:Number_of_days Only delete profiles that have been inactive for 'X' Number of days (or greater)

/R Delete roaming profile cache only ##

## = New in version 5.2 (XP resource kit)Example:

delprof /D:14

"The best way to destroy the capitalist system is to debauch the currency" - John Keynes Related Commands:

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

DEL

Delete one or more files.

Syntax DEL [options] [/A:file_attributes] files_to_delete

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

options /P Give a Yes/No Prompt before deleting. /F Ignore read-only setting and delete anyway (FORCE) /S Delete from all Subfolders (DELTREE) /Q Quiet mode, do not give a Yes/No Prompt before deleting.

/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 characterExamples:

To delete HelloWorld.TXTDEL HelloWorld.TXT

To delete "Hello Big World.TXT"DEL "Hello Big World.TXT"

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

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

To delete all files with a .DOC extensionDEL *.DOC

To delete all read only filesDEL /a:R *

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

FoldersIf 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 FilesYou 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.txtDEL C:\examples\MyFile.txtUndeletable FilesFiles 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\LPT1Alternatively 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 applicationsOpen a command promptClick Start, and then Shut DownSimultaneously 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 filesRD /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 offpushd %1del /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 FeissRelated Commands:

DELPROF Delete NT user profilesDelrp - 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 binINUSE - updated file replacement utility (may not preserve file permissions)

Q120716 - Delete in-use files with rmQ320081 - Cannot delete a file or folderQ159199 - A file cannot be deleted (NTFS)Delete files older than X daysHow to change the Windows NT recycle bin

Equivalent Linux BASH commands:

rm - Remove filesrmdir - Remove folder(s)

The DevCon command-line utility functions as an alternative to Device ManagerView products that this article applies to.

Article ID : 311272Last Review : January 5, 2006Revision : 5.0

This article was previously published under Q311272

On This Page

SUMMARY MORE INFORMATION Using DevCon Example DevCon commands Notes

SUMMARY

The DevCon utility is a command-line utility that acts as an alternative to Device Manager. Using DevCon, you can enable, disable, restart, update, remove, and query individual devices or groups of devices. DevCon also provides information that is relevant to the driver developer and is not available in Device Manager.

You can use DevCon with Microsoft Windows 2000, Windows XP, and Windows Server 2003. You cannot use DevCon with Windows 95, Windows 98, or Windows Millennium Edition.

Back to the top

MORE INFORMATION

DevCon is not redistributable. It is provided for use as a debugging and development tool. You can freely modify DevCon for private use. The sample demonstrates how to use the SetupAPI and CfgMgr32 functions together effectively to enumerate devices and perform device operations. The following file is available for download from the Microsoft Download Center:

Download the DevCon package now. (http://download.microsoft.com/download/1/1/f/11f7dd10-272d-4cd2-896f-9ce67f3e0240/devcon.exe) Release Date: Jan-29-2003

For more information about how to download Microsoft support files, click the following article number to view the article in the Microsoft Knowledge Base: 119591 (http://support.microsoft.com/kb/119591/) How to obtain Microsoft support files from online services

Microsoft scanned this file for viruses. Microsoft used the most current virus-detection software that was available on the date that the file was posted. The file is stored on security-enhanced servers that help prevent any unauthorized changes to the file.

The DevCon.exe file contains the following files: File Description

I386\DevCon.exe32-bit DevCon tool binary. This will not function completely on 64-bit Windows.

Ia64\DevCon.exe 64-bit DevCon tool binary.

Note The source code for DevCon is also available in the Windows DDK (which is available from http://www.microsoft.com/whdc/devtools/ddk/default.mspx (http://www.microsoft.com/whdc/devtools/ddk/default.mspx)) under DDK root\Src\Setup\Devcon, along with documentation.

Back to the top

Using DevCon

DevCon is a command-line utility with built-in documentation. If you run the devcon help command, the following list of commands and descriptions appears. The devcon help command

will give more detailed help on any command. With some of these commands, you can specify a remote target computer. These commands work if you are using the 32-bit version of DevCon on WOW64. Device Console Help:devcon.exe [-r] [-m:\\<machine>] <command> [<arg>...]-r if specified will reboot machine after command is complete, if needed.<machine> is name of target machine.<command> is command to perform (see below).<arg>... is one or more arguments if required by command.For help on a specific command, type: devcon.exe help <command>classfilter Allows modification of class filters.classes List all device setup classes.disable Disable devices that match the specific hardware or instance ID.driverfiles List driver files installed for devices.drivernodes Lists all the driver nodes of devices.enable Enable devices that match the specific hardware or instance ID.find Find devices that match the specific hardware or instance ID.findall Find devices including those that are not present.help Display this information.hwids Lists hardware ID's of devices.install Manually install a device.listclass List all devices for a setup class.reboot Reboot local machine.remove Remove devices that match the specific hardware or instance ID.rescan Scan for new hardware.resources Lists hardware resources of devices.restart Restart devices that match the specific hardware or instance ID.stack Lists expected driver stack of devices.status List running status of devices.update Manually update a device.UpdateNI Manually update a device without user prompt SetHwID Adds, deletes, and changes the order of hardware IDs of root-enumerated devices.

Example DevCon commands

devcon -m:\\test find pci\*

Lists all known PCI devices on the computer test. (By using-m, you can specify a target computer. You must use Interprocess communication (IPC) to access the computer.)

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

Installs a new instance of the Microsoft loopback adaptor. This creates a new root-enumerated device node with which you can install a "virtual device," such as the loopback adaptor. This command also restarts the computer silently if a restart is required.

devcon classes

Lists all known setup classes. The output contains the short nonlocalized name (for example, "USB") and the descriptive name (for example, "Universal Serial Bus controllers").

devcon classfilter upper !filter1 !filter2

Deletes the two specified filters.

devcon classfilter lower !badfilter +goodfilter

Replaces the "badfilter" with the "goodfilter".

devcon driverfiles =ports

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

devcon disable *MSLOOP

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

devcon drivernodes @ROOT\PCI_HAL\PNP0A03

Lists all compatible drivers for the device ROOT\PCI_HAL\PNP0A03. This can be used to determine why an integral device information (.inf) file was chosen, instead of a third-party .inf file.

devcon enable '*MSLOOP

Enables all devices that have a hardware ID of "*MSLOOP". The single quotation mark indicates that the hardware ID must be taken literally (in other words, the asterisk ["*"] actually is an asterisk; it is not a wildcard character).

devcon find *

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

devcon find pci\*

Lists all known peripheral component interconnect (PCI) devices that are on the local computer (this command assumes that a device is PCI if it has a hardware ID that is prefixed by "PCI\").

devcon find =ports *pnp*

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

devcon find =ports @root\*

Lists devices that are present that are a member of the ports setup class and that are in the "root" branch of the enum tree (the instance ID is prefixed by "root\"). Note that you should not

make any programmatic assumption about how an instance ID is formatted. To determine root devices, you can look at device status bits. This feature is included in DevCon to aid in debugging.

devcon findall =ports

Lists "nonpresent" devices and devices that are present for the ports class. This includes devices that have been removed, devices that have been moved from one slot to another, and, in some cases, devices that have been enumerated differently due to a BIOS change.

devcon listclass usb 1394

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

devcon remove @usb\*

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

devcon rescan

Rescans for new Plug and Play devices.

devcon resources =ports

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

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

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

devcon hwids=mouse

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

devcon sethwid @ROOT\LEGACY_BEEP\0000 := beep

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

devcon stack =ports

Lists the expected driver stack for the device. This includes device and class upper/lower filters, and the controlling service.

devcon status @pci\*

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

devcon status @ACPI\PNP0501\1

Lists the status of a specific device instance, in this case an Advanced Configuration and Power Interface (ACPI)-enumerated serial port.

devcon status @root\rdp_mou\0000

Lists the status of the Microsoft Terminal Server or Terminal Services mouse driver.

devcon status *PNP05*

Lists the status of all COM ports.

devcon update mydev.inf *pnp0501

Updates all devices that exactly match the hardware ID *pnp0501 to use the best driver in Mydev.inf that is associated with the hardware ID *pnp0501.

Note This update forces all devices to use the driver in Mydev.inf, even if there is a better match already on the system. This is useful when you want to install new versions of drivers during

development before you obtain a signature. The update affects only the devices that match the specified hardware ID, and does not affect the child devices. If the specified .inf file is unsigned, Windows may display a dialog box that prompts you to confirm whether the driver should be installed. If a restart is required, this is reported and DevCon returns a level 1 error. If you specify -r, this causes a restart to occur automatically if one is required.

Notes

DevCon will return an error level for use in scripts: "0" indicates a success."1" indicates that a restart is required."2" indicates a failure."3" indicates a syntax error.

•If you specify -r and a restart is required, the restart occurs without warning after all devices have been processed.

•If you specify -m:\\computer and the command will not work for a remote computer, an error is reported.

DevCon allows wildcards in instance IDs for interactive convenience. Do not assume anything about the format of an instance ID from computer to computer and from operating system version to operating system version

DIR

Display a list of files and subfolders

Syntax DIR [pathname(s)] [display_format] [file_attributes] [sorted] [time] [options]Key [pathname] The drive, folder, and/or files to display, this can include wildcards:

* Match any characters ? Match any ONE character

[display_format] /P Pause after each screen of data. /W Wide List format, sorted horizontally. /D Wide List format, sorted by vertical column.

[file_attributes] /A:

/A:D Folder /A:-D NOT Folder /A:R Read-only /A:-R NOT Read-only

/A:H Hidden /A:-H NOT Hidden /A:A Archive /A:-A NOT Archive /A Show all files several attributes may be combined e.g. /A:HD-R

[sorted] Sorted by /O:

/O:N Name /O:-N Name /O:S file Size /O:-S file Size /O:E file Extension /O:-E file Extension /O:D Date & time /O:-D Date & time /O:G Group folders first /O:-G Group folders last several attributes may be combined e.g. /O:GEN

[time] /T: the time field to display & use for sorting

/T:C Creation /T:A Last Access /T:W Last Written (default)

[options] /S include all subfolders. /R Display alternate data streams. (Vista only) /B Bare format (no heading information 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 yearsThe 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 *.* /-SUpper 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 %%GNormally 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_downloadedSince TYPE won't lock the file_being_downloaded in any way, this doesn't pose a threat to the download itself. "There it was, hidden in alphabetical order" - Rita Holt

Related commands

WHERE - Locate and display files in a directory tree.XCOPY /L - List files without copying.ROBOCOPY /L - List files with specific properties DIRUSE - show size of multiple subfolders. (Resource Kit)Freedisk.exe - check free disk space. (Win 2K ResKit)

You can also get File Sizes and Date/Time from Windows 2000/XP Batch ParametersUse DIR to display drive status - disk missing / ready / emptyQ226370 - Browsing LAN directories is slow

Equivalent Linux BASH commands:

ls - List information about file(s)

DIRUSE (2K Resource Kit / XP Support Tools)

Display disk usage

Syntax DIRUSE [options] Folders...Options

/M Display in Mb/K Display in Kb/B Display in bytes (default)/, Use thousand separator when displaying sizes.

/Q:# Quota limit, mark folders that exceed the size (#) with a "!". set %errorlevel% to ONE if any folders are found that

exceed the specified size

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

DIR - Display a list of files and foldersYou can also list files with XCOPY /LFreedisk.exe - check free disk space. (Win 2K ResKit) FSUTIL - File and Volume utilities

Equivalent Linux BASH commands

du - Disk Usagequota - Display disk usage and limitsquotacheck - Scan a file system for disk usagequotactl - Set disk quotas ulimit - Limit user resources

DISKCOMP.com

Compare the content of two floppy disks.

Syntax DISKCOMP floppy_drive1: floppy_drive2:

Key floppy_drive is the drive letterThe two disks must be the same type, e.g. both 1.44 Mb or both 720 K If you specify the same drive letter for floppy_drive1 and floppy_drive2 - you will be prompted to enter each disk.

For Example:

DISKCOMP A: A:

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

Related commands:

DISKCOPY - Copy the contents of one floppy disk to anotherFC - Compare two files or sets of files, and display the differences between them

Equivalent Linux BASH commands:

cksum - Print CRC checksum and byte counts

DISKCOPY.com

Copy the content of one floppy disk to another.

Syntax DISKCOPY flopppy_drive1: floppy_drive2: [/V]

Key /V Verify that the information was copied correctly.The two disks must be the same type, e.g. both 1.44 Mb or both 720 K If you specify the same drive letter for floppy_drive1 and floppy_drive2 - you will be prompted to enter each disk.DISKCOMP A: A:

Related commands:

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

DOSKEY.exe

Recall and edit commands at the DOS prompt, and create macros. You cannot run a Doskey macro from a batch file.

Syntax DOSKEY [options] [macroname=[text]]

Key macroname : A short name for the macro.

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 soyou can use the following Keystrokes at the command line

UP and DOWN ARROWS or F8 will recall commands;

F7 : popup command history (enter to accept, ESC to cancel) <letter>F8 : command history (commands starting with letter) F9 : select a command by number

ESC : clear command line ALT+F7 : clear command history INSERT : toggle Insert/Overwrite

Pressing F8 repeatedly will cycle through all the matching commands.

The size of the command history can be set from Control Panel, Console or from the properties of any cmd shortcut. Clear all history with DOSKEY /REINSTALL

Examples:A macro to open notepad DOSKEY note=notepad.exe

A macro to open WordPad DOSKEY wpad="C:\Program Files\Windows NT\Accessories\wordpad.exe"

A macro called `d' to run dir/w DOSKEY d=dir/w

A macro to disable the FORMAT command DOSKEY FORMAT=;Ive disabled the Format command

More advanced macro definitions:

$T If you put more than one command in a DOSKEY macro, use $T. to separate them. Equivalent to & in a batch file.

$1-$9 Parameters, equivalent to %1-%9 in a batch file.

$* This represents ALL the parameters $1-9

A macro to open a file with WordPad:DOSKEY wpad="C:\Program Files\Windows NT\Accessories\wordpad.exe" $1Using the above macro:wpad MyTextfile.txt

Save and restore macro definitions

DOSKEY macros are normally only visible to the current CMD session.

The command doskey /macros >macros.cmdWill list all current macro definitions into macros.cmd, edit this fileand place DOSKEY at the start of each line."No man steps in the same river twice, for it's not the same river, and he's not the same man." - Heraclitus

Related commands:

The Script-It Utility can supply keystrokes to control almost any Windows Application.

Equivalent Linux BASH commands:

m4 - Macro processorhistory - Command history

DSADD.exe (Windows XP)

Add active directory object.

Syntax DSADD computer Computer_DN options DSADD contact ContactDN options DSADD group GroupDN options DSADD ou OU_DN organizational_unit_options DSADD user User_DN user_options

Key

DN=Distinguished Name(s)OU=Organisational UnitPretty much all the attributes can be modified (Name, display name, tel number etc)run the command with /? for a full liste.g DSADD USER /?CommasCommas must be escaped with the backslash \ character(other than separators in distinguished names)e.g."CN=Company\, Inc.,CN=Users,DC=ss64,DC=com"

BackslashesBackslashes used in distinguished names must be escaped with a backslash (for example,"CN=Sales\\ Latin America,OU=Distribution Lists,DC=ss64,DC=com").If any value contains spaces, use quotation marks: "CN=John Smith,CN=Users,DC=SS64,DC=com"Special TokensThe 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 ObjectsFor any DS command you can enter multiple values separated by spaces.e.g. to add several user accounts at once just supply a list of the distinguished names separated with spaces.

It is also possible to store multiple values in a text file and redirect into DSADD. "For a list of all the ways technology has failed to improve the quality of life, press three". - Alice Kahn

Related commands:dsmod - modify objectdsget - display object dsmove - move objectdsquery - find objectdsrm - delete objectCSVDE - Import or export AD info in CSV format.LDIFDE - Edit AD Objects, extend schema, import or export AD information.

Equivalent Linux BASH commands:

ldapmodify - Modify Lightweight Directory Access Protocol

DSMOD.exe (Windows XP)

Modify active directory object.

Syntax DSMOD computer Computer_DN options DSMOD contact ContactDN options DSMOD group GroupDN options DSMOD ou OU_DN Organizational_unit_options DSMOD server ServerDN Domain_controller_options DSMOD user User_DN User_options DSMOD quota QuotaDN Quota_options DSMOD partition PartitionDN Partition_options

KeyDN=Distinguished Name(s)OU=Organisational UnitPretty much all the attributes can be modified (Name, display name, tel number etc)run the command with /? for a full liste.g DSMOD USER /?CommasCommas must be escaped with the backslash \ character(other than separators in distinguished names)e.g."CN=Company\, Inc.,CN=Users,DC=ss64,DC=com"

BackslashesBackslashes used in distinguished names must be escaped with a backslash (for example,"CN=Sales\\ Latin America,OU=Distribution Lists,DC=ss64,DC=com").

RedirectionYou can pipe results from DSQUERY into DSMOD in order to modify an object.e.g. To find all users in the Marketing OU (organizational unit) and add them to the Sales group: DSQUERY user –startnode "ou=Marketing,dc=SS64,dc=com" | DSMOD group "cn=Sales,ou=Marketing,dc=SS64,dc=com" -addmbr SpacesIf any value contains spaces, use quotation marks: "CN=John Smith,CN=Users,DC=SS64,DC=com"Special TokensThe token $username$ (case insensitive) may be used to place the SAM account name.Entering * as a password will cause DSMOD to prompt for the new password.For any DS command you can enter multiple values separated by spaces.e.g. to modify several user accounts at once just supply a list of the distinguished names separated with spaces."For a list of all the ways technology has failed to improve the quality of life, press three". - Alice Kahn

Related commands:dsadd - add objectdsget - display object dsmove - move objectdsquery - find objectdsrm - delete objectCSVDE - Import or export AD info in CSV format.LDIFDE - Edit AD Objects, extend schema, import or export AD information.

Equivalent Linux BASH commands:

ldapmodify - Modify Lightweight Directory Access Protocol

ECHO

Display messages on screen, turn 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 displayType 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 statemente.g. The redirection and pipe characters: & < > | ON OFF

To override this behaviour you can escape each command character with ^ as follows: ECHO Nice ^&Easy ECHO Salary is ^> Commision ECHO Name ^| Username ^| Expiry Date ECHO:Off On Holiday

Echo a Variable

To display a department variable:

ECHO %_department%

If the variable does not exist - ECHO will simply return the text "%_department%"

This can be extended to search and replace parts of a variable or display substrings of a variable.

You can also redirect the echoed output from the screen into a file

Echo a file

see the TYPE command for this

Echo a sound

The following command in a batch file will trigger the default beep on most PC's

ECHO

Use Ctrl-G (or 'Alt' key, and 7 on the numeric keypad) to get this character (ascii 7)

Alternatively where a sound card is available:

START/min sndrec32 /play /close %windir%\media\ding.wav orSTART/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 %%GA 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 MuffinsRelated Commands:

SET - Create and display environment variablesTYPE - Display the contents of a text fileList - Text Display and Search Tool (Win 2K ResKit)

Batch file to echo giant size characters - BigText.cmdNET SEND %COMPUTERNAME%Q177795 - Large vs Small fonts

Equivalent Linux BASH commands:

echo - Display message on screen

ENDLOCAL

End localisation of environment changes in a batch file.

Syntax ENDLOCALAny changes made to an Environment Variable after ENDLOCAL has been issued will be persistent - they will still remain in memory after the batch file has terminated and any previous value stored in that Environment Variable will not be restored.

Ending the cmd.exe session will delete all Environment Variables created with the SET command.

For example: @ECHO off SETLOCAL

SET _filename=c:\test.txt SETLOCAL SET _filename=H:\UserManual.doc ENDLOCAL ECHO %_filename% - this will ECHO the value "c:\test.txt"

If SETLOCAL is used without a corresponding ENDLOCAL then localisation of environment changes will end when the batch file ends

Passing variables from one routine to another

When "&" is used to put several commands on one line, the command processor will convert all the %variables% into their text values before executing any of the commands.

By putting ENDLOCAL and SET commands on one line you are able to SET a variable outside the SETLOCAL-ENDLOCAL block that refers to a variable created inside the block.

For Example: @ECHO OFF SETLOCAL SET _file=%1 ENDLOCAL & SET _ret1=%_file%& SET _ret2=450You can use several "&" characters in order to SET several variables"A good place to visit, but a poor place to stay" - Josh BillingsRelated Commands:

SETLOCAL - Begin localisation of environment variables in a batch file.

Equivalent Linux BASH commands:

readonly - Mark variables/functions as readonly

EXIT

Quit CMD.EXE or the current batch script.

The options below are only available in Windows XP (or later).

Syntax EXIT [/B] [exitCode]

Key /B When used in a batch script it will exit the current batch script instead of CMD.EXE. If executed from outside a batch script, it

will still quit CMD.EXE

exitCode A numeric number. if /B is specified, sets ERRORLEVEL that number. If quitting CMD.EXE, sets the process exit code with that number.Gentlemen you can’t fight in here this is the war room." - President Muffley (Dr. Strangelove) Related Commands:

COLOR - Set an errorlevel (without exiting)KILL - Remove a program from memory

Equivalent Linux BASH commands:

break - Exit from a loop

EXPAND

Uncompress one or more compressed files.

Syntax EXPAND Source Destination EXPAND -r Source Destination EXPAND -r Source

Options

Source : Source filename or a wildcard

Destination : Destination filename or folder -r : Rename the filesRelated Commands:

ATTRIB - Display or change file attributesCOPY - Copy one or more files to another location

Equivalent Linux BASH commands:

gzip - Compress or decompress named file(s)

EXPAND

Uncompress one or more compressed files.

Syntax EXTRACT [options] CAB_file [filenames]

Key CAB_file : Cabinet file

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 promptRelated Commands:

ATTRIB - Display or change file attributesCOPY - Copy one or more files to another location

Equivalent Linux BASH commands:

gzip - Compress or decompress named file(s)

FC.exe

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

Syntax FC /B pathname1 pathname2

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.

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_differentExample:

If two files are compared and the four lines of text match as follows

1: different2: same3: same4: different

Specifying /nnnn =2 the file compare will display the 4th line and continue Specifying /nnnn =3 the file compare will halt at the 4th line (files too different)Specifying /LB1 the file compare will halt after the first line

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

make amends # - Janice Joplin

Related Commands:

COMP - Compare two files and display any characters which do NOT matchFIND - Search for a text string in a fileFINDSTR - Search for strings in filesWinDiff - GUI to compare files

Equivalent Linux BASH commands:

comm - Compare two sorted files line by line cmp - Compare two filesdiff - Display the differences between two filesdiff3 - Show differences among three filessdiff - merge two files interactively

FDISK

The FDisk utility is no longer supplied with recent Windows operating systems.

To reset disk partition information - boot using the install CD and choose the install/repair option.

To do a Hard Disk reformat completely outside of Windows you can use FDISK from Windows 95, 98 or ME see Q255867

Alternatively there are many third party formatting utils such as GDISK that will do the same thing.

For more advice and other links look at FDISK.com

Related Commands:

MSINFO - Windows NT diagnosticsFORMAT - Format a disk FSUTIL - File and Volume utilities Dmdiag - Display disk properties: Size, Status, Type...(Win 2K ResKit)DiskMap - Document disk structures, such as the master boot record (Win 2K ResKit)

Equivalent Linux BASH commands:

fdisk - Partition table manipulator for Linux

FIND

Search for a text string in a file & display all the lines where it is found.

Syntax FIND [/V] [/C] [/N] [/I] "string" [pathname(s)]

key /V : Display all lines NOT containing the specified string.

/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, EdinburghTo search for "Jones" in names.txtFIND "Jones" names.txt

---------- NAMES.TXTArnold Jones, 127 Scotland Street, EdinburghIf you want to pipe a command into FIND use this syntaxTYPE names.txt | FIND "Jones" You can also redirect like thisFIND /i "Jones" < names.txt >logfile.txt

To search a folder for files that contain a given search stringFOR %G IN (*.txt) do (find /n /i "SearchWord" "%G")Searching from Windows ExplorerBecause the built-in Windows File Search is broken you may want to add a find script to the Send To folder. Alternatively Agent Ransack or other search utilities will do the job properly.

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

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

Related Commands:

FC - Compare filesFINDSTR - Search for strings in filesMUNGE - Find and Replace text within file(s)ATTRIB - Find filename (rather than searching the file contents)

Equivalent Linux BASH commands:

grep - Search file(s) for lines that match a given patterngawk - Find and Replace text within file(s)tr - Translate, squeeze, and/or delete characters

FINDSTR

Search for strings in files.

Syntax FINDSTR [options] [/F:file] [/C:string] [/G:file] [string(s)] [pathname(s)]

Key string Text to search for. pathname(s) The file(s) to search. /C:string Use string as a literal search string. /G:file Get search string from a file (/ stands for console). /F:file Get a list of pathname(s) from a file (/ stands for console). /d dirlist Search a comma-delimited list of directories.

options may be any combination of the following switches:

/I Case-insensitive search. /S Search subfolders. /P Skip any file that contains non-printable characters

/L Use search string(s) literally.

/R Use search string(s) as regular expressions.(default)

/B Match pattern if at the Beginning of a line. /E Match pattern if at the END of a line.

/X Print lines that match exactly. /V Print only lines that do NOT contain a match. /N Print the line number before each line that matches. /M Print only the filename if a file contains a match. /O Print character offset before each matching line.

/a color_attribute Display filenames in colour (2 hex digits)

Options in bold are new in Windows 2000When 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 wordMetacharacters 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 charactersThe .* expression may be useful within a larger expression, for example f.*ing will match any string beginning with F and ending with ing.

Examples:

FINDSTR "granny Smith" MyFile.txtsearches for "granny" OR "Smith" in MyFile.txt.

FINDSTR /C:"granny Smith" MyFile.txtsearches for "granny Smith" in MyFile.txt This is effectively the same as the FIND command

To search every file in the current folder and all subfolders for the word "Smith", regardless of upper/lower case use:

FINDSTR /s /i smith *.*

Note that /S will only search below the current directory

To find every line containing the word SMITH, preceeded by any number of spaces, and to prefix each line found with a consecutive number:

FINDSTR /b /n /c:" *smith" MyFile.txt

Finding a string only if surrounded by the standard delimitersTo find the word "computer", but not the words "supercomputer" or "computerise":

FINDSTR "\<computer\>" MyFile.txt

Now assume you want to find not only the word "computer", but also any other words that begin with the letters comp, such as "computerise" or "compete"

FINDSTR "\<comp.*" MyFile.txt

Example of a literal search

Searching a text file that contains the followingthe quick brown foxthe darkbrown foxthe really *brown* foxFINDSTR /r .*brown MyFile.txtorFINDSTR .*brown MyFile.txtWill both match the word "brown" in all 3 lines

FINDSTR /L *brown* MyFile.txtWill only match the last string

Using a script file

Multiple search criteria can be specified with a script file /G. Multiple files to search can be specified with a source file /F.

When preparing a source or script file, place each item on a new line.

For example: to use the search criteria in CRIT.TXT and search the files listed in FILES.TXT then store the results in the file RESULTS.OUT, type

FINDSTR /g:CRIT.TXT /f:FILES.TXT > results.outErrorlevelWhen 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 charactersEcho 12G6 |FindStr /R "[^0-9]" If %ERRORLEVEL% EQU 0 echo The string contains one or more non numeric charactersBugsIn early versions of FindStr /F:file a path length of more than 80 chars will be truncated.

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

Related Commands

FIND - Search for a text string in a file.MUNGE - Find and Replace text within file(s)

Equivalent Linux BASH commands:

grep - Search file(s) for lines that match a given patterngawk - Find and Replace text within file(s)tr - Translate, squeeze, and/or delete characters

FOR /F

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

Syntax FOR /F ["options"] %%parameter IN (filenameset) DO command 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 to indicate a comment (end of line)

tokens=n Specifies which numbered items to read from each line (default = 1) usebackq Specify `back quotes`: - Use double quotes to quote long file names in filenameset. - Use single quotes for 'Text string to process' (useful if the text string contains double quotes)

Filenameset : A set of one or more files. Wildcards may be used. If (filenameset) is a period character (.) then FOR will loop through every file in the folder.

command : The command to carry out, including any command-line parameters. %%parameter : A replaceable parameter: in a batch file use %%G (on the command line %G)FOR /F processing of each text file consists of reading the file one line of text at a time and then breaking the ine up into individual items of data or 'tokens'. The DO command is then executed with the parameter(s) set to the token(s) found.

By default, /F breaks up the line at each blank space, and any blank lines are skipped. You can override this default parsing behavior by specifying the "options" parameter. The options must be contained within "quotes"Within a FOR loop the visibility of FOR variables is controlled via SETLOCAL EnableDelayedExpansionThe ` backquote character is just below the ESC key on most keyboards, the usebackq option is not available in NT4 or earlier.

Tokens tokens=2,4,6 will cause the second, fourth and sixth items on each line to be processed

tokens=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

Specifying more than 1 token will cause additional parameter names to be allocated.

If the last character in the tokens= string is an asterisk, then additional parameters are allocated for all the remaining text on the line.

Delims Specifying more than one delimiter has been known to cause problems with some data sets, if you have problems try parsing with just one delimiter at a time. When more than one delimiter is specified it's an OR, i.e either delimiter will work. If you don't specify anything it will default to "delims=<tab><space>"

When editing a CMD script notice that many text editors will fail to enter the TAB character correctly.

You can use any character as a delimiter - but they are case sensitive.ExamplesParse the output of a command: FOR /F %%G IN ('"C:\program Files\command.exe"') DO ECHO %%GParse the contents of a file: FOR /F "usebackq tokens=1,2* delims=," %%G IN ("C:\My Documents\my textfile.txt") DO ECHO %%G

FOR /F "tokens=1,2* delims=," %%G IN (C:\MyDocu~1\mytex~1.txt) DO ECHO %%GUsing tokens to Parse a text file: myfile.txt[12-AUG-99,DEPOSIT,450,23,55; start of the new year14-JAN-00,WITHDRAWAL,285,122 03-FEB-00,DEPOSIT,200]

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

This will split each line into tokens delimited by a comma, ignoring lines that begin with a semicolon, as shown below.

"12-AUG-99"

DEPOSIT "450" "23,55"

token1   token3* = All the rest

%%G   %%H %%I

%%G is explicitly declared in the FOR statement and the %%H and %%I are implicitly declared via the tokens= option. You can specify up to 26 tokens via the tokens= line, provided this does not cause an attempt to declare a parameter higher than the letter 'Z'.

FOR parameter names are global, so in complex scripts which call one FOR statement from within another FOR statement you can refer to both sets of parameters. You cannot have more than 26 parameters active at any one time.

Parse a text string: A string of text will be treated just like a single line of input from a file, the string must be enclosed in double quotes (or single quotes with usebackq).

Echo the dollar amount and the dateFOR /F "tokens=1,3* delims=," %%G IN ("12-AUG-99,deposit,$45.50,23.7") DO @echo %%H was paid on %%GFilenamesetTo specify an exact set of files to be processed, such as all .MP3 files in a folder including subfolders and sorted by date - just use the DIR /b command to create the list of filenames ~ and use this variant of the FOR command syntax. UnicodeMany of the newer commands and utilities (e.g. WMIC) output text files in unicode format, these cannot be read by the FOR command which expects ASCII. To convert the file format use the TYPE command.

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

Related Commands:

FOR - Loop commandsFOR - Loop through a set of files in one folderFOR /R - Loop through files (recurse subfolders) FOR /D - Loop through several foldersFOR /L - Loop through a range of numbersFOR /F - Loop through the output of a commandFORFILES - Batch process multiple filesIF - Conditionally perform a command SETLOCAL - Control the visibility of environment variables inside a loop

Equivalent Linux BASH commands:

cut - Divide a file into several columnscase - Conditionally perform a commandeval - Evaluate several commands/argumentsfor - Expand words, and execute commandsuntil - Execute commands (until error) while - Execute commands

FOR /F

Loop command: against the results of another command.

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

Key options: delims=xxx - The delimiter character(s) (default = a space) skip=n - A number of lines to skip at the beginning. (default = 0)

eol=; - character to indicate a comment (end of line)

tokens=n - specifies which numbered items to read from each line (default = 1)

usebackq - under Windows 2000 (and greater) the usebackq option specifies that an alternative set of FOR command delimiters are to be used: - a `command_to_process` is placed in BACK quotes instead of 'straight' quotes (see the FOR /F filename syntax for more)

command_to_process : The output of the 'command_to_process' is passed into the FOR parameter.

command : The command to carry out, including any command-line parameters.

%%parameter : A replaceable parameter: in a batch file use %%G (on the command line %G)FOR /F processing of a command consists of reading the output from the command one line at a time and then breaking the line up into individual items of data or 'tokens'. The DO command is then executed with the parameter(s) set to the token(s) found.

By default, /F breaks up the command output at each blank space, and any blank lines are skipped. You can override this default parsing behavior by specifying the "options" parameter. The options must be contained within "quotes"

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 Specifying more than one delimiter has been known to cause problems with some data sets, if you have problems try parsing with just one delimiter at a time, or change the order in which they are listed.

You can use any character as a delimiter - but they are case sensitive.

Examples:

To ECHO from the command line, the name of every environment variable. FOR /F "delims==" %G IN ('SET') DO @Echo %GThe same command with usebackq (Windows 2000 and above) FOR /F "usebackq delims==" %G IN (`SET`) DO @Echo %GTo 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 %%GIn 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 "History never repeats itself, Mankind always does" - Voltaire

Related Commands:

FOR - Summary of FOR Loop commandsFOR - Loop through a set of files in one folderFOR /R - Loop through files (recurse subfolders) FOR /D - Loop through several foldersFOR /L - Loop through a range of numbersFOR /F - Loop through items in a text file SETLOCAL - Control the visibility of variables inside a FOR loopFORFILES - Batch process multiple filesGOTO - Direct a batch program to jump to a labelled lineIF - Conditionally perform a command

Equivalent Linux BASH commands:

for - Expand words, and execute commandscase - Conditionally perform a commandgawk - Find and Replace text within file(s)m4 - Macro processoruntil - Execute commands (until error) while - Execute commands

FOR

Conditionally perform a command several times.

syntax-FOR-Files      FOR %%parameter IN (set) DO command

syntax-FOR-Files-Rooted at Path       FOR /R [[drive:]path] %%parameter IN (set) DO command

syntax-FOR-Folders      FOR /D %%parameter IN (folder_set) DO command

syntax-FOR-List of numbers       FOR /L %%parameter IN (start,step,end) DO command

syntax-FOR-File contents       FOR /F ["options"] %%parameter IN (filenameset) DO command

      FOR /F ["options"] %%parameter IN ("Text string to process") DO command

syntax-FOR-Command Results       FOR /F ["options"] %%parameter IN ('command to process') DO command

The operation of the FOR command can be summarised as...

Take a set of data Make a FOR Parameter %%G equal to some part of that data Perform a command (optionally using the parameter as part of the command). Repeat for each item of data

If you are using the FOR command at the command line rather than in a batch program, specify %parameter instead of %%parameter. FOR Parameters

The first parameter has to be defined using a single character, I tend to use the letter G.

e.g. FOR %%G IN ...

In each iteration of a FOR loop, the IN ( ....) clause is evaluated and %%G set to a different value

If this results in a single value then %%G is set = to that value and the command is performed.

If this results in a multiple values then extra parameters are implicitly defined to hold each. These are automatically assigned in alphabetical order %%H %%I %%J ...(implicit parameter definition)

For exampleFOR /F %%G IN ("This is a long sentence") DO @echo %%G %%H %%Jwill 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

Other Environment variablesEnvironment variables within a FOR loop are expanded at the beginning of the loop and won't change until AFTER the end of the DO section. The following example counts the files in the current folder, but %count% always returns 1: @echo offSET count=1  FOR /f "tokens=*" %%G IN ('dir /b') DO ( echo %count%:%%G set /a count+=1) To make this work correctly we must force the variable %count% to be evaluated during each iteration, using the CALL :subroutine mechanism:@echo offSET count=1FOR /f "tokens=*" %%G IN ('dir /b') DO (call :s_do_sums "%%G")GOTO :eof

:s_do_sums echo %count%:%1 set /a count+=1 GOTO :eofNested 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 Commands:

FOR - Loop through a set of files in one folderFOR /R - Loop through files (recurse subfolders) FOR /D - Loop through several foldersFOR /L - Loop through a range of numbersFOR /F - Loop through items in a text fileFOR /F - Loop through the output of a command

FORFILES - Batch process multiple filesGOTO - Direct a batch program to jump to a labelled lineIF - Conditionally perform a command

Equivalent Linux BASH commands:

cut - Divide a file into several columnsfor var in [list]; do - Expand list, and execute commandseval - Evaluate several commands/argumentsuntil - Execute commands (until error) while - Execute commands

FORFILES.exe (Resource Kit)

Batch process multiple files

syntax FORFILES [-pPath] [-s] [-dDate] [-mMask] [-cCommand]

key -Path : Path to search default=current folder

-s : Recurse into sub-folders

-Date : This can be +DDMMYY to select files newer than a given date (filedate >=DDMMYY) or -DDMMYY to select files older than a given date (filedate <=DDMMYY) or +DD to select files newer than DD days ago or -DD to select files older than DD days ago

-Mask : Search mask (wildcards allowed) default=*.*

-Command : Command to execute on each file. default="CMD /C Echo @FILE"

-v : Verbose report

The following variables can be used in -cCommand (must be upper case)

@FILE, @FNAME_WITHOUT_EXT,

@EXT, @PATH, @RELPATH,

@ISDIR, @FSIZE, @FDATE, @FTIME

To ECHO Hex characters in the Command use: 0xHH

Examples: To find every text file on the C: driveFORFILES -pC:\ -s -m*.TXT -c"CMD /C Echo @FILE is a text file"

To show the path of every HTML file on the C: driveFORFILES -pC:\ -s -m*.HTML -c"CMD /C Echo @RELPATH is the location of @FILE"

List every folder on the C: driveFORFILES -pC:\ -s -m*. -c"CMD /C if @ISDIR==TRUE echo @FILE is a folder"

For every file on the C: drive list the file extension in double quotesFORFILES -pc:\ -s -m*.* -c"CMD /c echo extension of @FILE is 0x22@EXT0x22"

List every file on the C: drive last modified over 100 days agoFORFILES -pc:\ -s -m*.* -d-100 -c"CMD /C Echo @FILE : date >= 100 days"

Find files last modified before 01-Jan-1995FORFILES -pc:\ -s -m*.* -d-010195 -c"CMD /C Echo @FILE is quite old!"

note:'0x22' is hex 22 - the double quote character - put these around any long filenames.Version 1.0 of FORFILES will only search for files newer than a specified date.Version 1.1 (described above) can search for file dates Newer or Older then a specified date.

version 1.1 can be downloaded from Microsoft's ftp siteAn alternative method of dealing with files older or newer than a specified date is to use ROBOCOPYRule #1: Don't sweat the small stuff. Rule #2: It's all small stuff - Dr Robert S Eliot, University of Nebraska cardiologist

Related Commands:

FOR - Conditionally perform a command several times.MUNGE - Find and Replace text within file(s)

Equivalent Linux BASH commands:

for - Expand words, and execute commandscase - Conditionally perform a commandeval - Evaluate several commands/argumentsif - Conditionally perform a commandwhile - Execute commands

FORMAT.com

Format a disk for use with Windows XP

Syntax FORMAT drive: [/FS:file-system] [/V:label] [/Q] [size] [/C]

Key /FS:file-system The file system (FAT or NTFS). The NTFS file system does not function on floppy disks.

/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.Attempting to format a 720K floppy as 1.4 Mb will give the rather unhelpful error: "The type of the file system is RAW. Invalid media or Track 0 bad - disk unusable.""Man created logic, and is therefore superior to it" - Roger Zelazny

Related Commands:

Q314878 - Choosing Cluster Size when formatting a hard driveQ252448 - How to create an NT BootdiskFloppy Disks - History from Wikipedia GDISK - Ghost Disk, a popular 3rd party tool.

Equivalent Linux BASH commands:

fdformat - Low-level format a floppy diskfdisk - Partition table manipulator for Linux

FSUTIL.exe (Win XP/2003 server)

File and Volume specific commands, Hardlink management, Quota management, USN, Sparse file, Object ID and Reparse point management

Create a hardlink

FSUTIL hardlink create <new filename> <existing filename> Eg : fsutil hardlink create c:\foo.txt c:\bar.txt

Create a new file of a specific size

FSUTIL file createnew <filename> Eg : fsutil file createnew C:\testfile.txt 1000

Set the short name for a file

FSUTIL file setshortname <filename> <shortname> Eg : fsutil file setshortname C:\testfile.txt testfile

Set the valid data length for a file

FSUTIL file setvaliddata <filename> <datalength> Eg : fsutil file setvaliddata C:\testfile.txt 4096

Set the zero data for a file

FSUTIL file setzerodata offset=<val> length=<val> <filename>

offset : File offset, the start of the range to set to zeroes length : Byte length of the zeroed range Eg : fsutil file setzerodata offset=100 length=150 C:\Temp\sample.txt

List all drives (including mapped and Subst drives)

FSUTIL fsinfo drives

Query drive type for a drive

FSUTIL fsinfo drivetype <volume pathname> Eg : fsutil fsinfo drivetype C:

Query volume information

FSUTIL fsinfo volumeinfo <volume pathname> Eg : fsutil fsinfo volumeinfo C:\

Query NTFS specific volume information

FSUTIL fsinfo ntfsinfo <volume pathname> Eg : fsutil fsinfo ntfsinfo C:

Query file system statistics

FSUTIL fsinfo statistics <volume pathname> Eg : fsutil fsinfo statistics C:

QUOTA Management

FSUTIL quota {query|disable|track|enforce } C: FSUTIL quota violations FSUTIL quota modify <volume pathname> <threshold> <limit> <user> Eg : fsutil quota modify c: 3000 5000 domain\user Find a file by user name (if Disk Quotas are enabled)

FSUTIL file findbysid <user> <directory> Eg : fsutil file findbysid scottb C:\users

File system options:

FSUTIL behavior query option FSUTIL behavior set option

FSUTIL dirty query <volume pathname> FSUTIL dirty set <volume pathname>

Where option is one of:disable8dot3allowextchardisablelastaccessquotanotifymftzone

Eg : FSUTIL behavior query disable8dot3 1 FSUTIL dirty query C:

Query a reparse point

FSUTIL reparsepoint query <filename> Eg : fsutil reparsepoint query C:\Server

Delete a reparse point

FSUTIL reparsepoint delete <filename> Eg : fsutil reparsepoint delete C:\Server

Edit an object identifier

FSUTIL objectid {query | set | delete | create}

Set sparse file properties

FSUTIL sparse queryflag <filename> FSUTIL sparse setflag <filename>

FSUTIL sparse queryrange <filename> FSUTIL sparse setrange <filename> Eg : fsutil sparse queryflag "C:\My Test.txt"

Query the allocated ranges for a file

FSUTIL file queryallocranges offset=<val> length=<val> <filename> offset : File Offset, the start of the range to query length : Size, in bytes, of the range

Eg : fsutil file queryallocranges offset=1024 length=64 C:\Temp\sample.txtTo run FSUTIL, you must be logged on as an administrator or a member of the Administrators group.

Sparse files provide a method of saving disk space for files that contain meaningful data as well as large sections of data composed of zeros. If an NTFS file is marked as sparse, then disk clusters are allocated only for the data explicitly specified by the application. e.g. The Indexing Service, stores it's catalogs as sparse files.With 8.3 filennames disabled you'll notice a performance improvement only with a large number of files (over 300,000) in relatively few folders where a lot of the filenames start with similar names. Not having 8.3 filenames available will prevent the use of old applications such as Word 2.0 and Excel 4.0 FSUTIL behavior query disable8dot3 1If 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), 3 = 37.5%, 4 = 50%The last access time attribute of NTFS can really slow performance, if you disable it, the time set will simply be the Creation Time.FSUTIL behavior set disablelastaccess 1

Some features in fsutil are reported to not work correctly under FAT or FAT32 volumes e.g. FSUTIL dirty query."You can tune a file system, but you can't tune a fish" - Sun man page for tunefs

Related Commands:

CACLS - Change file permissions CHKNTFS - Check the NTFS file system DevCon - Device Manager Command Line Utility DIRUSE - Display disk usage FDISK - Disk Format and partition SHORTCUT - Create a windows shortcut (.LNK file)WINMSD - Windows NT Diagnostics Q286164 - Hard Links and System RestoreQ249734 - Backup Software, RSM and file last access date

Equivalent Linux BASH commands:

quota - Display disk usage and limitsquotacheck - Scan a file system for disk usagequotactl - 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.

An example FTP Script to retrieve files in binary and ascii mode ::GetFiles.ftp

[User_id] [ftp_password] binary get /usr/file1.exe get file2.html mget *.jpeg ascii mget *.txt quit

To run the above script: FTP -s:GetFiles.ftp [hostname]This will connect as the user:User_id with password:ftp_password

An FTP Script to publish files in binary mode

::PutFiles.ftp

[User_id] [ftp_password] binary mput *.html cd images mput *.gif quit

To run the above script: FTP -s:PutFiles.ftp [hostname]This will connect as the user:User_id with password:ftp_passwordThis can be further automated by constructing the FTP file using a series of ECHO commands. Also you may want to put the main FTP command inside a batch script, which also CD's to the correct local folder before transferring any files.Don't forget to delete/protect the script file if it contains a valid password. "Happy is harder than money. Anyone who thinks money will make them happy, doesn't have money - David GeffenRelated commands:

COPY - Copy one or more files to another locationXCOPY - Copy files and folders REM - Add a comment (includes commenting FTP scripts)Equivalent Linux BASH commands:

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: [View, Options, File Types] however the spelling is usually different to that expected by the FTYPE command e.g. the File Type "txtfile" is displayed in the GUI as "Text Document"and "jpegfile" is displayed as "image/jpeg"

Several FileTypes can be linked to the same executable application, butone FileType cannot be linked to more than one executable application.

FTYPE file type will display the current executable program for that file type.

FTYPE without any parameters will display all FileTypes and the executable program for each.

Defining command line parameters

It is almost always necessary to supply command line parameters so that when a document is opened not only is the relevant application loaded into memory but the document itself also loaded into the application. To make this happen the filename of the document must be passed back to the application.

Command line parameters are exactly like batch file parameters, %0 is the executable program and %1 will reference the document filename

so a simple command line might be:

MyApplication.exe "%1"

If any further parameters are required by the application they can be passed as %2, %3. To pass ALL parameters to an application use %*. To pass all the remaining parameters starting with the nth parameter, use %~n where n is between 2 and 9.

The FileType should always be created before making a File Association

For example:

FTYPE htmlfile="C:\PROGRA~1\Plus!\MICROS~1\iexplore.exe" -nohomeASSOC .html=htmlfile

FTYPE pagemill.html=C:\PROGRA~1\Adobe\PAGEMI~1.0\PageMill.exe "%1"ASSOC .html=pagemill.html

FTYPE rtffile="C:\Program Files\Windows NT\Accessories\WORDPAD.EXE" "%1"ASSOC .rtf=rtffile

FTYPE word.rtf.8="C:\Program Files\Microsoft Office\Office\winword.exe" /n

ASSOC .rtf=word.rtf.8

Switching a File Association between multiple applications

If you have multiple applications that use the same file extension, the ASSOC command can be used to switch the file extension between the different FileTypes.

Deleting a FileType

Specify executable_path=nothing and the FTYPE command will delete the executable_path for that FileType. For example:FTYPE htmlfile=

Backing up your FileTypes

FTYPE >backup_types.txtASSOC >backup_ext.txt

Restoring your FileTypes from a Backup

FOR /F "tokens=* delims=" %G IN (backup_types.txt) DO FTYPE %GFOR /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 | \\serverKey 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 resourcesNET LOCALGROUP - Manage network resources FINDGRP - List the (global or local) security groups a user has joined (NT 4 Reskit)LOCAL - Display membership of local groupsGetDC - Get domain controllerCusrmgr - Console User Manager. (Win 2K ResKit)

Equivalent Linux BASH commands:

groups - Print group names a user is inid - Print user and group id's uname - Print system information

GOTO

Direct a batch program to jump to a labelled line.

Syntax GOTO label

Key label : a predefined label in the batch program. Each label must be on a line by itself, beginning with a colon.For example:

IF %1==12 GOTO s_december :: other commands:s_december

GOTO :eof

An easy way to exit a batch script file without defining a label is to specifyGOTO :eof this transfers control to the end of the current batch file.

Using a variable as a label

CHOICE goto s_routine_%ERRORLEVEL%

:s_routine_0 echo You typed Y for yes

:s_routine_1echo You typed N for no

Skip commands by using a variable as a :: comment (REM)

In this example the COPY command will only run if the parameter "Update" is supplied to the batch

@echo off setlocal IF /I NOT %1==Update SET _skip=::

%_skip% COPY x:\update.dat %_skip% echo Update applied ...If Command Extensions are disabled GOTO will no longer recognise the :EOF label"It's just a jump to the left... and then a step to the right.." - The Time Warp Related Commands:

IF - Conditionally perform a commandCALL - Call one batch program from another

Equivalent Linux BASH commands:

case - Conditionally perform a command

HELP

Online help for MS Windows - most commands will give help when run with /? or -? (COMMAND /? or COMMAND -?)

GUI Help is available from START - Help or by running the help files directly:

C:\WINDOWS\help\ntcmds.chmC:\WINDOWS\help\ntdef.chmC:\WINDOWS\help\ntchowto.chmC:\WINDOWS\help\nthelp.chmC:\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.Equivalent Linux BASH commands:

man pages

HFNETCHK (Shavlik Technologies)

Network Security Hotfix Checker.

Syntax hfnetchk.exe [options]

Options [-h hostname] NetBIOS computer name(s) to scan. default=local host. separate multiple host name entries with a comma,

[-fh hostfile] The name of a file containing NetBIOS computer names to scan

[-i ipaddress] The IP address of computer(s) to scan. separate multiple entries with a comma,

[-fip ipfile] The name of a file containing IP addresses to scan. (Maximum 256 addresses per file)

[-r range] An IP address range to be scanned, -r start_ip_address-end_ip_address

[-d domainname] A domain name to scan. All computers in the domain are scanned.

[-n] All computers on the local network are scanned. All computers in all domains are scanned.

[-b] Scan only for `baseline critical` patches

[-history level] Display explicit install history - ignoring supersedences and roll-up patches This option is not normally required

[-t threads] The number of threads used to run the scan. (1 to 128). Default = 64. More threads may increase the speed of the scan.

[-o output] The output format: tab = tab delimited format. wrap = word-wrapped format.(default) When scanning more than 255 hosts you must use tab output. tab is useful for redirecting the screen output to a text or spreadsheet file.

[-x datasource] The XML hotfix data. An XML file name, compressed XML .cab file, or URL The default file is the Mssecure.cab file from the Microsoft Web site.

Running Hfnetchk without the -x switch, the XML file Mssecure.xml is downloaded from Microsoft.com. store the XML file in the same folder as Hfnetchk.exe or host on a Web server or file server. After you download the file, you can run future scans with the -x switch

[-z] Skip registry checks (file checks only)

[-v] Verbose - display the reason a hotfix failed when combined with -z will display any missing files.

[-s 1] Suppress NOTE warnings [-s 2] Suppress both NOTE and WARNING messages

[-nosum] Skip checksum validation for the hotfix files.

[-u username] The username to use when scanning a local or remote computer(s) [-p password] Password for above (sent via challenge-response authentication)

[-f outfile] The name of a file to store the results.

[-about] About info

-? Menu of optionsYou can use the switches above in combination - so a single command can scan a range of IP addresses plus a list of specific machines.

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

Related Commands:Q303215 - Download HFNETCHK (plus examples)HFNETCHK - Microsoft HfNetChk Newsgroup.Q296861 - Use QCHAIN to install multiple hotfixes with only one reboot.Q310747 - System File Checker (Sfc.exe)

Equivalent Linux BASH commands:

rpm - Remote Package Manager

IF

Conditionally perform a command.

File syntax IF [NOT] EXIST filename command

IF [NOT] EXIST filename (command) ELSE (command)

String syntax IF [/I] [NOT] item1==item2 command

IF [/I] item1 compare-op item2 command

IF [/I] item1 compare-op item2 (command) ELSE (command)

Error Check Syntax IF [NOT] DEFINED variable command

IF [NOT] ERRORLEVEL number command

IF CMDEXTVERSION number command

key

item : May be a text string or an environment variable a variable may be modified using either Substring syntax or Search syntax

command : The command to perform

NOT : perform the command if the condition is false.

== : perform the command if the two strings are equal.

/I : Do a case Insensitive string comparison.

compare-op : may be one of EQU : equal NEQ : not equal

LSS : less than < LEQ : less than or equal <=

GTR : greater than > GEQ : greater than or equal >=

This 3 digit syntax is necessary because the > and < are recognised as redirection symbolsIF EXIST filename will return true if the file exists (this is not case sensitive).

IF ERRORLEVEL statements should be read as IF Errorlevel > OR = numberi.e.IF ERRORLEVEL 1 will return TRUE for an errorlevel of 1 or greater.

To put that another way, ERRORLEVEL will return 0 on the successful completion of a command, however IF ERRORLEVEL 0 will also return true even if the errorlevel is 196! Examples: IF EXIST C:\install.log (echo complete) ELSE (echo failed) IF DEFINED _department ECHO Got the department variable IF DEFINED _commission SET /A _salary=%_salary% + %_commission% IF CMDEXTVERSION 1 GOTO start_process

IF ERRORLEVEL EQU 2 goto sub_problem2

Does %1 exist?

To test for the existence of a command line paramater - use empty brackets like this

IF [%1]==[] ECHO Value MissingorIF [%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)Testing Numeric values Do not use brackets or quotes when comparing numeric values e.g. IF (2) GEQ (15) echo "bigger" orIF "2" GEQ "15" echo "bigger"These will perform a character comparison and will echo "bigger" however the commandIF 2 GEQ 15 echo "bigger" Will perform a numeric comparison and works as expected - notice that this behaviour is exactly opposite to the SET /a command where quotes are required. Any test made using the compare-op syntax will always be a "string" comparison,so when comparing numbers note that "026" > "26" Wildcards

Simple wildcards are not supported by IF, so ==SS6* will not match SS64

The workaround is to spoof a wildcard using SET to retrieve the substring SET _part_name=%COMPUTERNAME:~0,3% IF NOT %_part_name%==SS6 GOTO they_matchedPipes: When piping commands, the expression is evaluated from left to right, so IF... | ... is equivalent to (IF ... ) | ... you can use the explicit syntax IF (... | ...) Setting an ERRORLEVELIt is possible to create a string variable called %ERRORLEVEL% (user variable)if present such a variable will prevent the real ERRORLEVEL (a system variable) from being used by commands such as ECHO and IF. If you want to deliberately raise an ERRORLEVEL in a batch script use the command "COLOR 00" or simply SET MyError=YES To test for the existence of a user variable use SET errorlevel, or IF DEFINED ERRORLEVEL If Command Extensions are disabled IF will only support direct comparisons: IF ==, IF EXISTS, IF ERRORLEVEL also the system variable CMDEXTVERSION will be disabled. You see things; and you say 'Why?' But I dream things that never were; and I say 'why not?' - George Bernard Shaw Related commands:

Conditional execution syntax (AND / OR)SET - Display, or Edit Windows NT environment variablesECHO - Display message on screenIFMEMBER - NT Workgroup member (Resource kit)SC - Is a Service running (Resource kit)

Equivalent Linux BASH commands:

case - Conditionally perform a commandif - Conditionally perform a commanduntil - Execute commands (until error) while - Execute commands

IFMEMBER (Resource Kit)

Count the NT Workgroups that the current user is a member of.

Syntax IFMEMBER [options] WorkGroup [ WorkGroup2 WorkGroup3...]

Options:

/verbose or /v : print all matches. /list or /l : print all groups user is a member ofThe %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 normal in that%ERRORLEVEL% = 1 = Successwith most other NT commands %ERRORLEVEL% = 1 = Fail/Error

The best way to utilise IFMEMBER is through conditional execution...

IFMEMBER Administrators || ECHO Error is 1 so [%Username%] is in Admin_WG

IFMEMBER Administrators && ECHO Error is 0 so [%Username%] is NOT in Admin_WG "The euro will raise the citizens' awareness of their belonging to one Europe more than any other integration step to date" - Gerhard Schroeder

Related Commands:NET GROUP - add or remove a user from a workgroupSHOWMBRS - List the members of an NT WorkgroupSHOWACCS - Show access profile (Windows 2000) GRPTEST - SMS support tools - enumerate group membership for a user account.Cusrmgr - Console User Manager. (Win 2K ResKit) Joeware.net - MemberOf.exe - Like IFMEMBER but able to handle nested AD groups

IPCONFIG

Configure IP.

Syntax

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

## = New option in Win 2K/XPIf 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 KellerRelated Commands:

BROWSTAT - Get domain, browser and PDC info NETSTAT - Display networking statistics (TCP/IP) NETSH - Configure interfaces, routing protocols, filters, routes, RRAS PATHPING - IP trace utility PING - Test a network connection

Q192064 - Locate multiple preferred logon serversQ813878 - How to block specific network protocols and ports.Q313190 - Use IPSec IP Filter ListsThe Inq/Jon Honeyball - Routing to harden machines against attackNTFAQ - How to disable automatic private IP addressing (2K and XP)

Equivalent Linux BASH commands:

ping - Test a network connectiontrace - Find the IP address of a remote host.

KILL (Resource kit)

Remove a running process from memory.

Syntax KILL [option] process_id KILL [option] task_name KILL [option] window_title

Option -f Force process killNote: Kill -f basically just nukes the process from existence, potentially leaking a lot of memory and losing any data that the process hadn't committed to disk yet. It is there for worst case scenarios - when you absolutely must end the process now, and don't care whether proper cleanup gets done or not.

In WindowsXP, KILL is replaced with the superior TASKKILL - Allowing you to specify a remote computer, different user account etc - for more details run TASKKILL /?

If you're going to tell people the truth, you'd better make them laugh. Otherwise they'll kill you. - George Bernard Shaw

Related Commands:

PsKill - Kill processes by name or process IDPsSuspend - Suspend a processesTASKKILL - Kill a local or remote task (XP)PsList List detailed information about processesNET - Stop a service from runningNET FILE - Force an open file to closeRKILL - Remote Kill (Resource Kit) view or kill processes on a remote server

Q171773 - Kill a background process Q178893 - Terminate an Application "Cleanly" in Win32 Q197155 - How to Kill an Orphaned Process

Equivalent Linux BASH commands:

kill - Kill a process

LABEL

Edit a disk label.

Syntax LABEL [drive:][label]The disk label is never referred to by other batch commands, it's just for human recognition. e.g. as a reminder of which floppy disk is actually in the machine.

The maximum length is 11 characters (spaces allowed)This is not to be confused with the drive description held in the registry.

Example

LABEL A: My work disk

"A name is a label, and as soon as there is a label, the ideas disappear and out comes label-worship and label-bashing" - Richard Bach

Related Commands:

VOL - display the volume labelQ159865 - How to distinguish a physical disk device (registry settings)

Equivalent Linux BASH commands:

hostname - Print or set system name uname - Print system information

LOCAL (Resource kit)

Display membership of local groups on remote servers or remote domains.

Syntax LOCAL group_name domain_name | \\serverKey group_name The local group. domain_name A network domain. server A network server.Examples:

Local "Power Users" Scotland

Displays the members of the group 'Power Users' in the Scotland domain.

Local Administrators \\9G_Server

Displays the members of the group Administrators on server 9G_Server."This is a local shop for local people, there’s nothing for you here" - league of gentlemen

Related commands

NET GROUP - Manage network resourcesNET LOCALGROUP - Manage network resourcesFINDGRP - List the (global or local) security groups a user has joined (NT 4 Reskit)GLOBAL - Display membership of global groups. GetDC - Get domain controllerCusrmgr - Console User Manager. (Win 2K ResKit)

Equivalent Linux BASH commands:

groups - Print group names a user is inid - Print user and group id's uname - Print system information

LOGEVENT (Resource kit)

Write text to the event log (event viewer)

Syntax logevent [-m \\MachineName] [options] "Event Text"Options -s Severity one of (S)uccess (I)nformation (W)arning

(E)rror (F)ailure

-c Category A Number between 0 and 65536 This can be used to Filter the event log view (default = "none")When a fellow says, "It ain't the money but the principle of the thing," it's the money. - Kim HubbardRelated

EVENTCREATE - Create a custom event log message (Windows XP)EVENTQUERY - Read an event log message (Windows XP)EVENTTRIGGERS - display and configure Event Triggers (Windows XP) NET SEND - Manage network resources (Popup message)WshShell.LogEvent - Log an item in the Event log WMIC NTEVENTLOG - WMI access to the event logQ131008 - Use eventlog from a batch file

LOGOFF.exe (Resource Kit)

Log a user off.

Syntax LOGOFF [/f] [/n]

Key /f Force running processes to close, but will ask for user confirmation. The user will not be asked to save unsaved data.

/n Force running processes to close without confirmation. The user will be prompted to save unsaved data. By default LOGOFF will ask for user confirmation and prompt to save unsaved data.

Windows XP includes the SHUTDOWN command that can now logoff a user."The man who is tired of London is tired of looking for a parking space" - Paul Theroux

Related Commands:

SHUTDOWN - Shutdown the computerpsShutdown - SysInternals JSIFAQ Tip 9130 - log off user after n minutes of inactivity

LOGTIME.exe (Resource kit)

Create logtime.txt and adds the date, time and a message

Syntax LOGTIME text_string

Key text_string : The message to add to the log file. The date is stored in the US mm/dd/yy format (NT 4.0)

Sample batch file:

LOGTIME "begin import program" import.exe LOGTIME "end import program"

An alternative command isECHO. | DATE | FIND /i "current">>C:\Install_log.txt

"You can always tell that an organisation is on the skids when it changes it's name, and pays a lot of money for consultants to invent some ghastly new corporate identity" - Baroness Helena Kennedy

Related Commands:

ECHO - Display message on screenDATE /T - Display or set the dateTOUCH - Change file timestamps Timethis - Time how long it takes the system to run a command. (Win 2K ResKit) Uptime - Time since last reboot. (Win 2K ResKit)

Equivalent Linux BASH commands:

echo - Display message on screenselect - Accept keyboard input

MAPISEND (Back Office/Exchange Resource kit)

Send email from the command line.

Syntax MAPISEND -u "profile" -p password -r recipient -s "subject" -m text message [options]

MAPISEND -u "profile" -p password -r recipient -s "subject" -t text_file [options]

options -i interactive login (prompts for profile and password) -c cc: list

-f File Attachment - path and file name(s) -v generates verbose output (an 8 line summary of the message)

"profile" is the profile name (user mailbox) of sender"subject" is the subject line "recipient" is one or more recipient(s) If more than one recipient - separate with ';' these must not be ambiguous in the default address book.Mapisend requires MAPI - i.e the MS Outlook client needs to be installed. Examplesmapisend -u "MS Exchange Settings" -p MyPassword -r [email protected] -s "Subject" -m "Test message text"

mapisend -u "MS Exchange Settings" -p MyPassword -r [email protected] -s "Subject" -t c:\MyMail.txt >> c:\mail.log"The new electronic interdependence re-creates the world in the image of a global village" - Marshall McLuhan

Related Commands:

Q290499 - programmatic access to Outlook emailBLAT (freeware) - Send email via SMTP (avoids the need to install MS Outlook)

On machines with a web browser installed the command START mailto:[email protected] send email but requires the user to complete and send the message.

Equivalent Linux BASH commands:

sendmail

MEM

Display memory usage.

Syntax MEM MEM /C MEM /D MEM /P

Key /P List programs in memory with the memory address and size of each

/D List Programs(as /P) and also Devices

/C List programs in conventional memory and

list programs in upper memoryMEM will only display details about the current CMD shell environment, programs running in a separate shell (or WIN32 programs) will not be listed - so it won't tell you anything about total memory usage.

"The palest ink is better than the sharpest memory" - Chinese proverb

Related Commands:

CLEARMEM (Resource Kit) - Clear Memory LeaksWINMSD - Windows NT Diagnostics (including Physical Memory)GUI Task Manager - for all program details including Win32 applications.TLIST - Task List Q184419 - DisablePagingExecutive (use when >500M RAM is available) Q126962 - How to increase desktop heap memory for non-interactive processes/3GB Startup Switch for Windows 2003

Equivalent Linux BASH commands:

free -t - Display a summary of current memory usage and availability.

MD

Make Directory - Creates a new folder.

Syntax MD [drive:]path

Key The path can consist of any valid characters up to the maximum path length availableYou should avoid using the following characters in folder names - they are known to cause problems

© ® " - & ' ^ ( ) and @

also many extended characters may not be recognised by older 16 bit windows applications.

The maximum length of a full pathname (folders and filename) under NTFS or FAT is 260 characters.

Folder names are not case sensitive, but only folder names longer than 8 characters will always retain their case, as typed.

For ExampleC:\temp> MD MyFolder

Make several folders with one commandC:\temp> MD Alpha Beta Gammawill create

C:\temp\Alpha\C:\temp\Beta\C:\temp\Gamma\

Make an entire path MD creates any intermediate directories in the path, if needed. For example, assuming \utils does not exist then: MD \utils\downloads\Editor is the same as: md \utils cd \utils md downloads cd downloads md Editor

for long filenames include quotes

MD "\utils\downloads\Super New Editor" You cannot create a folder with the same name as any of the following devices:CON, PRN, LPT1, LPT2 ..LPT9, COM1, COM2 ..COM9This limitation ensures that redirection to these devices will always work.

If you plan to copy data onto CDROM avoid folder trees more than 8 folders deep

MKDIR is a synonym for MD

"We are American at puberty. We die French" - Evelyn Waugh

Related Commands:

RD - Delete folders or entire folder treesLinkd - link an NTFS directory to a target object. (Win 2K ResKit)

Equivalent Linux BASH commands:

mkdir - Create new folder(s)

MODE

Mode is an all purpose configuration command, used without parameters, MODE displays the status of all devices installed on your system.

Devices

Show the status of all devices: (Typically COM1, COM2, LPT1, CON)MODE

Show the status of a specific device:MODE [device]

To additionally show the status of any redirected parallel printer:MODE [device] [/STATUS]

CMD Prompt window size

Change the CMD prompt screen size/buffer Number of cols(characters) wide and Number of lines deep

MODE CON[:] [COLS=c] [LINES=n]

Keyboard

Set the keyboard typematic rate, the rate at which a character is repeated when you hold down the key. MODE CON[:] [RATE=r DELAY=d]

Printing

To redirect output from a parallel port (PRN, LPT1, LPT2, or LPT3) to a serial port(COM1, COM2, COM3, etc). You must be a member of the Administrators group to redirect printing.

To configure a parallel printer port (PRN, LPT1, LPT2, or LPT3): MODE LPTn[:]=COMm[:]

To setup the parameters for a serial port (* see Start, Help, Commands for more on this). MODE COMm [options*]

Configure a printer connected to a parallel printer port. mode LPTn[:] [c][,[l][,r]] mode LPTn[:] [cols=c] [lines=l]This allows you to configure a line printer connected to a parallel printer port.

International Settings

Change the current code page: MODE CON[:] CP SELECT=yyy

Display the current Code page: MODE CON[:] CP [/STATUS]

Examples:

MODE CON:cols=80 lines=25

"The dogma of the ghost in the machine" - Gilbert Ryle

Related commands:

NET - manage network resourcesCHCP - Display or change device settings

Equivalent Linux BASH commands:

lpc - Line printer control program printcap - printer capability databasePROMPT_COMMAND - environment variablescreen - Terminal window manager

MORE

Display output one screen at a time. MORE can be used to run any executable command (or batch file) and pause the screen output one screen at a time. MORE can also be used to TYPE the contents of any file to the screen.

Syntax command | MORE [/E [/C] [/P] [/S] [/Tn] [+n]]

MORE [/E [/C] [/P] [/S] [/Tn] [+n]] < Pathname

MORE /E [/C] [/P] [/S] [/Tn] [+n] [Pathname(s)]

Key command : Any executable command or batch file

Pathname : The file to be displayed. (if more than one separate with spaces)

/E : Enable extended features

/E /C : Clear screen before displaying page

/E /P : Expand FormFeed characters

/E /S : Squeeze multiple blank lines into a single line

/E /Tn : Expand tabs to n spaces (default 8)

/E +n : Start displaying the first file at line nYou can create an environment variable called %MORE% and use this to supply any of the above switches.When MORE is used without any redirection symbols it will display the % complete e.g.

MORE /E myfile.txt--More (17%) --

If extended features are enabled, (/E) the following keystrokes can be used at the -- More -- prompt: <space> Display next page <return> Display next line Q Quit P n Display next n lines S n Skip next n lines F Display next file = Show line number ? Show help line "less is more" - Ludwig Mies van der Rohe

Related commands:TYPE - display filesECHO - display variablesList - Text Display and Search Tool (Win 2K ResKit)

Equivalent Linux BASH commands:

more - Display output one screen at a timeless - Display output one screen at a time

MOUNTVOL (Windows 2000)

Create, delete or list a volume mount point.

Syntax MOUNTVOL [drive:]path option

Options

path : An existing NTFS folder where the mount point will reside.

VolName : The volume name that is the target of the mount point.

/D : Remove the volume mount point from the specified folder.

/L : List the mounted volume name for the specified folder."The shortest and surest way of arriving at real knowledge is to unlearn the lessons we have been taught, to mount the first principles, and take nobody's word about them" - Henry BolingbrokeRelated commands:

WINDISK - NT Disk AdministratorBootCFG - Edit Boot.ini settings.

Equivalent Linux BASH commands:

mount - Mount a file system

MOVE

Move a file from one folder to another

Syntax MOVE [options] [Source] [Target]

Key source : The path and filename of the file(s) to move.

target : The path and filename to move file(s) to.

options: (Windows 2000 only) /Y Suppress confirmation prompt.

/-Y Enable confirmation prompt.

Both Source and Target may be either a folder or a single file.The source may include wildcards (but not the destination). Under Windows 2000 the default action is to prompt on overwrites unless the 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=/YThis will turn off the prompt in Win2000 and will be ignored by NT4 (which overwrites by default). Examples:

In the current folderMOVE oldfile.wp newfile.doc

Full path specifiedMOVE g:\department\oldfile.wp "c:\Files to Convert\newfile.doc"

Specify the drive and filename (assumes the current folder on both drives is correct)MOVE a:oldfile.wp c:newfile.doc

Specify source only (will copy the file to current folder, keeping the same filename)MOVE g:\department\oldfile.wp

Quiet move (no feedback on screen)MOVE oldfile.wp newfile.doc >nul"If it moves, tax it. If it keeps moving, regulate it, and if it stops moving, subsidize it" - Ronald Reagan

Related Commands:

COPY - Copy one or more files to another locationROBOCOPY /MOVE - Robust File and Folder Copy XCOPY - Copy files and foldersMV - Copy in-use files REN - Rename a file or files. Cachemov - Offline Files Cache Mover. (Win 2K ResKit)

Equivalent Linux BASH commands:

mv - Move or rename files or directories

MOVEUSER.exe (Resource Kit)

Move a user account into a domain or edit an NT username.

Syntax

MOVEUSER [DOMAIN/]user1 [DOMAIN/]user2 [/c:computer] [/k] [/y]

Key:

user1 The existing user (who has a local profile) Specify domain users in 'DOMAIN/user' format or just 'user' for a local account.

user2 The user acount that will inherit the user1 profile. This account must already exist. Specify domain users in DOMAIN/user format specify only user for local accounts.

/c:computer The computer on which to make the changes.

/k Keep user account user1 (only applies to local users)

/y Overwrite an existing profile for user2.NotesTo use MOVEUSER, you must be logged in with admin rights to create and modify user accounts on both the source and target machine.MOVEUSER is particularly useful for moving local user accounts into a domain.This command was first available in the Windows 2000 Server Resource kit, it's also in the 2003 resource kit. MOVEUSER does not run on NT 4.0ExamplesMOVEUSER fred MyDomain\newfredOr if the account 'fred' is on the remote PC called 'wks0123' MOVEUSER fred MyDomain\newfred /c:\\wks0123 "You don't sew with a fork, so I see no reason to eat with knitting needles" - Miss Piggy, on eating Chinese Food

Related:

Q838191- RestrictRemoteClients registry keys for MOVEUSER under XP sp2 SHUTDOWN - Shutdown the computerADMT - Active Directory Migration Tool (domain to domain)

MSG.exe

Send a pop-up message to a user.

Syntax MSG username [options] [message]

MSG sessionname [options] [message]

MSG sessionid [options] [message]

MSG @filename [options] [message]

MSG * [options] [message]

Options

/SERVER:servername The server to contact (default is current).

/TIME:seconds Time delay to wait for receiver to acknowledge msg.

/V Verbose, display extra information.

/W Wait for response from user, useful with /V.

If no message text to send is specified, MSG will prompt for it(also reads from stdin)

@filename identifies a file containing a list of usernames,sessionnames or sessionids to send the message to.

* will send the message to all sessions on the server. e.g. use this for Terminal Server/Citrix shutdown messages.# And these children that you spit on, As they try to change their worldsAre immune to your consultations, they're quite aware of what they're going through # - David BowieRelated Commands:

ECHO - Display message on screenTYPE - Display the contents of a text file

Equivalent Linux BASH commands:

echo - Display message on screen

MSIEXEC

Microsoft Windows Installer.

Syntax Install MSIEXEC /i package options

Uninstall MSIEXEC /x package options

Advertise to current user MSIEXEC /ju package options [/t Transform_List | /g LanguageID]

Advertise to all users MSIEXEC /jm package options [/t Transform_List | /g LanguageID]

Administrative install - install on the network. MSIEXEC /a package

Apply a patch to an installed Admin image MSIEXEC /p patchPKG /a package

Options: /fp fix - replace missing files /fo fix - replace Older files /fe fix - replace older or Equal date files /fd fix - replace Different version files /fc fix - replace files based on Checksum differences /fa fix - replace All files /fu fix - rewrite HKCU registry /fm fix - rewrite HKLM registry /fs fix - recreate shortcuts /fv fix - rewrite local cache from source /l* Logfile Log Everything (not Verbose) /l*v Logfile Log Everything Verbose /lv Logfile Log Verbose /le Logfile Log All error messages /lw Logfile Log Non-fatal warnings /li Logfile Log Status messages /la Logfile Log Startup actions /lr Logfile Log Actions /lu Logfile Log User requests /lc Logfile Log User Interface (UI) parameters /lm Logfile Log memory use /lp Logfile Log Terminal properties /l+ Logfile Append to an existing log file. /l! Logfile Clear an existing log file. /q , /qn No UI. /qb Basic UI. /qb! Basic UI with no cancel button. /qr Reduced UI. A modal dialog box is displayed at the end of the install.

/qf Full UI. A modal dialog box is displayed at the end of the install. /qn+ No UI. However, a modal dialog box is displayed at the end of the installation. /qb+ Basic UI. A modal dialog box is displayed at the end of the installation. If you cancel the installation, a modal dialog box is not displayed. /qb- Basic UI with no modal dialog boxes. /y module Register a DLL - only use for registry information that cannot be added using the registry tables of the .msi file. /z module UnRegister a DLL - only use for registry information that cannot be removed using the registry tables of the .msi file.Windows installer versions

Windows NT can support version 1.1 or version 1.2Windows 2K includes version 1.1Windows XP Sp1 /Server 2003 include version 2.0Windows XP SP2 includes version 3.0

Updates to msiexec can be downloaded from MSDN.

"People don't resist change. They resist being changed!" - Peter Senge.

Related commands:

CHANGE - Change Terminal Server session properties REGSVR32 - Register or unregister a DLLRunDll32 - Uninstall DLL's e.g. MS JavaQ230781 - Msiexec command-lineQ310747 - System File Checker (Sfc.exe) InstallSite.org - Installer and Setup resources

Equivalent Linux BASH commands:

RPM - Rpm Package Manager

MSINFO32 (Windows 2000 or MS Office)

Windows NT diagnosticsReports: Memory use, Drivers, DLL versions, Audio,Video and Print settings.

Syntax MSinfo32 <options>

Options

/c List the version, date, and build of each DLL in a user-specified folder and determine whether it's loaded in memory. /msinfo_file Open the specified .nfo or .cab file /nfo or /s Output an .nfo file with the specified file name /report Output a text file /computer Get details from a remote computer /categories Display or output the specified categories /category Set focus to a specific category at startup The GUI interface will open if no options are specified.for example:

msinfo32 /c [My DLL’s] c:\mydir(Be sure to include the square brackets.)

Note that early versions of MSinfo do not support all the switches listed above.

MSinfo is typically started from Help,About rather than the command line, if not in the system path, MS info can usually be found in:C:\Program Files\Common Files\Microsoft Shared\MSInfo

Note that generation of the text file can take some time, depending on the complexity of the system.

If you have problems getting MSInfo to run, check permissions on the following key: HKLM\SOFTWARE\Microsoft\Shared Tools\MSInfo\

Under the W2K command-line you can run WINMSD /? rather than Msinfo32 /?

"Education is not the filling of a pail, but the lighting of a fire." W. B. Yeats

Related Commands:

WINMSDP - Windows NT Diagnostics IIQ255713 - Windows 2000 Command-Line Parameters for Msinfo32Microsoft online DLL version Database

MSTSC

Terminal Server Connection, RDP (Remote Desktop Protocol)

Syntax MSTSC option MSTSC /Edit"ConnectionFile" MSTSC /migrate

Options ConnectionFile The name of an RDP file for connection /v:<server[:port]> Terminal server (or PC) to connect to /console Connect to the console of a server /f Start in Full Screen mode /w:width Width of the RDP screen /h:height Height of the RDP screen /edit Open the RDP file for editing /migrate Migrate a Client connection file to RDPThe /console option only works when connecting to an Windows XP Professional or Windows Server 2003 computer.When connected to a remote desktop, the key combination Ctrl-Alt-END will send Ctrl-Alt-Del to the remote client. Examples:

MSTSC /v:MyServer /f /console

MSTSC /v:127.0.0.1 /w:1024 /h:768

MSTSC /v:MyServer /w:800 /h:600

MSTSC /edit filename.rdp On the Windows XP CD, under \SUPPORT\TOOLS you'll find MSRDPCLI.exe. This is the setup for use with 9.x/2000 machines.

"Ignorance is preferable to error; and he is less remote from the truth who believes nothing, than he who believes what is wrong" - Thomas Jefferson

Related Commands:

MAPISEND - Send email from the command lineRMTSHARE - Share a folder or printerSHORTCUT - Create a windows shortcut SHUTDOWN - Shutdown the computer/Log off a userEquivalent Linux BASH commands:vncconnect - Connect to a VNC server

MUNGE.exe (NT4 Resource Kit)

Find and Replace text within file(s) Munge.exe has been dropped from the Resource Kit in Windows 2000 and above.

Syntax MUNGE ScriptFile [options] FilesToMunge...

Key ScriptFile : A text file containing the strings to Find & Replace FilesToMunge : One or more files to be changed (may use wildcards)

Editing options -q : Query only - don't actually make changes. -e : Query only - display entire line for each match -o : Query only - just display filename once on first match -k : Case - Case sensitive scriptFile -r : Recurse into subfolders -m : Collapse multiple carriage returns into one -@ : Remove null characters -n : Neuter - Surround all strings with TEXT() -L : Literals - Dont process any quoted text (excludes comments) -l : Literals - Dont process any quoted text (includes comments too)

Display options

-i : Just output summary of files changed at end -c : If no munge of file, then check for cleanlyness -v : Verbose - show files being scanned

Destination options

-t : Don't create .bak files -a : Use ATTRIB -r command for files that are readonly -s : Use OUT command command for files that are readonly (OUT is not a standard documented NT command!) -f : Use -z flag for SLM OUT command -u undoFileName : Generate an undo MUNGE script file for the changes made -z : Truncate file after a Ctrl-Z character

Each line in the ScriptFile should take one of the following 3 forms:

oldName newName "oldString" "newString" -F .Ext Name. Name.Ext

In the script file -F may be used to restrict the files processed by MUNGE when FilesToMunge is a wildcard.

-F [Name].[Ext] Munge will only search for a complete string delimited with spaces - it won't match part of a string. Munge does not support long file names.Munge does not work reliably for files greater than 2 Mb.

Munge will not read unicode text. When FilesToMunge (on the command line) is a specific file then this filename will override any -F setting.

When MUNGE is used with a wildcard to modify multiple files then you must specify -F in the scriptfile.

MUNGE will create a backup file called .BAK, for this reason do not process files that have a .BAK extension unless you specify -t (dont create backup)

Example: MUNGE myChanges.ini FileToMunge.txtWhere myChanges.ini contains the following :::::::::::: -F FileToMunge.txt "Driver32=C:\WINNT\System32\odbc16.dll" "Driver32=C:\WINNT\System32\odbc32.dll" "Driver32=C:\WINNT\System32\jct16.dll" "Driver32=C:\WINNT\System32\jct32.dll" ::::::::::::Notice that the whole string has to be spelled out even though only a small part is being changed. Watch out for trailing spaces.

In the onscreen feedback a TOKEN means your script may replace one word with another, while a LITERAL STRING means your script will replace one "Quoted String" with "Another Quoted string"

Munge script files can contain multiple string replacements - these will be applied in one pass only. In other words if you replace A with B and also replace B with C. Then A will not be changed into C (unless you run the MUNGE command twice.

"I understand that change is frightening for people, especially if there's nothing to go to. It's best to stay where you are. I understand that." - Princess Diana

Related:

FOR - Conditionally perform a command several times. FIND - Search for a text string in a file FINDSTR - Search for strings in files

QGREP - Search file(s) for lines that match a given patterngawk for Windowssed for Windows (Docs)ReplaceEm - GUI Freeware InfoRapid - Search & Replace Freeware Equivalent Linux BASH commands:

gawk - Find and Replace text within file(s)sed - Stream Editor - Find and Replace text within file(s) tr - Translate, squeeze, and/or delete characters

MV.exe (Resource Kit)

Move File - Copy a file to another location even if the file is in use (Locked)

Syntax MV /x /d source destination

Key The first file name is the file to be copied and the second the destination pathname.

/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 Commands:

INUSE - updated file replacement utility (may not preserve file permissions)COPY - Copy one or more files to another locationMOVE - Move a file from one folder to anotherCachemov - Offline Files Cache Mover. (Win 2K ResKit)

Equivalent Linux BASH commands:

mv - Move or rename files or directories

NET.exe

The NET Command is used to manage network resources as follows:

Manage ServicesNET START, STOP, PAUSE, CONTINUE

Connect to a file/print Share (Drive Map) NET USE

Create/view file/printer SharesNET SHARE, VIEW, FILE, SESSIONS

Manage Network Print jobs and Network TimeNET TIME, PRINT

SecurityNET ACCOUNTS, USER, GROUP, LOCALGROUP

Network MessagingNET NAME, SEND

HelpNET HELP, HELPMSG

Network configurationNET COMPUTER, CONFIG_WORKSTATION, CONFIG_SERVER, STATISTICS_WORKSTATION, STATISTICS_SERVER

When you use NET commands in a batch file, you can use the Y or N switch to unconditionally answer Yes or No to questions returned by the Net command

"The white man knows how to make everything but he does not know how to distribute it" - Sitting Bull

Related commands:

CON2PRT - Connect or disconnect a PrinterGLOBAL - Display membership of global groupsLOCAL - Display membership of local groupsMODE - Configure a system deviceNETDOM - Domain Manager SC - Service Control

Q149427 - Change Password from the CMD prompt

Equivalent Linux BASH commands:

groups - Print group names a user is inhostname - Print or set system name id - Print user and group id'slogname - Print current login name mount - Mount a file systemram - ram disk device uname - Print system informationusers - Print login names of users currently logged inwho - Print who is currently logged in

NETDOM.exe (NT Resource Kit supplement 2, Win2K Support Tools)

Domain Manager - a whole bag of network management tools in one tool.

The syntax for NETDOM varies considerably between versions

In summary you can

/JOINDOMAIN /JOINWORKGROUP /Add /DELETE a computer account (including BDC and resource domain computer accounts) /Query the secure channel of a resource domain or BDC /List the resource domain/BDCs in a domain /Edit trust relationships /Query the computer role of any domain member or BDC.

In Win2K only Move a workstation or member server (computer) to a new domain Rename/Reset a workstation or member server Verify or reset and synchronize TIME within a domain Resynchronize 'out of synch' domain controller`s Run NETDOM /? for full syntax - or look in the supplied WinHelp file.

"Between knowledge of what really exists and ignorance of what does not exist lies the domain of opinion. It is more obscure than knowledge, but clearer than ignorance" - Plato

Related Commands:

Q150493 - Join a Domain from the command line Q104558 - Change NT Server NameQ139055 - Change Computer Name without changing DNS Q222525 - Create Computer Account

NETSH (Win2k Resource Kit, standard command in XP)

Configure Interfaces, Routing protocols, Filters, Routes, Routing & remote access.

Syntax NETSH [-r router name] [-a AliasFile] [-c Context] [Command | -f ScriptFile]

Key context may be any of: DHCP, ip, ipx, netbeui, ras, routing, autodhcp, dnsproxy, igmp, mib, nat, ospf, relay, rip, wins.

Under Windows XP the available contexts are: AAAA, DHCP, DIAG, IP, RAS, ROUTING, WINS

To display a list of commands that can be used in a context, type the context name followed by a space and a ? at the netsh> command prompt. e.g.

netsh> routing ?

command may be any of:

/exec script_file_name Load the script file and execute commands from it.

/offline Set the current mode to offline. changes made in this mode are saved, but require a "commit" or "online" command to be set in the router.

/online Set the current mode to online. Changes in this mode are immediately reflected in the router.

/commit Commit any changes made in the offline mode to the router.

/popd Pop a context from the stack.

/pushd Push current context onto the stack.

/set mode [mode =] online | offline Set the current mode to online or offline.

/abort Discard changes made in offline mode.

/add helper DLL_name Install the helper .dll file in netsh.exe.

/delete helper .dll file name Remove the helper .dll file from Netsh.exe.

/show alias list all defined aliases. /show helper list all top-level helpers. /show mode show the current mode.

/alias List all aliases.

/alias [alias_name] Display the string value of the alias.

/alias [alias_name] [string1] [string2 ...] Set alias_name to the specified strings.

/unalias alias_name Delete an alias.

/dump - file name Dump or append configuration to a text file.

/bye Exit NETSH /exit Exit NETSH /quit Exit NETSH /h Display help /help Display help /? Display helpExamplesSet LAN connection to DHCPNETSH set address name="Local Area Connection" source=dhcpSet LAN connection to the static IP address 192.168.5.99NETSH set address name="MyLocal AreaConnection" source=static addr=192.168.5.99 mask=255.255.255.0 gateway=192.168.5.1 Show IP configurationNETSH interface ip show configConnect to portNETSH diag connect iphost www.ss64.com 80Export IP settings to fileNETSH -c interface dump > netsh.txtImport IP settings from a fileNETSH -f netsh.txt "Once you eliminate your #1 problem, #2 gets a promotion" - Gerald Weinberg, "The Secrets of Consulting"

Related commands:

Q242468 - How to Use the Netsh.exe Tool Q257748 - Change from Static IP Address to DHCP with NETSHQ140859 - Win NT TCP/IP Routing Basics ROUTE - Manipulate network routing tables

Equivalent Linux BASH commands:

route -

NETSVC.exe (Resource Kit)

Command-line Service Controller. Start, Stop and Query services, but does not cover creating or deleting them. Although part of the Windows 2000 resource kit - this command runs fine under NT 4.

Syntax

NETSVC \\server command servicename

Key server The workstation or server where the service is running

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 /queryRelated Commands:

SC - Service Control - Create, Create remotely, Start, Stop, Query, Delete.NET - manage network resourcesSCLIST - Display NT ServicesINSTSRV - Install an NT service (run under a specific account)DELSRV - Delete NT service START /HIGH - Start a specified program or command. Svcmon - Monitor services and raise an alert if they stop. (Win 2K ResKit) Q166819 - Control Services Remotely

NBTSTAT.exe

Display protocol statistics and current TCP/IP connections using NBT (NetBIOS over TCP/IP).

Syntax By Name NBTSTAT -a Remote_host_Name [options] [interval]

By IP address NBTSTAT -A IP_address [options] [interval]

Key -a (adapter status) List the remote machine's name table given its name -A (Adapter status) List the remote machine's name table given its IP address -c (cache) List NBT's cache of remote [machine] names and their IP addresses -n (names) List local NetBIOS names. -r (resolved) List names resolved by broadcast and via WINS -R (Reload) Purge and reloads the remote cache name table -S (Sessions) List sessions table with the destination IP addresses -s (sessions) List sessions table converting destination IP addresses to computer NETBIOS names. -RR (ReleaseRefresh) Send Name Release packets to WINS and then, starts Refresh

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 Commands:

IPCONFIG - IP ConfigurationNETSTAT - Display networking statistics (TCP/IP) PING - Test a network connectionTRACERT - Trace route to a remote host

Q163409 - The 16th character is a NetBIOS suffixQ119493 - NetBIOS over TCP/IP Name Resolution Q314053 - TCP/IP and NBT Configuration Parameters

Equivalent Linux BASH commands:

ping - Test a network connectiontrace - 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 Linux BASH commands:

ping - Test a network connectiontrace - Find the IP address of a remote host

NOW.exe (Resource Kit)

Display Message with current Date and Time

Syntax NOW [message to be printed with time-stamp] Typical output:

Mon Mar 06 14:58:48 2000 your message here

Related Commands:

ECHO - Display message on screenDATE /t - Display or set the dateLOGTIME - Log the date and time in a fileTimethis - Time how long it takes the system to run a command. (Win 2K ResKit) Uptime - Time since last reboot. (Win 2K ResKit)

Equivalent Linux BASH commands:

date - Display or change the date & time

NSLOOKUP (TCP/IP)

Lookup IP addresses on a NameServer.

Syntax Lookup the ip address of MyHost:

NSLOOKUP [-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 class=X - 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 type=X - set query type set querytype=X - 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 Related Commands:

NBTSTAT - Display networking statistics (NetBIOS over TCP/IP) NETSTAT - Display networking statistics (TCP/IP)TRACERT - Trace route to a remote host Q200525 - Using nslookupnetwork-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} Is the backup is a volume shadow copy. Windows XP only.

/um (Windows 2000 only) Find the first available media, format it, and use for the current backup. Use with the /p switch to scan for available media pools. This command is only for standalone tape devices (not tape loaders.) The /UM switch must be at the end of the command line.Backups made using Windows Server 2003's NT Backup program can't be restored with any previous WinNT Backup Program - (expect a patch for this soon.)See also: NTBACKUP syntax for Windows NT 4Mick Jagger sang backup vocals for "You're so Vain" by Carly Simon

Related Commands:

Q821730 - Backup does not run as expected (Server 2003)Q814583 - NT Backup in Windows Server 2003 Q104169 - Files that are automatically skipped by NtbackupQ300135 - Using the Windows 2000 Backup Wizard. Q237310 - Manually Edit Ntbackup.exe Selection Script Files Q260327 - NT Backup error codes. (Win2000)

HKCU\Software\Microsoft\Ntbackup\User Interface - UndocumentedJSIFAQ Tip 2265 - NTBackup without manually managing the mediaAT - Schedule a command to run at a later timeCIPHER - Encrypt or Decrypt files/folders XCOPY - Copy files and foldersRSM - Remote Storage Management - Eject tapes (Win2000) MT - Tape utility (3rd party)

Equivalent Linux BASH command:

NTRIGHTS.exe (Resource Kit, 2000/2003)

Edit user account Privileges.

Syntax NTRIGHTS +r Right -u UserOrGroup [-m \\Computer] [-e Entry]

NTRIGHTS -r Right -u UserOrGroup [-m \\Computer] [-e Entry]

Key:

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

Privilege Meaning

SeAssignPrimaryTokenPrivilege Replace a process level tokenSeAuditPrivilege Generate security auditsSeBackupPrivilege Back up files and directoriesSeBatchLogonRight Log on as a batch job

SeChangeNotifyPrivilege Bypass traverse checkingSeCreateGlobalPrivilege Create global objects*SeCreatePagefilePrivilege Create a pagefileSeCreatePermanentPrivilege Create permanent shared objects. SeCreateTokenPrivilege Create a token object

SeDenyBatchLogonRight Deny log on as a batch jobSeDenyInteractiveLogonRight Deny log on locallySeDenyNetworkLogonRight Deny access this computer from the networkSeDenyServiceLogonRight Deny log on as a serviceSeDebugPrivilege Debug programs

SeEnableDelegationPrivilege Enable computer and user accounts to be trusted for delegation

SeImpersonatePrivilege Impersonate a client after authentication*SeIncreaseBasePriorityPrivilege Increase scheduling prioritySeIncreaseQuotaPrivilege Increase quotasSeInteractiveLogonRight Log on locally

SeLoadDriverPrivilege Load and unload device driversSeLockMemoryPrivilege Lock pages in memorySeMachineAccountPrivilege Add workstations to domainSeNetworkLogonRight Access this computer from the networkSeProfileSingleProcessPrivilege Profile single processSeRemoteShutdownPrivilege Force shutdown from a remote systemSeRestorePrivilege Restore files and directories

SeSecurityPrivilege Manage auditing and security logSeServiceLogonRight Log on as a serviceSeShutdownPrivilege Shut down the systemSeSyncAgentPrivilege Synchronize directory service dataSeSystemEnvironmentPrivilege Modify firmware environment values SeSystemProfilePrivilege Profile system performanceSeSystemtimePrivilege Change the system time

SeTakeOwnershipPrivilege Take ownership of files or other objectsSeTcbPrivilege Act as part of the operating systemSeUndockPrivilege Remove computer from docking stationSeUnsolicitedInputPrivilege Read unsolicited input from a terminal device

This command requires Administrator rights and does not run on NT 4.0* = Privilege valid in Windows 2003 and above only Example:Allow members of the local Users group to logon locallyntrights -u Users +r SeInteractiveLogonRightRevoke the above ntrights -u Users -r SeInteractiveLogonRightSpecifically deny local logon rights to jdoe ntrights -u jdoe -r SeDenyInteractiveLogonRight

"What distinguishes the majority of men from the few is their inability to act according to their beliefs." - Henry Miller

Related commands:

CACLS - Change file permissionsQ267553 - Reset User Rights in Group PolicyQ315276 - Set Logon User Rights by Using the NTRights

PATH

Display or set a search path for executable files

Syntax PATH pathname [;pathname] [;pathname] [;pathname]... PATH PATH ;

Key pathname : drive letter and/or folder ; : the command 'PATH ;' will clear the pathPATH without parameters will display the current path.

The %PATH% environment variable contains a list of folders. When a command is issued at the CMD prompt, the operating system will first look for an executable file in the current folder, if not found it will scan %PATH% to find it. Use the PATH command to display or change the list of folders stored in the %PATH% environment variable.To view each item on a single line use this batch script:::viewpath.cmd@echo off::echo the path one line at a timefor %%G in ("%path:;=" "%") do @echo %%G

To add items to the current path, include %PATH% in your new setting.For Example:

PATH=%PATH%;C:\Program Files\My Application

Permanent Changes

Changes made using the PATH command are NOT permanent, they apply to the current CMD prompt only and remain only until the CMD window is closed.

T o permanently change the PATH use

Control Panel, System, Environment, System VariablesControl Panel, System, Environment, User Variables

You can also do this at the command line with SETX

Changing a variable in the Control Panel will not affect any CMD prompt that is already open. Only new CMD prompts will get the new setting.

To change a system variable you must have administrator rights

The %PATH% variable is set as both a system and user variable, the 2 values are combined to give the PATH for the currently logged in user. This is explained in full by MS Product Support Article Q100843

If your system has an AUTOEXEC.BAT file then any PATH setting in AUTOEXEC.BAT will also be appended to the %PATH% environment variable. This is to provide compatibility with old installation routines which need to set the PATH. All other commands in AUTOEXEC.BAT are ignored.

Terminology

For a file stored as:C:\Program Files\Adobe\Acrobat.exe

The Drive is:C:

The Filename is:Acrobat.exe

The Path is:\Program Files\Adobe\The Pathname is:\Program Files\Adobe\Acrobat.exe

The Full Pathname isC:\Program Files\Adobe\Acrobat.exe

"If you do not love your job, change it. Instead of pushing paper, push ideas. Instead of sitting down, stand up and be heard. Instead of complaining, contribute. Don't get stuck in a job description" - Microsoft job advert

Related Commands:

SET - Display, set, or remove environment variables.PATHMAN - Resource Kit utility - modify system and user paths. Pathman can resolve duplicate characters, and can improve performance by removing duplicate paths. For details see Pathman.wri in the resource kit.

Equivalent Linux BASH commands:

env - Display, set, or remove environment variables CDPATH - Environment variableMAILPATH - Environment variablePATH - Environment variable

PATHPING (Windows 2000)

Trace route and provide network latency and packet loss for each router and link in the path.

Syntax PATHPING [-n] [-h max_hops] [-g host_list] [-p period] [-q num_queries] [-w timeout] [-t] [-R] [-r] target_name

Key -n Don't resolve addresses to hostnames -h max_hops Max number of hops to search, default=30 -g host_list Loose source route along host-list up to 9 hosts in dotted decimal notation, separated by spaces. -p period Wait between pings, default=250 (milliseconds) -q num_queries Number of queries per hop, default=100 -w timeout Wait timeout for each reply, default is 3000 (milliseconds) -T Test each hop with Layer-2 priority tags (QoS connectivity) -R Test if each hop is Resource Reservation Protocol (RSVP) aware

All parameters are Case-SensitivePathping 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.FirewallsLike 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 VerenaRelated Commands:

BROWSTAT - Get domain, browser and PDC infoIPCONFIG - IP ConfigurationNETSTAT - Display networking statistics (TCP/IP) PING - Test a network connectionTRACERT - Trace route to a remote host

Equivalent Linux BASH commands:

ping - Test a network connectiontrace - Find the IP address of a remote host

PAUSE

Pause the execution of a batch file

Syntax PAUSEdisplays the message "Press any key to continue . . ."

To suppress the message use PAUSE >nul

"Advertising may be described as the science of arresting the human intelligence long enough to get money from it." - Stephen Leacock Related commands

TIMEOUT - Delay that allows the user to press a key and continue immediately.

Equivalent Linux BASH commands: read -p "press any key to continue"sleep - Delay for a specified time

PERMS.exe (Windows 2000)

Display a user’s ACL access permissions for a file. Output from PERMS may be misleading in cases where a user has inherited permission through membership of

an NT workgroup. [First released in the NT4 Resource Kit]

Syntax PERMS [account] [path] options

Key account : username or [domain\|computer\]username

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 Commands:

CACLS - Display or modify Access Control Lists (ACLs) for files and foldersSHOWACL - Show file Access Control Lists (win 2000)SUBINACL - Change an ACL's user/domain (use when the file owner has moved to a new domain)ATTRIB - Display or change file attributes

XCACLS - Display or modify Access Control Lists (ACLs) for files and folders

Equivalent Linux BASH commands:

chmod - Change access permissionschown - Change file owner and group

Monitor (Resource Kit)

Control Performance Monitor logging from the command line, this removes the graphical workload of Perfmon from the server making the reported values more accurate.The Data Logging Service (DATALOG.EXE) is a Windows NT Service that performs the same function as the Performance Monitor Alert and Logging facility.

Syntax MONITOR setup

MONITOR %SYSTEMROOT%\SYSTEM32\MyLogSet.PMW

MONITOR start

MONITOR stop

Key SETUP is needed once only to install the service. Use START and STOP to Start/Stop logging. Save .PMW files from the PERFMON GUI under the file menu.Any graphical process running on a server will affect performance to some degree, most interactive programs (in particular the command prompt) will run faster when minimised.

Monitoring Hard DrivesTo enable performance counters run:diskperf -y This enables the objects and counters for logical and physical disks .

To enable performance counters for a striped array run:diskperf -ye

To disable performance counters run:diskperf -Nor set in the registry HKLM\SYSTEM\CurrentControlSet\Services\PerfDisk\PerformanceREG_DWORD 'Disable' = 1

Monitoring drive performance with perfmon will itself have a small impact on performance, any changes require a reboot and any errors will be logged in the

event viewer. Disable perfmon when tuning is complete.

Alternatives: Monitoring a server by running Performance Monitor from a remote workstation is a good alternative to the Data Logging Service that still gives accurate figures (and you don't need the resource kit to do this).

"Quality in a product or service is not what the supplier puts in. It is what the customer gets out and is willing to pay for" - Peter Drucker

Related Commands:

LOGEVENT - Write text to the event viewer.

PING

Test a network connection - if successful, ping returns the ip address.

Syntax PING [options] destination_host

Options -w timeout Timeout in milliseconds to wait for each reply. -i TTL Time To Live. -v TOS Type Of Service. -a Resolve addresses to hostnames. -n count Number of echo requests to send. -t Ping the destination host until interrupted. -l size Send buffer size. -f Set Don't Fragment flag in packet. -r count Record route for count hops. -s count Timestamp for count hops. -j host_list Loose source route along host_list. -k host_list Strict source route along host_list.destination_host The name of the remote hostA 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.A successful PING does NOT always return an %errorlevel% == 0Therefore 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

ExamplesPING -n 1 -w 7500 Server_06

PING -w 7500 MyHost |find "TTL=" && ECHO MyHost found

PING -w 7500 MyHost |find "TTL=" || ECHO MyHost not found

PING -n 5 -w 7500 www.microsoft.com

PING -n 5 -w 7500 microsoft.comPING is named after the sound that a sonar makes.Ping 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 sereneThe very pulse of the machine."- William Wordsworth, (She Was a Phantom of Delight)

Related Commands:

TRACERT - Trace route to a remote hostIPCONFIG - IP ConfigurationPATHPING - Route Tracing tool (Windows 2000) RPings - RPC Connectivity Verification Tool (Win 2K but works with NT)

Q115388 - Resolving IP Address with Leading Zero FreePing - Freeware Windows GUI Ping WebPing - Ping from any web browser

Equivalent Linux BASH commands:

ping - Test a network connectiontrace - Find the IP address of a remote host

POPD

Change directory back to the path/folder most recently stored by the PUSHD command.POPD will also remove any temporary drive maps created by PUSHD

Syntax POPD For example c:\Program Files> PUSHD c:\utils c:\utils> PUSHD c:\WINNT c:\Winnt> c:\Winnt> POPD c:\utils> c:\utils> POPD c:\Program Files>If Command Extensions are disabled PUSHD and POPD will not create temporary drive letters.

"It's amazing how low you go to get high" - John Lennon

Related CommandsPUSHD - Change the current directory/folder and store the previous folder/pathCD - Change Directory, select a Folder (and drive)

Equivalent Linux BASH commands:

export - Set an environment variable

PORTQRY (Download)

Port Query - Display the status of TCP and UDP ports, troubleshoot TCP/IP connectivity and security, return LDAP base query info, SMTP, POP3, IMAP4 status, enumerate SQL Server instances (UDP port 1434), Local ports, local services running (and the DLL modules loaded by each).

Portqry.exe can query a single port, a list of several ports, or a sequential range of port numbers.

Syntax

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' waits longer for UDP replies from

remote systems-nr by-passes default IP address-to-name resolution

ignored unless an IP address is specified after -n-cn specifies 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>Examplesportqry -localportqry -local -l MyLogFile.txt -vportqry -wpid 1272 -wt 5 -l MyLogFile.txt -y -vportqry -wport 53 -l dnslog.txtportqry -n myserver.com -e 25portqry -n 10.0.0.1 -e 53 -p UDP -iportqry -n host1.dev.reskit.com -r 21:445portqry -n 10.0.0.1 -o 25,445,1024 -p both -sp 53portqry -n host2 -cn !my community name! -e 161 -p udpNotesPortQry 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 Commands:

nslookup - Lookup IP addresses on a NameServerNETSH diag - Connect to TCP portWMIC PORTCONNECTOR - Access Physical portQ310099 - Description of PortQryQ832919 - PortQry Version2Q310456 - Use PortQry to Troubleshoot Active Directory Connectivity Q310298 - Use PortQry to Troubleshoot MS Exchange

Equivalent Linux BASH commands:

PRINT

Print a file or files to a local or network printer.

syntax PRINT [/D:device] [pathname(s)]

key device : either a local printer (LPTx, COMx ) or a network printer by its sharename (\\servername\print_share)

pathname : The file or files to be printedThe 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 relevant .spl and .shd files from%SystemRoot%\system32\spool\PRINTERS but the .spl file for a print job at the top of the print queue cannot be deleted.

Printing requires the Spooler service to be running

Related Commands:

NET PRINT - View and Delete print jobsPrint Migrator - Microsoft tool for moving print queues.Defptr - Default Printer. (Win 2K ResKit) PRNCNFG - Display, configure or rename a printer WMIC PRINTER - Set printing options through WMI. Print Notification - this is set under Control Panel, Printers, File, Server Properties, Advanced Q246868 - New TCP/IP Printing Options in the Windows Standard Port Monitor Q234270 - Group Policies to Control Printersprncnfg.vbsprndrvr.vbsprnjobs.vbsprnmngr.vbsprnport.vbsprnqctl.vbspubprn.vbs

Equivalent Linux BASH commands:

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) whereit's installed (\windows\system32) and run PRNCNFG -?Related Commands:

PRINT - Print a text fileCON2PRT - Connect or disconnect a PrinterNET VIEW - to view a list of printersNET PRINT - View and Delete print jobs PRNDRVR - Add, delete or list printer drivers.PRNJOBS - Pause, resume, cancel, or list print jobsPRNMNGR - Add, delete, or list printers / connections, set the default printer. PRNPORT - Create, delete, or list TCP/IP printer ports, change port configuration. PRNQCTL - Print a test page, pause or resume a printer, clear a printer queue.RUNDLL32 - Install/Remove Printers (plus advanced options)WMIC PRINTER - Set printing options through WMI. Q246868 - New TCP/IP Printing Options in the Windows Standard Port Monitor

WSH Commands:Add printer - .AddPrinterConnection Add Network printer - .AddWindowsPrinterConnection List printers - .EnumPrinterConnections Set default printer - .SetDefaultPrinter

Equivalent Linux BASH commands:

lpc - Line printer control programlpr - Off line print lprint - Print a file lprintd - Abort a print job lprintq - List the print queuelprm - Remove jobs from the print queue

PRNMNGR (XP and .Net)

Display, add, remove or set default printer.

Syntax PRNMNGR [-options] [-s server][-p printer_name][-m driver model] [-r port][-u user_name][-w password]

Options -l list printers

-a add local printer -ac add printer connection

-g get the default printer -t set the default printer -d delete printer -x delete all printersExamples 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 Commands:

CON2PRT - Connect or disconnect a PrinterNET VIEW \\Printserver - to view a list of available printersNET 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 jobsPRNPORT - 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 fileRUNDLL32 - Install/Remove Printers (plus advanced options) WMIC PRINTER - Set printing options through WMI. Q246868 - New TCP/IP Printing Options in the Windows Standard Port Monitor

WSH Commands:Add printer - .AddPrinterConnection Add Network printer - .AddWindowsPrinterConnection List printers - .EnumPrinterConnections Set default printer - .SetDefaultPrinter

Equivalent Linux BASH commands:

lpc - Line printer control programlpr - Off line print lprint - Print a file lprintd - Abort a print job lprintq - List the print queuelprm - Remove jobs from the print queue

PROMPT

Change the cmd.exe command prompt.

Syntax PROMPT [text] Key text : a text string.The prompt text can be made up of normal characters and the following special codes: $A & (Ampersand) $B | (pipe) $C ( (Left parenthesis) $D Current date $E Escape code (ASCII code 27) $F ) (Right parenthesis) $G > (greater-than sign) $H Backspace (erases previous character) $L < (less-than sign) $M Display the remote name for Network drives $N Current drive $P Current drive and path $Q = (equal sign) $S (space) $T Current time $V Windows NT version number $_ Carriage return and linefeed $$ $ (dollar sign) $+ Will display plus signs (+) one for each level of the PUSHD directory stackExamplesDisplay the UNC path whenever you are using a network drive (mapped with NET USE)PROMPT $M$_$P$GSimulate an HP-UX prompt with the computername and the current folder on separate lines:PROMPT=$p$_%username%@%computername%:.Restore the default prompt:PROMPT $P$GPROMPT is implemented as a hidden NT environment variable called PROMPT, try doing:ECHO %prompt% knowing this you can force a permanent change in the CMD prompt for all sessions by setting a permanent environment variable with the appropriate prompt text.e.g. SETX PROMPT $M$_$P$G

You can also create specific shortcut's to the command prompt like this:CMD /K PROMPT $M$_$P$G

If Command Extensions are disabled the commands $M and $+ are not supported.

Related Commands:

SETX - Set an environment variable permanently.

Equivalent Linux BASH commands:

The BASH prompt is set by the BASH variable $PROMPT_COMMAND

env - Display, set, or remove environment variables export - Set an environment variable

PsExec (part of PsTools - download PsExec)

Execute a 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.

PsExec does not require you to be an administrator of the local filesystem this can allow UserA to run commands as UserB - a Runas replacement.Surround any long filenames "with quotation marks"

Examples:

Launch an interactive command prompt on \\workstation64:psexec \\workstation64 cmdExecute IpConfig on the remote system, and display the output locally:psexec \\workstation64 ipconfig /allCopy the program test.exe to the remote system and execute it interactively:psexec \\workstation64 -c test.exeExecute 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 Commands:RUNAS - Execute a program under a different user account

Equivalent Linux BASH command:xon - start an X program on a remote machine

PsFile (part of PsTools - download PsFile)

Show files opened remotely, or close an open file (kill file locks)

Syntax psfile [\\Computer [-u User [-p Passwd]]] [[Id | path] [-c]]

Options:

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 Commands:NET FILE - Display all the open shared files on a server and the lock-id

Equivalent Linux BASH commands:

flock - apply or remove an advisory lock on an open filefcntl - manipulate file descriptordnotify - file-monitoring mechanism 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 SIDSpecify 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: Niamodpsgetsid NiamodGet the SID for the currently logged-in user psgetsid %username% Related Commands:SYSTEMINFO - List system configuration

PsInfo (part of PsTools - download PsInfo)

List information about a system including the type of installation, kernel build, registered organization, owner, processor details, physical memory and the system install date.

Syntax psinfo [\\computer[,computer[,..]] [options] [filter]

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.

-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 -decho %errorlevel% Related Commands:PsGetSid - Display the SID of a computer or a userSYSTEMINFO - List system configuration

Equivalent Linux BASH command:

cat /proc/*

PsKill (part of PsTools - download PsKill)

Kill processes by name or process ID

Syntax pskill [- ] [-t] [\\computer [-u user] [-p passwd]] <process name | process id>

Options:

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 Commands:PsList - List detailed information about processesThe process button of Task Manager in Windows will also identify the process ID (PID)PsSuspend - Suspend processes (so they can be continued at a later point in time)KILL - Remove a program from memory

Equivalent Linux BASH command:

kill - Stop a process from running, either via a signal or forced termination

PsList (part of PsTools - download PsList)

List detailed information about processes

Syntax pslist [-?] [-t] [-m] [-x] [\\computer [-u user] [-p passwd]] [name | pid]

Options:

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.Examples:

List all processes running on \\workstation64:pslist \\workstation64 Related Commands:PsKill - Kill processes by name or process IDTASKLIST - List running applications and servicesWindows Task Manager - List of running process IDs (PID)PerfMon - Monitoring tool

Equivalent Linux BASH commands:

ps - Process status, information about processes running in memory.top - Process viewer, find the CPU-intensive programs currently running.

PsLoggedOn (part of PsTools - download PsLoggedOn)

See who is logged onto a computer, either locally or remotely

Syntax psloggedon [- ] [-l] [-x] [\\computer | username]

Options:

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.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 Related Commands:net session - List or disconnect user sessions (Local machine only)

Equivalent Linux BASH commands:

who - Print who is currently logged in

PsLogList (part of PsTools - download PsLogList)

Event log records

Syntax psloglist [- ] [\\computer[,computer[,...] | @file [-u user [-p passwd]]] [-s [-t delim]] [-m #|-n #|-h #|-d #|-w] [-c][-x][-r][-a mm/dd/yy][-b mm/dd/yy] [-f filter] [-i ID[,ID[,...] | -e ID[,ID[,...]]] [-o event source[,event source][,..]]] [-q event source[,event source][,..]]] [-l event_log_file] <eventlog>

Options:

computer The computer on which the log resides. Default=local system

-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 applicationRelated Commands:elogdump - Resource Kit event log dump (local machine only)

Equivalent Linux BASH command:

Logs are in plain ascii text

PsPasswd (part of PsTools - download PsPasswd)

Change account password

Syntax pspasswd [[\\computer[,computer[,..] | @file [-u user [-p passwd]]] Username [NewPassword]

Options:

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 password567Related Commands:NET USER

Equivalent Linux BASH command:passwd - Modify a user password

PsService (part of PsTools - download PsService)

View and control services

Syntax psservice [\\computer [-u user] [-p passwd]] <command> <options>

Options:

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 serviceTyping a command followed by "- " displays the syntax for that command.Service States: 1 - Stopped2 - Start Pending

3 - Stop Pending4 - RunningExamples:

Restart the spooler service on \\server64psservice \\server64 restart spoolerRelated Commands:NET START/STOP SC - Service control

PsShutdown (part of PsTools - download PsShutdown)

Initiate a shutdown/reboot of a local or remote computer, logoff a user, lock a system.

Syntax psshutdown [[\\computer[,computer[,..] | @file [-u user [-p passwd]]] -s|-r|-h|-d|-k|-a|-l|-o [-f] [-c] [-t nn|h:m] [-n s] [-v nn] [-e [u|p]:xx:yy] [-m "message"]Options:

computer The computer on which the user account resides. Default=local system a wildcard (\\*), will affect all computers in the current domain.

-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 Commands:

SHUTDOWN - With full list of reason codes

Equivalent Linux BASH command:shutdown - Shutdown or restart linux

PsSuspend (part of PsTools - download PsSuspend)

Suspend processes on the local or a remote system.

Syntax pssuspend [- ] [-r] [\\computer [-u user] [-p passwd]] <process name | process id>

Options:

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 Commands:PsKill - Kill processes by name or process ID

PUSHD

Change the current directory/folder and store the previous folder/path for use by the POPD command.

Syntax PUSHD pathname Key pathname - the folder to make 'current' (UNC names accepted)Examplec:\Program Files> PUSHD c:\utilsc:\utils> c:\utils> POPDc:\Program Files> c:\Program Files> PUSHD \\Server_23\MyShare\MyFolderZ:\MyFolder>Z:\MyFolder> POPDc:\Program Files>

Networks When a UNC path is specified, PUSHD will create a temporary drive map and will then use that new drive.

Temporary drive letters are allocated in reverse alphabetical orderso if Z: is free it will be used.

If Command Extensions are disabled the PUSHD command will not accept a network (UNC) path."One of the phrases that kept running through the conversation was 'pushing the outside of the envelope' The envelope was a flight test term referring to the limits of a particular aircraft" - Tom Wolfe (The Right Stuff)

Related commandsCD - Change directory CMD - UNC options PROMPT - Display the level of the PUSHD stack

Equivalent Linux BASH commands:

export - Set an environment variable

QGREP (Windows 2000 Resource Kit)

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

Syntax QGREP [options] [-e string] [-f file] [-i file] [strings] [files]

key: -L Search strings literally. -X Treat search strings as regular expressions. -B Match pattern at beginning of line. -E Match pattern at end of line. -y Treat upper and lower-case as equivalent.

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

MUNGE - Find and Replace text within file(s)

Equivalent Linux BASH commands:

grep - Search file(s) for lines that match a given pattern

RASDIAL (Dial Up Networking)

Manage RAS/DUN connections.

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: RASDIALTo 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 Commands:

RASPHONE - Manage RAS connectionsConnection Manager Administration Kit - VPN connections (2003 Resource Kit)RASMON - Windows 2000 GUI Resource Kit toolCHECKRAS - 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_entryTo use this command requires that Dial Up Networking Service be installed (via Control Panel - Networking)

The default location for PhoneBook entries is %SystemRoot%\System32\ras\"Someone invented the telephone, And interrupted a nation's slumber, Ringing wrong but similar numbers" - Ogden Nash

Related Commands:

RASDIAL - Manage RAS connectionsConnection Manager Administration Kit - VPN connections (2003 Resource Kit)RASMON - Windows 2000 GUI Resource Kit toolCHECKRAS - SMS support tools

RECOVER

Recover a damaged file from a defective disk.

SYNTAX RECOVER [drive:][path]filenameRecover is designed to help in the case of hardware failure. When a drive fails the failure is not always total, in other words you may be able to read some of the files but not others, and some files will be only partly readable.

The data on a disk is stored in tracks and sectors in an almost random manner. Data stored in a bad sectors cannot be read.

RECOVER reads a file sector by sector and recovers data from the good sectors. You must specify a file.

Recover will not allow you to undelete a file.Recover files one at a time; move each file to a good disk before editing to re-enter missing information.In the case of complex documents you will probably lose formatting/graphics but will retain raw text.

"Whom the gods love dies young - Menander 300 BC

Related Commands:

CHKDSK - Check Disk - check and repair disk problems

Equivalent Linux BASH commands:

cksum - Print CRC checksum and byte counts (can detect problems but not fix them)

REG.exe (NT Resource Kit, W2K Support Tools, XP)

Read, Set or Delete registry keys and values

The REG command was updated in NT Resource Kit supplement 2 - the syntax for Win 2K/XP is different.

SYNTAX:

REG QUERY RegistryPath ["String"] [/S] [/size] [/list] REG ADD RegistryPath=Value [DataType] REG UPDATE RegistryPath=Value REG DELETE RegistryPath [/FORCE] REG COPY Source [\\Machine] Dest [\\Machine] REG SAVE RegistryPath FileName REG RESTORE FileName KeyName REG LOAD FileName KeyName REG UNLOAD KeyName REG FIND [ROOTKEY\]Key [DataType] SearchStr [ReplaceStr] [-y] [-z[R]] REG DUMP RegistryPath FileName REG COMPARE [ROOTKEY\]Key [ROOTKEY\]Key [-o[M][D]] [-q] [-e]

You can apply any of the above commands to a remote machine by adding \\MachineName to the command line.

Key:

RegistryPath : [ROOTKEY\]Key[\'ValueName'] where ROOTKEY is one of HKLM = hkey_Local_machine (default) HKCR = hkey_classes_root HKCU = hkey_current_user HKU = hkey_users

Key = The full name of a key under the selected ROOTKEY.

ValueName = The value, under the selected Key, to edit. (default is all keys and values) Enclose ValueNames that containe the \ character in single quotes.

DataType : REG_SZ | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ (default = REG_SZ)

Machine : Name of remote machine - omitting defaults to current machine. Only HKLM and HKU are available on remote machines.

Source : a RegistryPath in the format above.

Dest : a RegistryPath in the format above.

FileName : The filename to save to or restore from (without an extension.)

KeyName : A key name to load the hive file into. (Creating a new key) specify the key name to UNload with: [ROOTKEY\]Key

/S Query all subkeys.

/size Query the size of RegistryPath

/list Search strings from RegistryPath

/FORCE Force a deletion without asking "are you are sure"

SearchStr : Value to search for.

ReplaceStr : Value to replace.

-y : Force case sensitivity for SearchStr

-z : Find non-Unicode-compliant entries or entries missing a trailing null character. (forces case sensitity)

R : Adjust entry to add Unicode compliancy or the missing null char.

-o Omit screen output of: M: Matches D: Differences

-e Sets the error level to the error code that was in effect the last time the utility was run. By default, the error level is set to the number of differences that were found.

-q Very quiet, just print the number of differences.notes: On remote NT machines the file is written to the System32 directory. On remote Win95 machines the file is written to the Windows directory. SAVE is identical to BACKUP.

Examples

An example of each command is available from the command line

REG QUERY /? REG ADD /? REG UPDATE /? REG DELETE /? REG COPY /? REG SAVE /? REG BACKUP /? REG RESTORE /? REG LOAD /? REG UNLOAD /? REG FIND /? REG DUMP /? REG COMPARE /?

"The way to a mans heart is through his stomach" - Fanny Fern (writer)

Related Commands:

SETX - Set environment variables permanently, can also read a registry key and write the value to a text file.REGEDIT - Load Registry settings from a .REG fileREGEDT32.EXE - Edit the registry including Security and Auditing Options Dureg - Registry Size Estimator. (Win 2K ResKit) JsiFaq Tip 6671 - How to include a quote mark (")

REGEDIT

Import, export or delete registry settings from a text (.REG) file

Syntax Export the Registry (all HKLM plus current user) REGEDIT /E pathname

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 ImportHow to add keys and values from the registry:

Create a text file like this:REGEDIT4[HKEY_CURRENT_USER\SomeKey]"SomeStringValue"="Hello" When double clicking this .reg file the key and value will be added.Alternatively run REGEDIT MYKEY.REG from the command line.How to delete keys and values from the registry:

Create a reg file like this, notice the hyphen inside the first bracket REGEDIT4[-HKEY_CURRENT_USER\SomeKey] When double clicking this .reg file the key "SomeKey" will be deleted along with all string, binary or Dword values in that key.

If you want to just delete values leaving the key in place, set the value you want to delete = to a hyphene.g. REGEDIT4[HKEY_CURRENT_USER\SomeKey]"SomeStringValue"=-Again double clicking this .reg file will delete the values specified - or you can use REGEDIT /s MyDeleteScript.REG.

Windows XP Registry files.Under Windows NT all registry scripts start with:REGEDIT4

Under Windows 2K and XP the first line is:Windows Registry Editor Version 5.00

To be sure that a .REG script will run under any version of Windows use the earlier syntax: REGEDIT4.Compare the Registry of two machinesWindiff is your friend, this simple GUI utility from the resource kit will list all the differences.

CommentsWithin a registry file, comments can be preceded by "; " e.g.;; Turn the NUMLOCK on at login; [HKEY_CURRENT_USER\Control Panel\Keyboard] "InitialKeyboardIndicators"="2" "I never make stupid mistakes. Only very, very clever ones" - John Peel

Related commands:

REGEDT32.EXE - Edit the registry including Security and Auditing Options (NT 4)REG - Read, Set or Delete registry keys and values SET - Display, set, or remove Windows NT environment variables SETX - Set environment variables permanentlyWMIC REGISTRY - Set registry options through WMI. Q322756 - How to backup and edit the registryDureg - Registry Size Estimator. (Win 2K ResKit) XP Registry Keys - Commonly tweaked user interface settings

registry

; Sanity.REG; Windows XP Sanity check

; Registry settings for all those annoying HKEY_CURRENT_USER user interface; settings that are likely to drive you nuts when running WinXP

; Usual disclaimers apply - don't edit the registry unless you know what you are doing and; BACKUP THE REGISTRY FIRST

; If you edit this file ensure all comment lines are prefixed with ; so that REGEDIT will ignore them

Windows Registry Editor Version 5.00

; - - - Section1 - - - - MS Explorer - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer]

; Disable the animated Click Start to begin"NoStartBanner"=hex:01,00,00,00

; Don't constantly shuffle around the start menu items"Intellimenus"=dword:00000000

; Use the classic Start Menu"NoSimpleStartMenu"=dword:00000001

; Dont tie new shortcuts to a specific PC"LinkResolveIgnoreLinkInfo"=dword:00000001

; Don't hide all the local Drives"NoDrives"=dword:00000000

; Don't display a welcome screen"NoWelcomeScreen"=dword:00000001

; Don't automatically create shortcuts within My Network Places "NoRecentDocsNetHood"=dword:00000001

; Don't run the Desktop Cleanup Wizard"NoDesktopCleanupWizard"=dword:00000001

; Don't create a Shared Documents folder for My Computer "NoSharedDocuments"=dword:00000001

; Don't hide the log-off option from the start menu"ForceStartMenuLogOff"=dword:00000001

; Don't clutter start menu with My Network Places"NoStartMenuNetworkPlaces"=dword:00000001

; Don't add a My Documents shortcut to the start menu"NoSMMyDocs"=dword:00000001

; Don't add a Favorites shortcut to the start menu"NoFavoritesMenu"=dword:00000001

; Don't add a My Pictures shortcut to the start menu"NoSMMyPictures"=dword:00000001

; Don't add a My Music shortcut to the start menu"NoStartMenuMyMusic"=dword:00000001

; Don't hide any of the following settings in the explorer GUI"NoActiveDesktopChanges"=hex:00,00,00,00"NoActiveDesktop"=dword:00000000"NoSaveSettings"=dword:00000000"ClassicShell"=dword:00000000"NoThemesTab"=dword:00000000

; Disable active desktop"NoActiveDesktop"=hex:01,00,00,00

; Don't ignore the flag above, really disable active desktop"ForceActiveDesktopOn"=dword:00000000

; Enable Windows Update;; "NoWindowsUpdate"=dword:00000000; OR ; Disable Windows Update ;; "NoWindowsUpdate"=dword:00000001

;; - - - Section2 - - - - Explorer\Advanced - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

;[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]

; Show hidden files and folders"Hidden"=dword:00000001; 00000002 would mean "Don't show hidden files and folders"

; Don't Hide file extensions"HideFileExt"=dword:00000000

; Don't change the upper/lower case of filenames"DontPrettyPath"=dword:00000001

; Hide the Start Button BalloonTip (Click here to begin)

"StartButtonBalloonTip"=dword:00000000

; Don't randomly open copies of windows explorer when I login"PersistBrowsers"=dword:00000000

;; - - - Section 3 - - - - Policy settings - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System]

; Don't hide any of the following options (normally under Control Panel, Desktop)"NoDispAppearancePage"=dword:00000000"NoColorChoice"=dword:00000000"NoSizeChoice"=dword:00000000"NoDispBackgroundPage"=dword:00000000"NoDispScrSavPage"=dword:00000000"NoDispCPL"=dword:00000000"NoVisualStyleChoice"=dword:00000000"NoDispSettingsPage"=dword:00000000"NoDispScrSavPage"=dword:00000000"NoVisualStyleChoice"=dword:00000000"NoSizeChoice"=dword:00000000"SetVisualStyle"=-

;; - - - Section 4 - - - - Policy - Add-Remove Programs restrictions - - - - - - - - - - - - - - - - - ;; These keys make sure you can uninstall anything;[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Uninstall]"NoAddRemovePrograms"=dword:00000000 "NoRemovePage"=dword:00000000 "NoAddPage"=dword:00000000 "NoWindowsSetupPage"=dword:00000000 "NoAddFromCDorFloppy"=dword:00000000 "NoAddFromInternet"=dword:00000000 "NoAddFromNetwork"=dword:00000000 "NoServices"=dword:00000000 "NoSupportInfo"=dword:00000000

;; - - - Section 5 - - - - Control Panel - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

;; Dont hide any cpanel applets see Q207750[HKEY_CURRENT_USER\Control Panel\don't load]"appwiz.cpl"=-

; Start menu speed[HKEY_CURRENT_USER\Control Panel\Desktop]"MenuShowDelay"="400"

;; - - - Section 6 - - - - Console - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;[HKEY_CURRENT_USER\Console]; Allow copy and paste from the command line."QuickEdit"=dword:00000001

;; - - - Section 7 - - - - Tip Of the Day - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;; Turn off the 'Tip Of the Day'[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\tips]"Show"=dword:00000000

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 DllInstallExamplesUnregister / Disable image viewer (wmf file vulnerability) REGSVR32 /u shimgvw.dllEnable image viewer:

REGSVR32 shimgvw.dllUnregister / Disable XP Zip folders and CAB View:

REGSVR32 /u C:\Windows\System32\zipfldr.dllREGSVR32 /u C:\Windows\System32\cabview.dllRegister/Enable XP Zip folders and CAB View:

REGSVR32 C:\Windows\System32\zipfldr.dllREGSVR32 C:\Windows\System32\cabview.dllRegister DAO 3.6 (DLL library):

REGSVR32 "C:\Program Files\Common Files\Microsoft Shared\DAO\DAO360.DLL" It costs nothing to register and will only take a moment...Related Commands:

Delsrv - unregister a service with the Services Control Manager. (Win 2K ResKit)MSIEXEC - Microsoft Windows Installer RUNDLL32 - Run a DLL command Microsoft DLL Database - which software installed a specific version of a DLLQ249873 - Regsvr32 usage and error messages

How to: Use a Script to Change Registry Permissions from the Command LineView products that this article applies to.

Article ID : 245031Last Review : November 1, 2006Revision : 1.1This article was previously published under Q245031

SUMMARY

This article describes how to use a script to change permissions defined in a registry key from a command prompt by using the Regini.exe utility included with Microsoft Windows NT Server 4.0 Resource Kit. The Resource Kit is a separate product that can be purchased from Microsoft.

MORE INFORMATION

CAUTION: When you use a script to change registry permissions, you replace the entire set of current permissions defined in a registry key. For example, if you have four types of users whose permissions are defined in a particular registry key, and you create and run a script file that changes the permissions for only three of the four types of users, the information about the fourth type is deleted.

To use a script to change permissions defined in a registry key from a command prompt:

1. Install the latest version of the Windows NT Server 4.0 Resource Kit.

2.

Create a script file that contains the change commands: a. Start any text editor (such as Notepad).

b.

Type the registry keys and the appropriate permissions in the following format \Registry\hive\key [permissions] where hive is the name of the registry hive, key is the name of the registry key, and [permissions] is the binary number format of the permissions.

For example, to modify the HKEY_LOCAL_MACHINE\Software registry key to give the Administrators group and the Creator/Owner group Full Control permission and the Everyone group Read permission, type the following string: \Registry\Machine\Software [1 5 8] NOTE: You must type the permissions in the binary number format. You must also refer to the registry hive in the predefined format. For more information about how to refer to a registry hive in a script file and about the binary numbers for various types of permissions, refer to the 'Reference to Registry Hives and Binary Number Representation for Permissions' section in this article.

c. Save and then close the script file.

3.

Type the following command at a command prompt, and then press ENTER REGINI [-m \\computername] scriptnamewhere computername is the name of the computer and scriptname is the name of the script file you just created.

NOTE: Use the -m option only when you edit the registry of a remote computer. Be sure to include the entire path to the script file.

Reference to Registry Hives and Binary Number Representation for Permissions

Refer to registry hives as indicated below: HKEY_LOCAL_MACHINE - \Registry\Machine HKEY_USERS - \Registry\Users HKEY_CURRENT_USER - \Registry\User\User_SID (where User_SID is the current user's security identifier)

Permissions and their binary number representations are as follows: Administrator Full 1Administrator R 2Administrator RW 3Administrator RWD 4Creator Full 5Creator RW 6World Full 7

World R 8World RW 9World RWD 10Power Users Full 11Power Users RW 12Power Users RWD 13System Op Full 14System Op RW 15System Op RWD 16System Full 17System RW 18System R 19Administrator RWX 20

You can use the Regdmp utility, also included with the Resource Kit, to obtain the current permissions of a registry key in the binary number format.

REM

In a batch file REM signifies a comment or REMARKadding :: at the start of a line has a similar effect

For example:

@ECHO OFF:::: First comment::REM Second commentREM::Although you can use rem without a comment to add vertical spacing to a batch file, you can also use blank lines. The blank lines are ignored when processing the batch program.

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

BugsThere are problems using a :: comment within an IF or FOR code brackete.g.@echo offFOR /L %%i IN (1,1,10) Do (Echo before comment:: Some commentEcho after comment)

The above will return the error :: was unexpected at this time.

In the script below the DIR command will set an %errorlevel%=2 if the file is not found, but the REM command is then executed successfully and resets %errorlevel%=0 If you use :: for the comment the errorlevel stays at 2.

DIR nonexistentfile.txtREM some commentECHO %errorlevel%

The problem above was fixed* in Win XP and later service packs of NT 4.

Finally in Windows 2000 and XP a comment like::%~ or REM %~ will be interpreted giving the error:The following usage of the path operator in batch-parameter substitution is invalid: %~

The bottom line on this is that you must test your comments to be sure they will be ignored as you expect.

Registry Comments

Within a registry file comments can be preceded by "; " e.g.;; Turn the NUMLOCK on at login; [HKEY_CURRENT_USER\Control Panel\Keyboard] "InitialKeyboardIndicators"="2"

FTP Comments

There is no valid comment character for FTP but you can cheat by escaping to the shell and running REMe.g.

C:\WORK>type ftpscript!REM This is a remarkbye

C:\WORK>ftp -s:ftpscriptftp> !REM This is a remarkftp> bye

C:\WORK>

* The errorlevels set by DIR are different under Windows NT 4 and XP

"First they ignore you, Then they laugh at you, Then they fight you, Then you win" - Gandhi

Equivalent Linux BASH commands:

### - Comment / Remark

REN

Rename a file or files.

REN [drive:][path]old_filename new_filenameRENAME 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. e.g. REN *.txt *.xyz REN c:\MyFile.txt *.xyz REN c:\MyFile.txt ????.xyz"We may dig in our heels and dare life never to change, but, all the same, it changes under our feet like sand under the feet of a sea gazer as the tide runs out. Life is forever undermining us. Life is forever washing away our castles, reminding us that they were, after all, only sand and sea water." - Erica Jong (Parachutes and Kisses)

Related Commands:

MOVE - Move a file from one folder to another StampMe.cmd - Batch file to rename a file to include the current date and time.

Equivalent Linux BASH commands:

mv - Move or rename files or directories

REPLACE

Replace or update one file with another

Syntax REPLACE Source_PathName Destination_path [/A] [/P] [/R] [/W]

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 Commands:

ROBOCOPY - MOVE - Move files from one folder to another folder on the same driveDEL - Delete one or more filesCOPY - Copy one or more files to another location

Equivalent Linux BASH commands:

install - Copy files and set attributes

RD

Delete folder(s)

Syntax RD pathname RD /S pathname RD /S /Q pathname Key /S : Delete all files and subfolders in addition to the folder itself.

Use this to remove an entire folder tree.

/Q : Quiet - do not display YN confirmationPlace 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 commands:CD - Create folder(s)DEL - Delete selected files from an entire folder treeDelrp - Delete a file/directory and NTFS reparse points.(Win 2K ResKit) INUSE - updated file replacement utility (may not preserve file permissions)

Equivalent Linux BASH commands:

rmdir - Remove folder(s)rm -rf - Delete directory recursively

RDISK

Create a Recovery Disk

Syntax RDISK

RDISK /s

Key

s : Update the repair informationA nation is not in danger of financial disaster merely because it owes itself money" - Andrew William Mellon

Related Commands:

In Windows 2000 this command is integrated into the system backup utility.

To create a set of NT 4 boot diskettes - the command WINNT32 /OX can be used from the install CD

FORMAT - Format a disk

RMTSHARE.exe (Resource kit)

Manage File and Printer shares, local or on a remote server. Although missing from the Windows 2000 Resource kit, the NT version works fine under Windows 2000/2003.

Syntax Display all shares RMTSHARE \\server

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 madeOR specify /UNLIMITEDYou can include several /GRANTs in a single command line.Enclose paths that include spaces like this \\server\"long share name"="c:\long file name""How to be green? consume less, share more, enjoy life" - Penny Kemp

Related commands:

NET USE - connect to a file share REMOTE - Run a command on a remote computer (Resource Kit)RUNDLL32 - Run a DLL command (add/remove print connections)

SHARE - List or edit a file share or print share (on any computer)

Equivalent Linux BASH commands:

mount - Mount a file system

ROBOCOPY.exe (Resource Kit)

Robust File and Folder Copy.By default Robocopy will only copy a file if the source and destination have different time stamps or different file sizes.

Syntax ROBOCOPY source_folder destination_folder [file(s)_to_copy] [options]

Key file(s)_to_copy : A list of files or a wildcard. (defaults to copying *.*)

Source options /S : Copy Subfolders /E : Copy Subfolders, including Empty Subfolders. /COPY:copyflag[s] : What to COPY (default is /COPY:DAT). (copyflags : D=Data, A=Attributes, T=Timestamps). (S=Security=NTFS ACLs, O=Owner info, U=aUditing info). /COPYALL : Copy ALL file info (equivalent to /COPY:DATSOU). /NOCOPY : Copy NO file info (useful with /PURGE).

/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 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+:[R][A][S][H] : set file Attributes on destination files - add. /A-:[R][A][S][H] : set file Attributes on destination files - remove. /FAT : create destination files using 8.3 FAT file names only.

/CREATE : CREATE directory tree structure + zero-length files only. /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). /LOG+:file : output status to LOG file (append to existing log).

/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 /XO : eXclude Older - if destination file exists and is the same date or newer than the source - don't bother to overwrite it. /XC | /XN : eXclude Changed | Newer files /XX | /XL : eXclude eXtra | Lonely files and dirs. An "extra" file is present in destination but not source,

excluding extras will delete from destination. A "lonely" file is present in source but not destination excluding lonely will prevent any new files being added to the destination. /IS : Overwrite files even if they are already the same.

/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

/MAX:n : MAXimum file size - exclude files bigger than n bytes. /MIN:n : MINimum file size - exclude files smaller than n bytes.

/IT : Include Tweaked files. /XJ : eXclude Junction points. (normally included by default). /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).

/XA:[R][A][S][H] : eXclude files with any of the given Attributes /IA:[R][A][S][H] : Include files with any of the given Attributes

/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.Syntax on this page is for the XP and .Net Version of Robocopy (XP010) The NT 4 and Windows 2000 resource kits include Robocopy 1.95 but I recommend you download the XP version which fixes a number of bugs - it runs fine on NT/2K.Robocopy does not run on Windows 95, or NT 3.5. (RoboCopy is a Unicode application).

ROBOCOPY will accept UNC pathnames. 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. Examples:

:: Copy files from one server to anotherROBOCOPY \\Server1\reports \\Server2\backup *.doc /S /NP:: List all files over 32 MBytes in sizeROBOCOPY C:\work /MAX:33554432 /L:: Move files over 14 days oldROBOCOPY C:\work C:\destination /move /minage:14:: Note the MOVE option will fail if any files are open and locked.

:: The script below copies data from FileServ1 to FileServ2, the destination holds a full mirror (all files), when run regularly to synchronize the source and destination, robocopy will only copy those files that have changed (changed meaning different time stamp or different size.)@ECHO OFFSETLOCALSET _source=\\FileServ1\e$\usersSET _dest=\\FileServ2\e$\BackupUsersSET _what=/COPYALL /B /SEC /MIR:: /COPYALL :: COPY ALL file info:: /B :: copy files in Backup mode. :: /SEC :: copy files with SECurity:: /MIR :: MIRror a directory tree SET _options=/R:0 /W:0 /LOG:MyLogfile.txt /NFL /NDL:: /R:n :: number of Retries:: /W:n :: Wait time between retries:: /LOG :: Output log file:: /NFL :: No file logging:: /NDL :: No dir logging ROBOCOPY %_source% %_dest% %_what% %_options%If either the source or desination are a "quoted long foldername" do not include a trailing backslash.In Windows Vista Robocopy is set to become a standard built-in command. By copying only the files that have changed, robocopy can be used to backup very large volumes. To limit the network bandwidth used by robocopy, specify the Inter-Packet Gap parameter /IPG:n This will send packets of 64 KB each followed by a delay of n Milliseconds.

"And bring me a hard copy of the Internet so I can do some serious surfing" - Dilbert, June 1999Related Commands:

COPY - Copy one or more files to another locationXCOPY - Copy files and folders

SyncToy - Microsoft Powertoy for synchronizing two folders SI Units - Bits and Bytes, bandwidth calculations Fcopy - File Copy for MMQ (copy changed files & compress. (Win 2K ResKit) Permcopy - Copy share & file ACLs from one share to another. (Win 2K ResKit) Q323275 - Copy Security info without copying files (/SECFIX or /COPY:S)JsiFAQ 0609 - Use Robocopy for Directory Replication.

Equivalent Linux BASH command:

rsync - Remote file copy (Synchronize file trees)

ROUTE.exe

Manipulate network routing tables. Route packets of network traffic from one subnet to another by modifying the route table.

Syntax

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.*.1157.*127.**224*

"Get your kicks on ROUTE 66" - Jack Kerouac.

Related Commands:

NETSTAT-rn - Display TCP/IP network connections, routing and protocol statisticsTRACERT - Trace route to a remote host

Q140859 - Win NT TCP/IP Routing Basics

Equivalent Linux BASH commands:

ping - Test a network connectiontrace - Find the IP address of a remote host

RUNAS (Windows 2000/XP)

Execute a program under a different user account.

Syntax RUNAS [/profile] [/env] [/netonly] /user:user Program

Key /profile Option to load the user's profile (registry) /env Use current environment instead of user's. /netonly Use if the credentials specified are for RAS only. /user Username in form USER@DOMAIN or DOMAIN\USER (USER@DOMAIN is not compatible with /netonly) Program The command to execute

Examples: runas /profile /user:mymachine\administrator CMD runas /profile /env /user:SCOT_DOMAIN\administrator NOTEPAD runas /env /user:[email protected] "NOTEPAD \"my file.txt\""Enter the password when prompted. RunAs from the Windows explorer GUISelect an executable file, Shift-Right-click and select Run As..This option can be hidden by settingHKLM\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer HideRunAsVerb=1 ErrorLevelThe error level returned by RunAs is not consistent between operating systemsIn Windows 2000:- success: %ERRORLEVEL%=1- fails: %ERRORLEVEL%=0In Windows XP:- success: %ERRORLEVEL%=0- fails: %ERRORLEVEL%=1For Example VER | find "2000" > nul IF %errorlevel% EQU 0 GOTO s_2000 ::Running XP

RUNAS /user:[email protected] "mycommand.exe" IF %ERRORLEVEL%==0 Echo command succeeded goto :eof :s_2000 ::Running Windows 2000 RUNAS /user:[email protected] "mycommand.exe" IF %ERRORLEVEL%==1 Echo command succeeded goto :eofRunAs Reqires the "Secondary Logon" service to be running. "Our deepest fear is not that we are inadequate. Our deepest fear is that we are powerful beyond measure. It is our light, not our darkness, that most frightens us" - Nelson Mandela Related Commands:

AT - Run a command on a remote machine (at a scheduled time)Aaron Margosis - Running with least privilege joeware.net - CPAU (Create Process As User) like RunAs but with an options to encrypt the password.PsExec - Execute process remotely

Equivalent Linux BASH commands:

SU - Switch User

RunDLL32.exe

Run a DLL program. This command is available on all version of Windows from Win95 onwards, but the DLL's and options available do vary considerably. Many options are case sensitive.

Syntax RUNDLL32.EXE dll_name,EntryPoint [options]

Examples

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 commands:

Bruce Sanderson - Setup shared printers (PrintUI.dll)MVPS.org - Remove or upgrade Java VM DX21.com - A long list of rundll32 optionsCON2PRT - Connect or disconnect a PrinterPRNCNFG - Add, delete, or list printers / connections, set the default printer.PRNMNGR - Add, delete, or list printers / connections, set the default printer. REGSVR32 - Register or unregister a DLL WMIC PRINTER - Set printing options through WMI. Q189105 - Add Printers with No User Interaction (Win 2000)Q314486 - Add Printers with No User Interaction (Win XP)

SC.exe (Resource Kit)

Service Control - Create, Start, Stop, Query or Delete any Windows SERVICE. The command options for SC are case sensitive.

Syntax SC [\\server] [command] [service_name] [Options]

Key server : The machine where the service is running

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: type= driver|service|all Query specific types of service state= active|inactive|all Query services in a particular state only bufsize= bytes ri= resume_index_number (default=0) group= groupname Query services in a particular group

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 : 0x0To retrieve specific information from SC's output, pipe into FIND or FindStre.g. SC query messenger | FIND "STATE" SC QUERY state= all |FINDSTR "DISPLAY_NAME STATE"In the statement above the FIND command will set the ERRORLEVEL as follows

ERRORLEVEL 0 = RunningERRORLEVEL 1 = Stopped or Paused

The NET START command can be used in a similar way to check if a service is running: NET START | FIND "Service name" > nul IF errorlevel 1 GOTO :s_not_runningThe 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 registryHKLM\SYSTEM\CurrentControlSet\ControlServicesPipeTimeout (REG_DWORD)Some options only take effect at the point when the service is started e.g. the SC config command allows the executable of a service to be changed. When the service next starts up it will run the new executable. Config changes requires the current user to have “permission to configure the service”.

Examples: SC GetKeyName "task scheduler" SC GetDisplayName schedule SC start schedule SC QUERY schedule SC QUERY type= driver SC QUERY state= all |findstr "DISPLAY_NAME STATE" >svc_installed.txt SC \\myServer CONFIG myService obj= LocalSystem password= mypassword SC CONFIG MyService binPath=c:\myprogram.exe obj=".\LocalSystem" password="" Watch out for extra spaces: SC QUERY state= all Works SC QUERY sTate =all Fails!

"There is always room at the top" - Daniel Webster

Related Commands:

DELSRV - Delete NT service INSTSRV - Install an NT service (run under a specific account)NET - manage network resourcesNETSVC - Command-line Service Controller (Win 2K ResKit)PsService - View and control servicesSCLIST - Display NT ServicesSTART /HIGH - Start a specified program or command.Svcmon - Monitor services and raise an alert if they stop. (Win 2K ResKit) Svcacls - Service ACL Editor (Win 2K ResKit)SUBINACL - Set service permissions WMIC SERVICE - WMI access to servicesList of Windows Services Q251192 - Create a Windows Service using SCQ166819 - Control Services RemotelyQ170738 - Debugging a Windows NT Service

Equivalent Linux BASH commands:

nice - Change job scheduling priority

SCHTASKS

Create, delete, edit, list, start or stop a scheduled task.Works on local or remote computers.

Syntax:

SCHTASKS /Create create_options

SCHTASKS /Delete [/S system [/U username [/P password]]] /TN taskname [/F]

SCHTASKS /Query [/S system [/U username [/P password]]] [/FO format] [/NH] [/V]

SCHTASKS /Run [/S system [/U username [/P password]]] /TN taskname SCHTASKS /End [/S system [/U username [/P password]]] /TN taskname

SCHTASKS /Change [/S system [/U username [/P password]]] {[/RU username] [/RP password] [/TR taskrun]} /TN taskname

create_options: [/S system #remote system (default is local) [/U username [/P password]]] #submit job under this name [/RU username [/RP password]] #run job under this name /SC schedule [/MO modifier] #When to run, see below [/D day] #day = MON,TUE,WED,THU,FRI,SAT,SUN [/M months] #month=JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC. [/I idletime] #1 - 999 minutes (ONIDLE task only) /TN taskname /TR taskrun #Name and pathname for task /ST starttime #HH:MM:SS (24 hour) [/SD startdate] [/ED enddate] # start and end date "dd/mm/yyyy"

query_del_options: /F Force delete, ignore warnings even if the task is currently runnning. /FO format Output format: TABLE, LIST, CSV /NH No header /V Verbose outputNotes:For MONTHLY schedules give the DAY as a number 1 - 31 (default=1)

To prompt for the password, specify /RP * or /RP noneThe User Account under which the Schedule service runs may require specific file access permissions, user permissions and drive mappings.

For the system account, /RU username can be written as "", "NT AUTHORITY\SYSTEM" or "SYSTEM", a Password is not required.

/SC schedule The schedule frequency.Valid schedules: MINUTE,HOURLY,DAILY,WEEKLY,MONTHLY, ONCE,ONSTART,ONLOGON,ONIDLE.

/MO modifiers allow finer control:

MINUTE: 1 - 1439 minutes. HOURLY: 1 - 23 hours. DAILY: 1 - 365 days. WEEKLY: weeks 1 - 52. ONCE: No modifiers. ONSTART: No modifiers. ONLOGON: No modifiers. ONIDLE: No modifiers. MONTHLY: 1 - 12, or FIRST, SECOND, THIRD, FOURTH, LAST, LASTDAY.Task Scheduler options are stored in the registryHKLM\SOFTWARE\Microsoft\SchedulingAgent\Examples: Create a daily task to run at 11 pm

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

Delete the task above

SCHTASKS /Delete /TN "MyDailyBackup" /f"We don't wake up for less than $10,000 a day" - Linda Evangelista Equivalent Linux BASH commands:

cron - Daemon to execute scheduled commands crontab - Schedule a command to run at a later time

SCLIST (Resource Kit)

Display NT Services

Syntax SCLIST [options] [ComputerName]Key -r : Display only running services

-s : Display only stopped services

ComputerName : The computer running the services (default = %ComputerName% )Related commands

NET - Manage network resourcesSC - Service Control MODE CON - Configure width of CMD windowNETSVC - Command-line Service Controller (Win 2K ResKit)

Equivalent Linux BASH commands:

ps - list processes

Script-it.exe (NT 4 Server)

Control GUI applications - feed values into dialogue boxes, press OK etc

Syntax SCRIPTIT script_fileScript-It.exe is no longer available for download at Microsoft.com- an alternative is the freeware tool AutoIt  Originally for NT4 Server, although it does run (rather crankily) on more recent OS'sScript-it works by recognising the Window Title of each open Application / Document / Dialogue box.

The script_file has to be prepared in advance with all the keystrokes you want to send to the appropriate Window.

The script_file is a text file in .ini format.

Example Script file:runwait=notepad.exe Untitled - Notepad=Hello World run=calc.exe

This will launch an instance of Notepad and then send the string "Hello World", when notepad.exe is closed the script will run CALC.exe

To TAB through dialogue boxes and send other keys follow the syntax shown below

KeySendKey Equivalent

Description

~ {~} send a tilde (~)

! {!}send an exclamation point (!)

^ {^} send a caret (^)+ {+} send a plus sign (+)Alt {ALT} send an Alt keystroke

Backspace {BACKSPACE}send a Backspace keystroke

Clear {CLEAR} Clear the field

Delete {DELETE}send a Delete keystroke

Right Arrow {RIGHT}send a Right Arrow keystroke

Down Arrow {DOWN}send a Down Arrow keystroke

End {END} send an End keystroke

Enter {ENTER}send an Enter keystroke

Escape {ESCAPE} send an Esc keystrokeF1 through F16

{F1} through {F16}

send the appropriate Function key

Page Down {PGDN}send a Page Down keystroke

Space {SPACE}send a Spacebar keystroke

Tab {TAB} send a Tab keystroke{ {{}  } {}}  [ {[}  ] {]}  CAPSLOCK {CAPSLOCK}  People in the West are always getting ready to live - Chinese proverb

Related Commands:

WshShell.SendKeys - Send Keys with WSHCLIP - Copy STDIN to the Windows clipboard.

The freeware tool AutoIt is available from hiddensoft.com/autoIt3/

SET

Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.

Syntax SET variable SET variable=string SET /A variable=expression SET variable= SET /P variable=[promptString] SET "

Key variable : A new or existing environment variable name

string : A text string to assign to the variable. expression: : Arithmetic Sum

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.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 "Arithmetic expressions (SET /a)

The expression to be evaluated can include the following operators: Multiply * Divide / Add + Subtract - Modulus % AND & OR | XOR ^ LSH << RSH >> Multiply Variable *= Divide Variable /= Add Variable += Subtract Variable -= AND Variable &= OR Variable |= XOR Variable ^= LSH Variable <<= RSH Variable <<=Prompt for user inputSET /P variable=[PromptString] The /P switch allows you to set a variable equal to a line of input entered by the user.

The PromptString is displayed before the user input is read. The PromptString can be empty. To place the first line of a file into a variable:Set /P _MyVar=<MyFilename.txtDisplay variables

Type SET without parameters to display all the current environment variables.

Type SET with just a variable name to display that variable

SET _department

Alternatively use the ECHO command:

ECHO [%_department%]

The SET command invoked with a string (and no equal sign) will display a wildcard list of all matching variablese.g. Display variables that begin with 'Pro':SET proDisplay variables that begin with an underscore '_'SET _ Examples

Storing a text string:

C:\>SET _department=Sales and MarketingC:\>set _ _department=Sales and MarketingOne variable can be based on another, but this is not dynamicE.g.C:\>set xx=fishC:\>set yy=%xx% chipsC:\>set yyyy=fish chipsC:\>set xx=sausageC:\>set yyyy=fish chipsC:\>set yy=%xx% chipsC:\>set yyyy=sausage chipsSET can be CALLed allowing a variable substring to be evaluated: SET start=10 SET length=9 SET string=The quick brown fox jumps over the lazy dog CALL SET substring=%%string:~%start%,%length%%% ECHO (%substring%) Deleting an environment variable

Type SET with just a variable name and an equals signFor example:

SET _department=

To be sure there is no trailing space after the command use(SET _department=)

Variable names can include Spaces

A variable can contain spaces and also the variable name itself may contain spaces, therefore the following assignment:SET my var=MyTextwill create a variable called "my var"

SimilarlySET _var =MyTextwill 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 doSET "_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 notfound in the current environment.This can be detected using the IF ERRORLEVEL commandUsing variables in a SET /a calculation Enclose any logical expressions in "quotes"

Several calculations can be put on one line if separated with commas.

Any SET /A calculation that returns a fractional result will be rounded down to the nearest whole number.

For example: SET /A _result=2+4 (=6)

set /a _result=2+4, _amount -= 20

SET /A _result="2<<3" (=2 Lsh 3 = binary 10 Lsh 3 = binary 10000 = decimal 16) SET /A _result=5 %% 2 (=5/2 = 2 + 2 remainder 1 = 1) SET /A _result=5 (=5) SET /A _result+=5 (=10) SET /A _result+=5 (=15)

SET /A _result=7 && 6 (=binary 111 AND binary 110 = binary 110 = 6)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.

For example:

SET /A _result=5 + NUMBER_OF_PROCESSORS:: this will return 6

SET /A _result="NUMBER_OF_PROCESSORS + 5":: this will return 6

SET /A _result="5 + NUMBER_OF_PROCESSORS":: this will return 5This last result demonstrates a minor bug present in NT 4 sp3.

Leading Zero will specify Octal

Numeric values are decimal numbers, unless prefixed by 0x for hexadecimal numbers, 0b for binary numbers and 0 for octal numbers.

So 0x12 is the same as 0b10010 is the same as 022.

The octal notation can be confusing - all numeric values that start with zeros are treated as octal but 08 and 09 are not valid numbers because 8 and 9 are not valid octal digits.

This is often a cause of error when performing date arithmetic. For example SET /a _day=07 will return the value=7, but SET /a _day=09 will return an error.

Permanent Changes

Changes made using the SET command are NOT permanent, they apply to the current CMD prompt only and remain only until the CMD window is closed.To permanently change a variable at the command line use SetXor 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 timeVariables set in this way are not available to 32 bit gui programs - they won't appear in the control panel.They will appear at the CMD prompt.

If autoexec.bat CALLS any secondary batch files, the additional batch files will NOT be parsed at boot.This behaviour can be useful on a dual boot PC.If Command Extensions are disabled all SET commands are disabled other than simple assignments like:_variable=MyText

# I got my mind set on you # I got my mind set on you... - George Harrison

Related Commands:

CALL - Evaluate environment variablesSETX - Set an environment variable permanently.SETLOCAL - Begin localisation of environment variable changesENDLOCAL - End localisation of environment changes, use to return values.Parameters - get a full or partial pathname from a command line variable. PATH - Change the %PATH% environment variable.PATHMAN - This Resource Kit utility allows quick modification of both the system and user paths. Pathman can resolve many problems such as duplicate characters, and can improve performance by removing duplicate paths. For details see Pathman.wri in the resource kit.REGEDIT - Import or export registry settings WMIC ENVIRONMENT - Set environment vars through WMI. Equivalent Linux BASH commands:

env - Display, set, or remove environment variables export - Set an environment variableset - Manipulate shell variables and functions

SETLOCAL

Set options to control the visibility of environment variables in a batch file.

Syntax

SETLOCAL

SETLOCAL EnableDelayedExpansion

SETLOCAL EnableExtensions | DisableExtensionsSETLOCAL on it's own, usually at the start of a batch file, will begin localisation of Environment Variables. You might think of this as being vaguely analagous to Option Explicit in Visual Basic, however the script will still inherit all variables from the master environment/session and you will not be forced to define variables before using them (so it's not really that similar to Option Explicit at all!) Changes made to an Environment Variable after SETLOCAL has been issued are local to the batch file.

Issuing an ENDLOCAL command will restore the previous environment variables. EnableDelayedExpansion This is an often misunderstood term, I would have prefered it be called something like'Expand_Variables_Inside_FOR_Loop' To explain - when using any kind of FOR loop this is the default behaviour:@echo offsetlocal:: count to 5 storing the results in a variableset _tst=0FOR /l %%G in (1,1,5) Do (echo [%_tst%] & set /a _tst+=1)echo Total = %_tst%C:\>demo_batch.cmd[0][0][0][0][0]Total = 5Notice that when the FOR loop finishes we get the correct total, so the variable correctly increments, but during each iteration of the loopthe variable is stuck at it's initial value of 0 The same script with EnableDelayedExpansion, gives the same final result but also displays the intermediate values:@echo offsetlocal EnableDelayedExpansion :: count to 5 storing the results in a variableset _tst=0FOR /l %%G in (1,1,5) Do (echo [!_tst!] & set /a _tst+=1)echo Total = %_tst%C:\>demo_batch.cmd[0][1][2][3][4]

Total = 5Notice that instead of %variable% we use !variable! inside the FOR loop.EnableDelayedExpansion is Disabled by default.EnableDelayedExpansion may also be enabled by starting CMD with the /v switch. In some cases it can be helpful to use EnableDelayedExpansion outside a FOR loop: when combining or concatenating variables, the delimiters may be confused, by using EnableDelayedExpansion with the ! and % delimiters this can be avoided.Overloading a variable

SETLOCAL can be used more than once in the same batch file so that multiple values can be stored in one Environment Variable.

For example: @echo off ::::Standard commissionSET _Commission=20 echo %_Commission%

::Super commissionSETLOCAL set _Commission=30echo %_Commission%

::Premium commissionSETLOCAL set _Commission=40 echo %_Commission%

::Back to Super commissionENDLOCALecho %_Commission%

::back to Standard commissionENDLOCALecho %_Commission%

DISABLEEXTENSIONSCommand Extensions are enabled by default, DisableExtensions will attempt to disable Command extensions. (ENABLEEXTENSIONS - will attempt to re-enable)

SETLOCAL will set an ERRORLEVEL if given an argument. It will be zero if one of the two valid arguments is given and one otherwise.

You can use this in a batch file to determine if command extensions are available, using the following technique: VERIFY errors 2>nul SETLOCAL ENABLEEXTENSIONS IF ERRORLEVEL 1 echo Unable to enable extensions

This works because "VERIFY errors" sets ERRORLEVEL to 1 and then the SETLOCAL will fail to reset the ERRORLEVEL value if extensions are not available (e.g. if the script is running under command.com)

If Command Extensions are permanently disabled then SETLOCAL ENABLEEXTENSIONS will not restore them. "A local shop for local people" - The League Of GentlemenRelated Commands:

ENDLOCAL - End localisation of environment changes in a batch file.

Equivalent Linux BASH commands:

readonly - Mark variables/functions as readonly

SETX.exe (Resource Kit)

Set environment variables permanently

SETX can be used to set Environment Variables for the machine or currently logged on user:

   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 in this way does not take effect until next logon due to caching of registry data. The type is REG_EXPAND_SZ.

Examples:

Set the variable "_mypc" to be COMPAQ in the users permanent environment:

SetX _mypc COMPAQ

Delete the variable "_myvar" 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=GMTSetX _myTimeZone GMT

Store the value of %my_important_var% in a second environment variable. SetX _mybackupvar %my_important_var%

Sets the value of _mypath to ALWAYS be equal to the value of the %PATH% environment variable even in the event that the PATH variable changes:SetX _mypath ~PATH~

Machine variables

These are stored on the machine and won't follow a users roaming profile. To set a machine variable (-m) requires Administrator rights.

Create a machine variable:

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 Commands:

SET - Display, set, or remove environment variablesREG - Delete keys or values from the registry Q104011 - Modify variables by editing the RegistrySETENV - Vincent Fatica's improved version

Equivalent Linux BASH commands:

env - Display, set, or remove environment variables export - Set an environment variable

SHARE.VBS (Resource Kit)

List or edit a file share or print share (on any computer)

Although missing from recent Resource Kits, this VBS script does still work under 2K/XP. The preferred method for creating shares is the RMTShare command, which can also grant permissions.

Syntax: List Shares Share.vbs /L [/S <server>] [/U <username>] [/W <password>] [/O <outputfile>] Create a Share Share.vbs /C /N <name> /P <path> [/T <type>] [/V <description>] [/S <server>] [/U <username>] [/W <password>] [/O <outputfile>] Delete a Share Share.vbs /D /N <name> [/S <server>] [/U <username>] [/W <password>] [/O <outputfile>]

Options:

/L List /C Create /D Delete /N name Name of the share to be created or deleted. /P path Path of the share to be created. /v description A description for the share. /T type Type of the share to be created. (Disk, Printer, IPC or Special) /S server A machine name. /U username The current user's name. /W password Password of the current user. /O outputfile Output file name.Examples:

List the shares on the machine \\Frodocscript Share.vbs /L /s FrodoCreate 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 \\Frodocscript Share.vbs /d /n scratch /s Frodo

"The inherent vice of capitalism is the unequal sharing of blessings,the inherent vice of Socialism is the equal sharing of miseries." - Winston Churchill

Related Commands:

CACLS - Display or modify Access Control Lists (ACLs) for files and foldersRMTShare - The preferred method for creating a file system share (it can also grant permissions)RUNDLL32 - Run a DLL command (add/remove print connections)Equivalent Linux BASH commands: mount - Mount a file system

SHIFT

Change the position of command line parameters in a batch file.

Syntax SHIFT [/n]for example:given %1=one, %2=two, %3=three...SHIFTwill result in %1=two, %2=three

alternatively given %1=one, %2=two, %3=three...SHIFT & SHIFTwill result in %1=three/n tells the SHIFT command to start shifting at the nth argument, where n may be between zero and eight.

for example:given %1=one, %2=two, %3=three, %4=four...SHIFT /2will result in %1=one, %2=three, %3=four

%0 is the name of the batch file itself - %1 can be shifted into %0

Relative pathnames

The parameter %0 will initially refer to the path that was used to execute the batch - this could be MyBatch.cmd if in the current directory or a full path like C:\apps\myBatch.cmd

When SHIFT is used to move a text parameter into %0 then references to %0 will refer to the current working directory, unless those parameters happen to contain a valid path.

For example:

%0\..\MyExecutable.exe

will run the executable from the same directory

If the following parameter is passed to myBatch.cmd

myBatch.cmd D:\utils\

Then the following commands in myBatch will run MyExecutable.exe from the directory D:\utils\

SHIFT %0\..\MyExecutable.exe

If Command Extensions are disabled, the SHIFT command will not support the /n switch "If NumLock is on, pressing a key on the numeric keypad while holding SHIFT overrides NumLock and instead generates an arrow key" - OldNewThing

Related commands

CALL - Call one batch program from anotherSET - Display or edit environment variables

Equivalent Linux BASH commands:

shift - Shift positional parameters

SHORTCUT.exe (Server Resource Kit)

Create a windows shortcut (.LNK file)

Syntax SHORTCUT [options]

Key Source options -t target : The path and file name of the application. -a arguments : The arguments passed when the shortcut is used. -d directory : The folder to start the application in.

-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 non tracking (Stupid)

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 fileIf 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"Alternatively use WSH to create a shortcut:optional sections in the VBscript below are commented out Set oWS = WScript.CreateObject("WScript.Shell") sLinkFile = "C:\MyShortcut.LNK" 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

Resolve Shortcut Links

If a shortcut to a file breaks, then by default Windows will attempt to automatically locate the shortcut destination by performing a simple search. To change this default - edit the registry:

HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\ExplorerNoResolveTrack=1(DWORD)This can also be controlled at Group Policy level in: User Config\Admin Templates\Start Menu & Taskbar. If a shortcut .LNK file is copied to another machine, then by default the shortcut's target may be automatically updated - e.g. create a shortcut on Machine1 to C:\AUTOEXEC.BAT when copied to Machine2 the shortcut will point back to \\Machine1\c$\AUTOEXEC.BAT To change this default - add this to the registry before creating the shortcut:

HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer"LinkResolveIgnoreLinkInfo"=dword:00000001FavouritesOften 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 ShawRelated Commands:

MD - Create folder(s)Slow Network browsing (XP)NTFAQ - Disable NTFS resolving of broken shortcutsFSUTIL - Create a Hardlink Q158682 - Shortcuts created resolve to UNC Path (Link Tracking)Q150215 - Disable Automatic Shortcut Resolution Q263324 - Shortcut Command truncates path names

Equivalent Linux BASH commands:

symlink - Make a new name for a fileln - Make links between files

SHOWGRPS (Resource Kit)

List the NT Workgroups a user has joined.

Syntax SHOWGRPS domain\username SHOWGRPS usernameIf no username is specified SHOWGRPS will list the workgroups for the currently logged in user.

For Example

SHOWGRPS john.smith

"Justice is such a fine thing that we cannot pay too dearly for it" - Alain-Rene Lesage

Related Commands:NET - add or remove a user from a workgroupFINDGRP - List the (global or local) security groups a user has joined (NT 4 Reskit) SHOWMBRS - List the members of an NT WorkgroupGRPTEST - SMS support tools - enumerate group membership for a user account. SHOWACCS - Show access profile (Windows 2000)

SHOWMBRS (Resource Kit)

List all the users who are members of a Workgroup.

Syntax SHOWMBRS domain\NT_Workgroup SHOWMBRS NT_WorkgroupA workgroup must be specified.

Example:

SHOWMBRS wg_finance

Related Commands:

NET GROUP - add or remove a user from a workgroupSHOWGRPS - List the Workgroups a user is inSHOWACCS - Show access profile (Windows 2000)GRPTEST - SMS support tools - enumerate group membership for a user accountWHOAMI /all - List all workgroups

SHUTDOWN.exe

Shutdown the computer

Syntax

SHUTDOWN [logoff_option] [/m \\Computer] [options]

logoff_option: /i Display the GUI (must be the first option) /l Log off. This cannot be used with /m or /d option /s Shutdown /r Shutdown and Restart /a Abort a system shutdown. (only during the time-out period) /p Turn off the local computer with no time-out or warning (only with /d) /h Hibernate the local computer (only with /f ) /e Document the reason for an unexpected shutdown of a computer

options:

/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 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 onlyExample:To create a desktop shortcut that will immediately shutdown your system - set the shortcut Target Properties to: C:\Windows\System32\shutdown.exe -s

When using this command to reboot a server, the shutdown process will normally allow about 30 seconds to ensure each running service has time to stop. The shutdown can be made faster if all the services are first halted using NET STOP

e.g.net stop "Microsoft Exchange Internet Mail Service"net stop "Microsoft FTP Service"net stop "Some other Service"SHUTDOWN /t:25 /rTypical 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 UnresponsiveE 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: UnresponsiveE 4 6 Application: Unstable U 5 15 System Failure: Stop errorE 5 19 Security issue U 5 19 Security issueE P 5 19 Security issueE 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

e.g. SHUTDOWN /r /d P:2:17"The man who is tired of London is tired of looking for a parking space" - Paul Theroux

Related Commands:

LOGOFF - Log off a user.BootCFG - Edit Boot.ini settings.

PsShutdown - SysInternals command line tool PowerOff - Stefan Kuhr utility (NT / 2K)JSIFAQ Tip 9130 - log off user after n minutes of inactivity

SLEEP.exe (Resource Kit)

Add a fixed delay to a batch file

Syntax SLEEP timeKey time : the number of seconds to pauseFor example: To pause for an hour before running the next command in a batch file:

SLEEP 3600

AlternativeA fixed delay can also be produced by the PING command with a loopback address:

e.g. for a delay of 60 seconds:PING -n 61 127.0.0.1>nul See Clay Calvert's newsgroup posting for a full explanation of this technique.

"I think men talk to women so they can sleep with them and women sleep with men so they can talk to them" Jay McInerney Related Commands:

TIMEOUT - Delay that allows the user to continueWAIT - the same as sleep but with noisesWScript.Sleep - Sleep

Equivalent Linux BASH commands:

crontab - Schedule a command to run at a later time

SOON.exe (Resource Kit)

Schedule a command to run in the near future (calls the AT command)

Syntax SOON [\\computername] delay [/interactive] "command" SOON /i:[on|off]

Key delay : When the command should run, in SECONDS from now. default=5

/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 behaviourSOON 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 to be sure that they:

Start at the expected time Execute the correct commands (specify a full pathname)

Finish and close successfully.

This command will work with both the NT 4 "Schedule" service (ATSVC) or with the "Task Scheduler" service in more recent versions of Windows. "We want the finest wines available to humanity. And we want them here and we want them now" - Bruce Robinson (Withnail and I ) Related Commands:

AT - Schedule a command to run at a later timeQ237840 - Setting a delay of less than 60 seconds.Q226370 - IE 5 bugs related to the Task Scheduler (fixed in IE 5.01)

Equivalent Linux BASH commands:

cron - Daemon to execute scheduled commandscrontab - Schedule a command to run at a later time watch - Execute/display a program periodically

SORT

Sort will accept a redirected or piped file input and TYPE the file, sorted line by line.

Syntax SORT [options]

Options /R : Reverse sort order (Z to A, 9 to 0)

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

Windows NT 4 does not support any of the above options other than /R and +n 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 Commands:

TYPE - Display the contents of a text fileRedirection - Redirect files, command output and error messages

Equivalent Linux BASH commands:

sort - Sort text files

START

Start a specified program or command in a separate window.

Syntax START "title" [/Dpath] [options] [command] [parameters]

Key WHAT to run

path : Starting directory command : The NT Command, Batch file or executable program to run parameters : The parameters passed to the command

HOW to run it

/MIN : Minimized /MAX : Maximized /WAIT : Start application and wait for it to terminate /LOW : Use IDLE priority class /NORMAL : Use NORMAL priority class /HIGH : Use HIGH priority class /REALTIME : Use REALTIME priority class "title" : Text for the CMD window title. /B : Start application without creating a new window. In this case ^C will be ignored - leaving ^Break as the only way to interrupt the application /I : Ignore any changes to the current environment.

Options for 16-bit WINDOWS programs only

/SEPARATE Start in separate memory space (more robust) /SHARED Start in shared memory space (default)ExamplesSTART "My Login Script" /Min Login.cmdSTART "" /wait MySlowProgram.exeNotes:Although ["title"] is supposedly an optional parameter, when it is omitted other options may be interpreted as being the title - so to be absolutely sure put something in like "My Script" or just a pair of empty quotes "".

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 PrintersA new printer can be installed very quickly (and the driver downloaded) with the commandSTART \\print_server\printer_name

Setting a Working DirectoryTo start an application and specify where files will be saved

START /Dc:\Documents\ /MAX notepad.exe

Note that START /D does not support long filenames which contain spaces, a workaround is to use the 8.3 compatible name(s)

Forcing a Sequence of ProgramsIf 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 offstart /wait /b First.exestart /wait /b Second.exestart /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> runsWhen <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 extensionsWhen executing a command line whose first token does NOT contain an extension, then CMD.EXE uses the value of the PATHEXT environment variable to determine which extensions to look for and in what order. The default value for the PATHEXT variable is:

.COM;.EXE;.BAT;.CMD

Notice the syntax is the same as the PATH variable, with semicolons separating the different elements.

When executing a command, if there is no match on any extension, then NT will look to see if the name, without any extension, matches a directory name and if it does, the START command will launch Explorer on that path.

"Do not run; scorn running with thy heels" - Shakespear, The Merchant of Venice

Related commands:

CALL - Call one batch program from another CMD - can be used to call a subsequent batch and ALWAYS return even if errors occur.GOTO - jump to a label or GOTO :eof

Q162059 - Opening Office documents

Equivalent Linux BASH commands:

.period - Run commands from a file

SU (Resource Kit)

Switch User.

Syntax SU "[cmdline]" [domain] [[Winsta\]Desktop] [options]

Key cmdline The command to run (default =%comspec%) domain The domain for the user account ('.' = local m/c) Winsta\Desktop The profile to load (default = current)

Options

-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 verboseAll LogOn Types require specific User Rights to be granted...SeNetworkLogonRight, SeServiceLogonRight, SeInteractiveLogonRight, SeBatchLogonRightBugs: see Q265401The RUNAS command is a lot easier to use!

"Our deepest fear is not that we are inadequate. Our deepest fear is that we are powerful beyond measure. It is our light, not our darkness, that most frightens us" - Nelson Mandela Related Commands:

RUNAS - Execute a program under a different user account. PsExec - Execute process remotely

Equivalent Linux BASH commands:

su - Run a command with substitute user and group id

SUBINACL.exe (Resource kit)

Download latest version (2004)Display or modify Access Control Entries (ACEs) for file and folder Permissions, Ownership and Domain.

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

Syntax SUBINACL [/noverbose] /object_type object_name [/action=parameter] [/help]

Key object_type: service e.g. /service Messenger \\ServerName\Messenger keyreg e.g. /keyreg HKEY_CURRENT_USER\Software /keyreg \\Srv\HKEY_LOCAL_MACHINE\KeyPath file e.g. /file *.obj /file c:\test.txt /file \\ServerName\Share\Path subdirectories manipulate files in specified directory and all subdirectories

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.

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" /displayRestore Permissions:subinacl /nostatistic /playfile my.log Change owner :subinacl /file C:\demofile.doc /setowner=MYDOMAIN\BillGBugsRunning subinacl against a subfolder, as in the example above will affect just that folder and it's contents. However if you run subinacl against a folder in the root of the drive it will scan the entire drive for folders matching that name (which can take some time).e.g.subinacl /subdirectories "C:\Spud"Will also matchC:\Program Files\SpudC:\Documents and Settings\Spud etc

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

Related Commands:

ATTRIB - Display or change file attributesPERMS - Show permissions for a userFIXACLS - Restore default privs (Resource Kit supplement 2)SHOWACL - Show file Access Control Lists (Windows 2000)XCACLS - Display or modify Access Control Lists (ACLs) for files and folders

Q245031 - Change Registry Permissions from the command line Q265360 - Change multiple Subdirectory PermissionsQ288129 - Grant users the right to manage services

Equivalent Linux BASH commands:

chmod - Change access permissionschown - Change file owner and group

SUBST

Substitute a drive letter for a network or local path.

Syntax SUBST drive_letter: path

SUBST SUBST drive_letter: /D

Key SUBST with no parameters will display current SUBST drives

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

BugsUnder NT 4 SUBST'ed drives cannot be disconnected using the Explorer GUI - this was fixed in Windows 2000.

In Windows 2000 (and above) you will have problems creating, accessing and deleting drive mappings with SUBST.

However under Win 2K/XP the functionality of the NET USE command is improved so you can now do NET USE g: \\server\share\folder1\folder2

If the network resource is unavailable (ie the server is down) SUBST will continually retry - unlike NET USE which will try to connect once and fail - depending on your application this may be a good or a bad thing - a subst drive that is not available will badly impact performance of most applications.

Notice that when SUBST is used against a local shared folder, it will create a RECYCLER for that drive. The RECYCLER is not removed when the drive substitution is removed, but can be deleted manually.

"A man should never be ashamed to own he has been in the wrong, which is saying in other words, that he is wiser today than he was yesterday" - Alexander Pope (thoughts on various subjects)

Related Commands:

NET USE - Map a drive letter to a network drive

SYSTEMINFO

List system configuration

Syntax SYSTEMINFO [/S system [/U username [/P [password]]] ] [/FO format] [/NH]

Key: /S system Remote system to connect to. /U [domain\]user User context under which to execute. /P [password] Password for the given user (will prompt if omitted) /FO format Output format: TABLE, LIST or CSV /NH No "Column Header" in the Table/CSV outputThe output includes OS configuration, security info, product ID, RAM, disk space, and network cards.ExamplesSYSTEMINFO SYSTEMINFO |find "Total Physical Memory:"SYSTEMINFO /S wkstn6324 SYSTEMINFO /S wkstn6325 /FO CSV /NH >>pcaudit.csv

"Thought is fugitive; the mind does not repeat itself; if you do not catch the whisperings of the oracle as they come to you, they are lost forever. You must; and this is absolutely essential; convince yourselves that what is offered you this very moment will never be offered again" - Jean Guitton

Related Commands:

WINMSD - Windows system diagnosticsWMIC - WMI CommandsPsGetSid - Display the SID of a computer or a user

TASKLIST (Win XP)

TaskList displays all running applications and services with their Process ID (PID) This can be run on either a local or a remote computer.

(Under Win NT 4 use the resource kit tool TList.)

Syntax tasklist optionsKey

/s computer Specify the name or IP address of a remote computer (do not use backslashes). The default is the local computer.

/u domain\user [/p password]] Run under a different account

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

Status eq, ne RUNNING|NOT RESPONDING Imagename eq, ne String PID eq, ne, gt, lt, ge, le

Positive integer. Session eq, ne, gt, lt, ge, le Any valid session number. SessionName eq, ne String CPUTime eq, ne, gt, lt, ge, le Time hh:mm:ss MemUsage eq, ne, gt, lt, ge, le Any valid integer. Username eq, ne User name ([Domain\]User). Services eq, ne String Windowtitle eq, ne String Modules eq, ne String

/m [ModuleName] | /svc | /v /m Show the processes that include the given module. /svc List all info for each process without truncation. Valid when /fo=TABLE. Cannot be used with /m or /v /v Verbose task informationExamples:tasklist /v /fi "STATUS eq running"

tasklist /v /fi "username eq ORACLE_SERVICE_ACCOUNT"

WMIWMIC can also list running processes and parameterse.g.

WMIC /OUTPUT:C:\ProcList.txt PROCESS get Caption,Commandline,Processid"The longer the title, the less important the job." - George McGovern

Related Commands:

PsList - List detailed information about processesPSTAT - display running tasks including all Process Threads.MEM - Display memory usage WINMSD - Windows NT Diagnostics (including Physical Memory)

Equivalent Linux BASH commands:

top - List running processes on the systemtime - Measure Program Resource Usetimes - User and system times

TIME

Display or set the system time.

Syntax TIME [new_time]

TIME

TIME /T

key new_time : The time as HH:MM

TIME with no parameters will display the current time and prompt for a new value. Pressing ENTER will keep the same time.

/T : Just display the time, formatted according to the current Regional settings.Time Formatting

In Control Panel, Regional settings a Time Appearance can be set. This can be used to change the separator, and the number of characters used to display hours and minutes.

To display the time including Seconds:

ECHO.| TIME will display the time, including seconds and hundredths of a second

Time Format information in the Registry

The Country Code is a user setting in the registry:

[HKEY_CURRENT_USER\Control Panel\International] "iCountry"="44"

The Country Code can be read using REG.exe as followsFOR /F "TOKENS=2,3*" %%A IN ('REG QUERY "HKEY_CURRENT_USER\Control Panel\International\iCountry"') DO (FOR %%G in (%%A) DO (SET _country=%%G)) The time separator is also a registry setting

[HKEY_CURRENT_USER\Control Panel\International] "sTime"=":"

The time separator can be read using REG.exe as followsFOR /F "TOKENS=2,3*" %%A IN ('REG QUERY "HKEY_CURRENT_USER\Control Panel\International\sTime"') DO (FOR %%G in (%%A) DO (SET _time_sep=%%G))The time formats for different country codes are as follows: Country or language CountryCode Date format Time format

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

"To me when a mother puts food in a microwave for her children, it is an act of hate" - Raymond Blanc

Related Commands:

DATE - Display or change the dateNOW - Display Message with Current Date and TimeTIMESERV - Time Service (resource kit)W32TIME - Time Service (y2K compliant update for TIMESERV)Timethis - Time how long it takes the system to run a command. (Win 2K ResKit) Uptime - Time since last reboot. (Win 2K ResKit) GetTime.cmd - Script to get current time GMT.cmd - Current time in GMT (World Time)

Equivalent Linux BASH commands:

date - Display or change the date & time

TIMEOUT.exe (Resource Kit)

Delay execution of a batch file.

Syntax TIMEOUT delay

Key delay :Delay in seconds (between -1 and 100000) to wait before continuing. The value -1 causes the computer to wait indefinitely for a keystroke (like the PAUSE command)Timeout will pause command execution for a number of seconds, after which it continues without requiring a user keystroke. If the user does press a key at any point, execution will resume immediately. Timeout.exe seems to consume less processor time time than Sleep.exe

"It is awful work this love and prevents all a mans projects of good or glory" - Lord Byron

Related Commands:

PAUSE - Suspend processing of a batch file and display a messageSLEEP - Fixed delayWAIT - Fixed delay

TITLE

Change the title displayed above the CMD window.

Syntax TITLE [string]

Key string : The title for the command prompt window.

The default title is %comspec% To change the title for the duration of a command use: TITLE This is the initial title text CMD /c MyBatchFile.cmd ...If MyBatchFile.cmd contains a different TITLE command it will revert when the second command session ends.

"The longer the title, the less important the job." - George McGovern.

Related commands:

MODE - change the size of the CMD windowCOLOR - change the colour of the CMD windowPROMPT - change the CMD window promptQuickEdit mode - also changes the title (temporarily)

TOUCH (Resource Kit)

Change file timestamps

Syntax TOUCH [option]... files ...

Key /t year month day hour minute secondThis 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"I believe entertainment can aspire to be art, and can become art, but if you set out to make art you're an idiot" - Steve Martin

Related commands:

Q299648 - Date and Time Stamps for Files and FoldersCOPY - Copy one or more files to another location

Equivalent Linux BASH commands:

touch - Change file timestamps

TRACERT

Trace Route - Find the IP address of any remote host. TRACERT is useful for troubleshooting large networks where several paths can be taken to arrive at the same point, or where many intermediate systems (routers or bridges) are involved.

Syntax TRACERT [options] target_name

Key target_name The HTTP or UNC name of the host

Options: -d Do not resolve addresses to hostnames. (avoids performing a DNS lookup)

-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) calculationTTL 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 Exceeded messages 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.FirewallsMany 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_serverGet your kicks on ROUTE 66 - Jack Kerouac.

Related Commands:

NSLOOKUP - Name server lookup PING - Test a network connectionPATHPING - Trace route and provide network latency and packet loss for each router and link in the path.ROUTE - Manipulate network routing tables

Q162326 - Using TRACERT to Troubleshoot TCP/IP Problemstip 4723 - A better description from JSIincTRACE.BAT - handy report on any given Internet addresstracert.com - trace routes from remote locations

Equivalent Linux BASH commands:

trace - Find the IP address of a remote host

TYPE

Display the contents of a text file or files.

Syntax TYPE [drive:]pathname(s)If more than one file is specified the filenames are included in the output.If a wildcard is used the filenames are not displayed.

Output can be redirected into a new file:

TYPE file.txt > Newfile.txt

Output can be appended to an existing file:

TYPE file.txt >> ExistingFile.txt

To do the same with user console input :

TYPE CON > Newfile.txt

This will require a CTRL - Z to indicate end of file.

When using redirection to SORT a file the TYPE command is used implicitlyFor example:

SORT < MyFile.txtIf you TYPE a Unicode text file, the output will be ANSI. eg: TYPE UnicodeFile.txt > ANSIFile.txtTo convert multiple Unicode files to ASCII try this script@echo offren *.txt *.txxfor %%G in (*.txx) do (TYPE %%G >%%~nG.txt)echo del *.txx"There are few more impressive sights than a Scotsman on the make" - Sir James Barrie

Related Commands:

FOR /F SORTList - Text Display and Search Tool (Win 2K ResKit)

Equivalent Linux BASH commands:

cat - Display the contents of a file

VER

Display the current operating system version.

Syntax

VER

Use ver to find specific operating systems like this:

@ECHO OFF

:: Win9x checks ::::::::::::

VER |find /i "Windows 95" >NUL IF NOT ERRORLEVEL 1 GOTO W9598ME

VER |find /i "Windows 98" >NUL IF NOT ERRORLEVEL 1 GOTO W9598ME

VER |find /i "Windows Millennium" >NUL IF NOT ERRORLEVEL 1 GOTO W9598ME

:: NT/XP checks ::::::::::::

VER | find "XP" > nul IF %errorlevel% EQU 0 GOTO s_win_XP

VER | find "2000" > nul IF %errorlevel% EQU 0 GOTO s_win_2000

VER | find "NT" > nul IF %errorlevel% EQU 0 GOTO s_win_NT

ECHO Unknown OS ! GOTO :EOF

:: Win9x commands ::::::::::::

:W9598ME ECHO Win9x commands go here GOTO :EOF

:W98 ECHO Win98 commands go here GOTO :EOF

:: NT/XP commands ::::::::::::

:s_win_XP ECHO XP commands go here goto :eof

:s_win_2000 ECHO WIN2K commands go here goto :eof

:s_win_NT ECHO NT4 commands go here goto :eof

:EOF (End-of-file)Service Pack VersionThis Batch script will give the Service Pack level.Works for NT, Win2K or WinXPBugs

The VER command reports the version of CMD.exe, so if for example you run the Win XP version of CMD under NT 4 then the VER command will return:Microsoft Windows XP [Version 4.0.1381]Related Commands:

Q190899 - How to Determine the OS Type in a Logon Script WINVER.exe - Opens the GUI Version dialogue box (Help, About) FILEVER - DLL version information (Resource Kit, XP Support tool)

Equivalent Linux BASH commands:

uname -r - Print system information

VERIFY

To check that files are saved to disk correctly; the system can 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 OFFWindows Explorer will always copy with verify ON

Copying files can be up to twice as fast with verify OFF.

VERIFY without a parameter will display the current setting.

"VERIFY dummy_text" will set %ERRORLEVEL% to 1

"Women might be able to fake orgasms. But men can fake whole relationships." - Sharon Stone

Related Commands:

MOVE - Move files from one folder to another

Equivalent Linux BASH commands:

cksum - Print CRC checksum and byte counts

VOL

Display the volume label of a disk.

Syntax VOL [drive:]If they exist, VOL will display both the disk label and serial number.

Related Commands:

LABEL - Edit the volume label of a diskBootCFG - Edit Boot.ini settings.

Equivalent Linux BASH commands:

hostname - Print or set system name uname - Print system information

WHERE (2K Resource Kit / .Net Server)

Locate and display files in a directory tree.

The WHERE command is roughly equivalent to the UNIX 'which' command.For early versions of windows that don't have this command you can use this WHICH batch file.

By default, the search is done in the current directory and in the PATH.

Syntax WHERE [/r Dir] [/q] [/f] [/t] Pattern ...

key /r A recursive search, starting with the specified Dir directory.

/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.ExamplesTo find all files named 'Zappa' in drive C: (including subdirectories)WHERE /r c:\ Zappa

To find all files named 'Zappa' in drive C: of the remote computer 'MyPC' and its subdirectories, and report the executable type for executable files

WHERE /r \\MyPC\c /e Zappa.*

Related commands:

CD - Change DirectoryTYPE - Display the contents of a text file

Equivalent Linux BASH commands:

which - Show full path of commands

WHOAMI.exe (Resource kit)

Displays the username and domain for the currently logged in user.

The whoami output is the same as the 2 environment variables %USERDOMAIN% and %USERNAME%.

So the same output can be achieved with

ECHO %USERDOMAIN%\%USERNAME%

Under Windows 2000 there is an additional switch WHOAMI /all - this shows all permissions and group memberships.

"We can now manipulate images to such an extrodinary extent that there's no lie you cannot tell" - Sir David Attenborough

Related Commands:

SET - Display, set, or remove Windows NT environment variablesVER - Display version information VOL - Display a disk labelWhereami.cmd - Display user information

Equivalent Linux BASH commands:

id - Print user and group id'swho - Print who is currently logged in whoami - Print the current user id and name (`id -un')

WinDiff

Compare the contents of two files or sets of files with a graphical interface.

Syntax windiff [path1] [path2]

Key path Individual files to compare or a directory of files to compareIf 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.DownloadsMicrosoft - Full SDK download 408098 KbWinDiff - Grigsoft (3rd party) download 75 Kb

"Shall I compare thee to a summer's day? Thou art more lovely and more temperate.Rough winds do shake the darling buds of May, And summer's lease hath all too short a date" - Shakespeare

Related Commands:

COMP - Compare two files and display any characters which do NOT matchFC - Compare two files FIND - Search for a text string in a fileFINDSTR - Search for strings in filesWinMerge (Sourceforge) Q171780 - Use WinDiff to compare registry files

Equivalent Linux BASH commands:

comm - Compare two sorted files line by line cmp - Compare two filesdiff - Display the differences between two files

WINMSD.exe

Microsoft Windows diagnosticsReports: Memory use, Services, Devices, IRQ's Ports, Environment variables, Network (rights, transport, stats), Hardware including Display adapter.

Syntax WINMSD [\\computername] options

Options: /a All details /s Summary details only

/f Send output to a file <computername.txt> in the current directory /p Send output to a printer

WINMSD with no switches will open the GUI with details of the computer you are logged into.

When a remote computername is specified then less info will be reportede.g. Diskspace and Memory won't be listedHot keys within the GUI:

SHIFT - F2 copies the current tab to the clipboard, F2 copies a summary of the current tab to the clipboard

Winmsd in Windows 2000 will actually run Msinfo32 - mmc.exe /s "C:\Program Files\Common Files\Microsoft Shared\MSInfo\MSInfo32.msc"

It is advisable to have the SERVER service running, if not - winmsd will show a warning dialogue.

Spooling output to file - if you have the resource kit WINMSDP allows more control over this.

Related Commands:

MSINFO - Windows NT diagnosticsWINMSDP - Windows NT Diagnostics IIDevCon - Device Manager Command Line Utility FSUTIL - File and Volume utilities SRVINFO - SMS support tools - partition info, running services and Network info. Dmdiag - display disk properties: Size, Status, Type...(Win 2K ResKit)

WINMSDP.exe (Resource Kit)

Windows NT diagnostics IIReports: 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 Commands:

WINMSD - Windows NT Diagnostics

Q102468 - How to use WINMSDPQ231368 - IIS/Site Server vulnerability via WINMSDPQ310747 - System File Checker (Sfc.exe)

XCACLS.exe (Server Resource Kit)

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

Syntax XCACLS filename [options]

XCACLS filename

Key If no options are specified XCACLS will display the ACLs for the file(s)

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 2003FolderSpec 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.Versions:When running this command it is important to use the correct version (NTFS standards have changed with different versions of Windows and XCACLS has been updated to suit)Early versions of xcacls may give unpredictable results against an NTFS v5 partition.xcacls.vbs is described in Q825751 and can be downloaded here - xcacls.vbs is an unsupported utility that addresses a limitation with the original xcacls.exe, specifically the inability to append permissions to a folder whose child objects have the inheritance flag set. The .vbs version does not suppport unc paths.Examples:

:: Allow guests the right to read and execute in MyFolderXCACLS MyFolder /E /G guests:rx

:: Allow guests the Full Control permission in MyFolder and all subfoldersXCACLS 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 MyFolderXCACLS MyFolder /T /P guests:x :: Take Ownership of "Application Data" folder and grant Administrators Full control (:OF) :: Preserve existing permissions (/E) & apply to subfolders (/T) XCACLS "Application Data" /E /g Administrators:OF /T"I spent most of the eighties, most of my life, riding around in somebody else's car, in possession of, or ingested of, something illegal, on my way from something illegal to something illegal with many illegal things happening all around me" - Iggy Pop

Related:

CACLS - Display or modify Access Control Lists (ACLs) for files and foldersDIR /Q - Display the owner for a list of files (try it for Program files) AccessEnum - GUI to browse a tree view of user privsNTRIGHTS - Edit user account rights PERMS - Show permissions for a userSHOWACL - 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/domainATTRIB - Display or change file attributesPermissions & Local/Global Workgroups

Permissions explained - Microsoft.com Access-based Enumeration - Set file listing to only display files you can read (Win 2003)Q245031 - Change Registry Permissions from the command line Q822790 - Xcacls /E - Objects do not inherit permissions as expected.ACL utils: SetAcl or FileACL

Equivalent Linux BASH commands:

chmod - Change access permissionschown - Change file owner and group

XCOPY

Copy files and/or directory trees to another folder. XCOPY is similar to the COPY command except that it has additional switches to specify both the source and destination in detail.

XCOPY is particularly useful when copying files from CDROM to a hard drive, as it will automatically remove the read-only attribute.

Syntax XCOPY source [destination] [options]

Key source : Pathname for the file(s) to be copied.

destination : Pathname for the new file(s).

[options] can be any combination of the following:

Source Options

/A Copy files with the archive attribute set (default=Y)

/M Copy files with the archive attribute set and turn off the archive attribute, use this option when making regular Backups (default=Y)

/H Copy hidden and system files and folders (default=N)

/D:mm-dd-yyyy Copy files that have changed since mm-dd-yyyy. If no date is given, the default is to copy files with a modification date before today. (at least 1 day before)

/U Copy only files that already exist in destination.

/S Copy folders and subfolders

/E Copy folders and subfolders, including Empty folders. May be used to modify /T.

/EXCLUDE:file1[+file2][+file3]...

(Windows 2000 only) The files can each contain one or more full or partial pathnames to be excluded.

When any of these match any part of the absolute path of a SOURCE file, then that file will be excluded. For example, specifying a string like \obj\ or .obj will exclude all files underneath the directory obj or all files with the .obj extension respectively.

Copy Options

/W Prompt you to press a key before starting to copy. /P Prompt before creating each file.

/Y (Windows 2000 only) Suppress prompt to confirm overwriting a file. may be preset in the COPYCMD env variable. /-Y (Windows 2000 only) Prompt to confirm overwriting a file.

/V Verify that the new files were written correctly. /C Continue copying even if an error occurs.

/I If in doubt always assume the destination is a folder e.g. when the destination does not exist.

/Z Copy files in restartable mode. If the copy is interrupted part way through, it will restart if possible. (use on slow networks)

/Q Do not display file names while copying. /F Display full source and destination file names while copying. /L List only - Display files that would be copied.

Destination Options

/R Overwrite read-only files.

/T Create folder structure, but do not copy files. Do not include empty folders or subfolders. /T /E will include empty folders and

subfolders.

/K Copy attributes. XCOPY will otherwise reset read-only attributes.

/N If at all possible, use only a short filename (8.3) when creating a destination file. This may be nececcary when copying between disks that are formatted differently e.g NTFS and VFAT, or when archiving data to an ISO9660 CDROM.

/O (Windows 2000 only) copy file Ownership and ACL information.

/X Copy file audit settings (implies /O).XCOPY will accept UNC pathnames

Examples:

To copy a file:

XCOPY C:\utils\MyFile D:\Backup\CopyFile

To copy a folder:

XCOPY C:\utils D:\Backup\utils /i

To copy a folder including all subfolders.

XCOPY C:\utils\* D:\Backup\utils /s /i

The /i defines the destination as a folder.

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=/YThis will turn off the prompt in Win2000 and will be ignored by NT4 (which overwrites by default).

When comparing Dates/Times the granularity (the finest increment of the timestamp) is 2 seconds for a FAT volume and 0.1 microsecond for an NTFS volume. The WinXP version of XCOPY will accept wildcards for the source e.g. *.txt It is also more forgiving with trailing backslashes

Related Commands:

COPY - Copy one or more files to another locationDEL - Delete files MOVE - Move a file from one folder to anotherROBOCOPY - Robust File and Folder CopyFcopy - File Copy for MMQ (copy changed files & compress. (Win 2K ResKit) Permcopy - Copy share & file ACLs from one share to another. (Win 2K ResKit) MTC - XCopy and create a log file. (Win 2K ResKit)

Q240268 - XCOPY changes in Win 2K

Equivalent Linux BASH commands:

cp - Copy one or more files to another locationinstall - Copy files and set attributes