FAQ – Windows Command Processor cmd.exe
Frequently Asked Questions Regarding The Windows Command Processor
Answer: Windows 2000 supports two (2) command processors: – COMMAND.COM is the command processor for the virtual DOS Machine (VDM), used for processing MS-DOS based applications and scripts. – CMD.EXE is the native 32-bit command processor, used to open a command prompt and to press batch (.bat) files. This FAQ addresses CMD.EXE. If you need help troubleshooting 16-bit applications, see Microsoft Knowledge Base articles: Troubleshooting NTVDM and WOW Startup Errors (Q196453). Troubleshooting MS-DOS-Based Programs in Windows (Q165214) Troubleshooting 16-Bit Windows Applications (Q103656). To identify whether any program is 16-bit or 32-bit:
To identify whether a running program is 16-bit or 32-bit:
Answer: To get help on commands, open a CMD.EXE prompt and type any of the following: help – To get a list of supported commands. <Command Name> /? – to get help on <Command Name>. Example: net /? <Command Name> <Sub Command Name> /? – to get help on the <Command Name> <Sub Command Name>. Example: net user /? Some commands provide detail help, such as DIR, SET, FOR, IF, etc., while others only provide minimal information, such as NET USER. To get additional help, create a shortcut to a ntcmds.bat file that contains: @echo off and set it to run Minimized.
Answer. To parse the date into its’ YYYY, MM, and DD components, we would use the FOR command. When you type Date /T, a typical North American installation would display Day MM/DD/YYYY, like Mon 07/15/2002. To parse this into the YYYY, MM, and DD components, type: for /f "Tokens=2-4 Delims=/ " %a in (‘date /t’) do set mm=%a&set dd=%b&set yy=%c Note When using the FOR command in a batch file, replace % with %%. To create a folder named 20020715, type MD %yy%%mm%%dd%. To create a universal date parser, that works on all Windows NT-based systems (Windows NT 4.0, Windows NT 5.0 (Windows 2000), and Windows NT 5.1 (Windows XP, which doesn’t display the Day when using date /t), regardless of date format, we can make use of the fact that when you type Date, a display similar to: The current date is: Mon 07/15/2002 exhibits the format (mm-dd-yy). Create a batch file, named univdate.bat, in your path, which contains:
When you type call univdate, the appropriate environment variables are set. In North America, this would typically be mm, dd, and yy.
Answer: In addition to the environment variables that are defined using Control Panel / System / Advanced / Environment Variables, Windows 2000 has some built-in variables. To see the environment variables that are available, type SET. Note The built-in variables are different if you log on locally versus log on to a domain. Notice that %LOGONSERVER% contains the validating domain controller. Windows 2000 also defines some hidden environment variables that you can use:
Answer: The Windows NT-based Registry Editor, Regedt32.exe, does NOT support batch or command prompt operations. You can use Regedit.exe, with appropriate switches, to silently Merge a filename.reg file with your registry, or to export a registry file. To silently Merge a filename.reg file, use the following syntax: regedit /s <Drive:>\FolderName\FileName.reg To export a filename.reg file, in Windows NT 5.x format, use: regedit /e "<Drive:>\FolderName\FileName.reg" "KeyPath" Note The quote marks are only required if the ‘path’ contains spaces. To export a filename.reg file, in W9x/NT4 format, suitable for merging with W9x/NT4/NT5 registries, use: regedit /a "<Drive:>\FolderName\FileName.reg" "KeyPath"
Answer: To delete a key, using a filename.reg file, use the following syntax: REGEDIT4 [-keyPath] Example: To delete the HKEY_LOCAL_MACHINE \Software \McAfee Key, including all sub-keys, and all Value Names, use the following filename.reg file: REGEDIT4 [-HKEY_LOCAL_MACHINE \Software \McAfee] Then run: regedit /s <Drive:>\Folder\FileName.reg To delete a Value Name, using a filename.reg file, use the following syntax: REGEDIT4 [keyPath] Example: To delete the Tweak UI Value Name from the HKEY_LOCAL_MACHINE \SOFTWARE \Microsoft \Windows \CurrentVersion \Run key, use the following filename.reg file: REGEDIT4 [HKEY_LOCAL_MACHINE \SOFTWARE \Microsoft \Windows \CurrentVersion \Run]
Answer: If you install the Support Tools from the Windows 2000 CD-ROM, you can use REG.EXE to Add, Delete, Copy, Compare, Export, Import, Load a Hive, Query, Save, Restore, and Unload a Hive. To install the Support Tools:
Using REG.EXE, and Netdom.exe from the Support Tools, you can script a report of all the Windows NT-based workstations in your domain, listing the computer name, O/S version, and service pack, and piping the report to C:\report.txt:
Answer: A logon script can use any command supported by the client O/S. If you have a mixture of Windows NT-based clients and other Windows clients, you can test if the client platform is Windows NT-based by including the following statement: if "%OS%"=="Windows_NT" goto winnt If you need to test for a specific operation system, the following commands should work on all Microsoft operating systems:
goto end goto end goto end goto end goto end goto end goto end :end To define the %USERNAME%, %COMPUTERNAME%, and %LOGONSERVER% environment variables on non-Windows NT-based Windows clients, install putinenv.exe on all non-Windows NT-based Windows clients. You must also install WINSET.EXE, from the Windows CD-ROM, on these clients. You can then use the following code in your logon script:
The most used command in a logon script is net use, used for mapping a drive letter to a share. The syntax is: net use <:Drive:> \\ServerName\ShareName[\folder] /persistent:NO Note See the NET USE help in the ntcmds.chm file for other options. Windows 2000 can map below a share, but downlevel clients cannot. If you have configured the users home directory, you can use the net use <:Drive:> /home /persistent:NO syntax.
Answer: The FOR command will allow us to process multiple lines of command output. We can use the FOR command to pass the results of a DIR to a process. If we wanted to rename all .txt files in a folder, whose 2nd-4th character of the file name was upper case ABC, to a .log file, we could use the following example.bat file, and pass the folder name as a parameter (example.bat "C:\Documents and Settings\Jerry\My Documents")
Answer: When you invoke a batch file with a parameter (%1), you are able to parse it to extract meaningful information. Note Command Extensions ( /E:ON ), enabled by default, must be on.
You can use these modifiers in combination:
To determine where a batch file was run from, use %~dp0 I have scripted demo.bat to display the various parsing of a file/folder name parameter. Demo.bat contains:
If I type:
demo.bat will display:
%1="C:\Documents and Settings\Jerry\My Documents\My Pictures\Jerold.jpg" %1=C:\WINNT\Notepad.exe %1="C:\Documents and Settings\Jerry"
Answer: The SET command can perform calculations. When you type SET /?, part of the help display contains: "The /A switch specifies that the string to the right of the equal sign is a numerical expression that is evaluated. The expression evaluator is pretty simple and supports the following operations, in decreasing order of precedence:
If you use any of the logical or modulus operators, you will need to enclose the expression string in quotes. Any non-numeric strings in the expression are treated as environment variable names whose values are converted to numbers before using them. If an environment variable name is specified but is not defined in the current environment, then a value of zero is used. This allows you to do arithmetic with environment variable values without having to type all those % signs to get their values. If SET /A is executed from the command line outside of a command script, then it displays the final value of the expression. The assignment operator requires an environment variable name to the left of the assignment operator. Numeric values are decimal numbers, unless prefixed by 0x for hexadecimal numbers, and 0 for octal numbers. So 0x12 is the same as 18 is the same as 022. Please note that the octal notation can be confusing: 08 and 09 are not valid numbers because 8 and 9 are not valid octal digits." We can script Yesterday.bat to calculate yesterdays date, returning the PDMM, PDDD, and PDYY environment variables:
Note To calculate that the year was divisible by 4, a leap year, I could have replaced:
with:
Answer: If your batch script needs to determine if a string is a sub-set of a larger string, the easiest method is to use environment variable string substitution: set work=%string:substring=% If the substring is an environment variable, set work=%string:%substring%=% or set work=%%string:%substring%=%% does NOT work. You can use the FOR command to parse this expression, but using the CALL command is much easier: call set work=%%string:%substring%=%% To determine if your path contains a specific folder, call chkpath "folder" Example: call chkpath "c:\program files\support tools", where chkpath.bat contains:
Note chkpath.bat sets the $chkpath environment variable to Y if the string is found. If you need to determine the position and length of the "folder" string in the path, chkpath.bat should contain:
Note $pos starts at position 0. Sample Usageset look=c:\program files\support tools
Answer: To process the contents of a text file, you can parse it with the FOR command: for /f "Tokens=*" %%a in (filenName.Extension) do set line=%%a&call :parse
or
for /f "Tokens=*" %%a in (‘type "filenName.Extension"’) do set line=%%a&call :parse Note See FOR /? for additional options. Example: To display only those keys that have dword values, and their dword values, in a c:\folder\registry.reg file:
Answer: When you type start /?, you receive:
START ["title"] [/Dpath] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED] "title" Title to display in window title bar. If it is not an internal cmd command or batch file then parameters These are the parameters passed to the command/program If Command Extensions are enabled, external command invocation non-executable files may be invoked through their file association just When executing an application that is a 32-bit GUI application, CMD.EXE When executing a command line whose first token is the string "CMD " When executing a command line whose first token does NOT contain an .COM;.EXE;.BAT;.CMD Notice the syntax is the same as the PATH variable, with When searching for an executable, if there is no match on any extension,
Answer: The start command can set the initial Title in a command Window. To cause the batch file to display the current directory every time it changes, add the following commands after each current directory change:
Answer: If you want to scroll the CMD window while a batch file is running, you can alter the Windows width (characters) and depth (screen buffer lines) by issuing a mode command in the batch file: mode con[:] [cols=c] [lines=n] where:
cols=c specifies the width, c, in characters. lines=n specifies the number of lines, n, in the screen buffer. Example: mode con: cols=100 lines=999
Answer: The SET command support the /P switch: SET /P variable=[promptString] "The /P switch allows you to set the value of a variable to a line of input Example: To prompt for folders to DIR:
Answer: The Windows 2000 Resource Kits provide sleep.exe to allow a batch file to sleep for n seconds. You can emulate this behavior by using the PING (Packet InterNet Groper) command: ping -n seconds+1 127.0.0.1>nul To sleep for 15 seconds, type: ping -n 16 127.0.0.1>nul
Answer: To cause a batch file to beep for attention, you need to send a BEL character. To create a Bell.bat in your path:
Note <> indicates that you type the key(s) within the <>. When you need to beep for attention: call bell
Answer: The general syntax for piping batch output, including commands and responses, to a log file is: Drive:\BatFolder\BatchName.bat>Drive:\LogFolder\LogName.log 2>&1
The default behavior of the CMD command processor is to evaluate an environment variable once per statement execution. To demonstrate this behavior, assume that your c:\test folder has 3 files: File1.txt If you run a batch script containing:
You would see the following:
You can see from this example that the LIST variable is expanded just once when the FOR statement is executed. Since LIST was empty, only the last file found is set into the variable. Windows 2000 supports delayed environment variable expansion. You must enable delayed environment variable expansion for the CMD session by using the CMD /V:ON switch, or by issuing a setlocal ENABLEDELAYEDEXPANSION command. With delayed environment variable expansion enabled, you can use the ! instead of the %, as follows:
This yields the following output:
You can have delayed environment variable expansion enabled by default, if you use Regedt32 to navigate to either of the following keys:
HKEY_CURRENT_USER \Software \Microsoft \Command Processor On the Edit menu, Add Value name DelayedExpansion, as a REG_DWORD data type. A data value of 1 enables delayed environment variable expansion and a data value of 0 disables it. Invoking the /V:ON or /V:OFF switch on CMD.EXE and/or using the setlocal ENABLEDELAYEDEXPANSION command, overrides the registry setting for the CMD session.
Answer: From the ntcmds.chm file:
Examples: dir filename.txt>nul && type filename.txt is equivalent to if exist filename.txt type filename.txt dir filename.txt>nul || @echo.>filename.txt is equivalent to if not exist filename.txt @echo.>filename.txt
Answer: The syntax of the net send command is: net send {name | * | /domain[:name] | /users} message To send a pop-up to all users in your domain, type: net send /domain This is a message. Note Windows NT-based client run the Messenger service by default. Other Windows clients must be running Winpopup.exe to receive the message. net send jennifer hello will send hello to Jennifer, if she is logged on. net send /users hello will send hello to all users that are connected to your computer. To send a files contents to logged on members of one or more domain groups, use: call sendfilegroup filename.txt group1 [group2 group3 … groupn], where sendfilegroup.bat contains:
Answer: The FOR /R command is meant to traverse sub-folders. The general syntax is: FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters] Walks the directory tree rooted at [drive:]path, executing the FOR Examples: To delete every *.log file in all the folders of your profile, type: for /r "%userprofile%" %i in (*.log) do del /q "%i" Note If used in a batch file, the %variable% must be %%variable%%. To list all the sub-folders of your profile, type: for /r "%userprofile%" %i in (.) do @echo %i To list every sub-folder of the current directory, type: for /r %i in (.) do @echo %i
Answer: Typing RD /S /Q <Drive:>\FolderName will delete <Drive:>\FolderName, all it’s files, and sub-folders. If you do NOT wish to remove the target folder, create DELTREE.BAT in your path: @echo off To delete all the files and sub-directories in <Drive:>\My Test Folder, type: DELTREE "<Drive:>\My Test Folder"
Answer: If you wish to send an e-mail message from the command line or from a batch file, you can use BLAT freeware. After installing BLAT by typing: blat -install mail.jsiinc.com Jerry@jsiinc.com 3, I received: Failed to open registry key for Blat profile , using default. When I typed: blat c:\temp\blatread.txt -to jerry@jsiinc.com -s "This is a BLAT test", the CMD window displayed:
Try number 1 of 3. AND I received the e-mail, containing the contents of c:\temp\blatread.txt.
Answer: I have scripted GetUserInfo.bat to retrieve basic user data. The syntax is: call getuserinfo UserName where UserName must be quoted if it contains any space characters. To verify that the UserName was found, use a statement like: if not defined $line1 goto NotFound After verifying that the UserName was found, you can access the basic user data by using the environment variables from the following table:
GetUserInfo.bat contains:
Sample UsageTo implement a user locator for a single domain controller domain, create a Locator$ share on your domain controller granting Domain Users Read and Write permissions, and Creator Owner delete permission. Add the following code to your logon script:
To locate a user, type: dir "%LOGONSERVER%\Locator$\UserName.*"
Answer: I have scripted Tail.bat to perform both functions. The syntax is: tail FileName [NumberOfLinesToDisplay] If NumberOfLinesToDisplay is 0, you can set the file line count by using: for /f %%i in (‘tail FileName 0’) do set lines=%%i If NumberOfLinesToDisplay is omitted, 10 lines will be displayed. If NumberOfLinesToDisplay is greater than the lines in the file, all lines in the file will be displayed. Tail.bat contains:
Answer: I have scripted AllUsers.bat to retrieve the list of all user names in the client’s domain. The syntax is: call AllUsers "FileName" where FileName is the full path to the file that will contain the user names. AllUsers.bat contains:
Sample Usage To create of report of all user names whose password has expired, or will expire today, Expired.bat contains:
Answer: If you receive the subject error message, the most likely cause is that the %SystemRoot%\System32 folder is no longer in your path. Most systems should have a PATH variable that begins with entries similar to: PATH=C:\WINNT\system32;C:\WINNT;C:\WINNT\system32\WBEM; Another possible reason for this error is that some application install changed the Path Value Name, in the registry, from a REG_EXPAND_SZ data type to a REG_SZ data type. If this is your problem:
|