Title: Another option to execute system commands
Question: When you want to execute some command you just call WinExec. But if you want to execute some system command like 'dir *.*' or even execute an old DOS application, WinExec by itself just doesn't give all you want.
Answer:
The solution here it's by running your commands trought the COMSPEC. This is,
COMPSPEC it's an environment variable that on Windows NT and 2000 returns the
path to CMD.EXE and on Windows 9x returns the path to COMMAND.COM.
While I tested all this article code with Windows 2000 it can probably run also
in Windows 9x (I think).
If you go to 'Command Prompt' and write the following you'll get a description
of a various number of options that you can use to run a command (or a batch of
commands in a single command line):
Starts a new instance of the Windows 2000 command interpreter
CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
[[/S] [/C | /K] string]
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
/S Modifies the treatment of string after /C or /K (see below)
/Q Turns echo off
/D Disable execution of AutoRun commands from registry (see below)
/A Causes the output of internal commands to a pipe or file to be ANSI
/U Causes the output of internal commands to a pipe or file to be
Unicode
/T:fg Sets the foreground/background colors (see COLOR /? for more info)
/E:ON Enable command extensions (see below)
/E:OFF Disable command extensions (see below)
/F:ON Enable file and directory name completion characters (see below)
/F:OFF Disable file and directory name completion characters (see below)
/V:ON Enable delayed environment variable expansion using c as the
delimiter. For example, /V:ON would allow !var! to expand the
variable var at execution time. The var syntax expands variables
at input time, which is quite a different thing when inside of a FOR
loop.
/V:OFF Disable delayed environment expansion.
Note that multiple commands separated by the command separator '&&' are accepted for string if surrounded by quotes. Also, for compatibility reasons, /X is the same as /E:ON, /Y is the same as /E:OFF and /R is the same as /C. Any other switches are ignored.
If /C or /K is specified, then the remainder of the command line after the switch is processed as a command line, where 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.
If /D was NOT specified on the command line, then when CMD.EXE starts, it
looks for the following REG_SZ/REG_EXPAND_SZ registry variables, and if
either or both are present, they are executed first.
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
and/or
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
Command Extensions are enabled by default. You may also disable extensions for a particular invocation by using the /E:OFF switch. You can enable or disable extensions for all invocations of CMD.EXE on a machine and/or user logon session by setting either or both of the following REG_DWORD values in the registry using REGEDT32.EXE:
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\EnableExtensions
and/or
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\EnableExtensions
to either 0x1 or 0x0. The user specific setting takes precedence over the machine setting. The command line switches take precedence over the registry settings.
The command extensions involve changes and/or additions to the following
commands:
DEL or ERASE
COLOR
CD or CHDIR
MD or MKDIR
PROMPT
PUSHD
POPD
SET
SETLOCAL
ENDLOCAL
IF
FOR
CALL
SHIFT
GOTO
START (also includes changes to external command invocation)
ASSOC
FTYPE
To get specific details, type commandname /? to view the specifics.
Delayed environment variable expansion is NOT enabled by default. You can enable or disable delayed environment variable expansion for a particular invocation of CMD.EXE with the /V:ON or /V:OFF switch. You can enable or disable completion for all invocations of CMD.EXE on a machine and/or user logon session by setting either or both of the following REG_DWORD values in the registry using REGEDT32.EXE:
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\DelayedExpansion
and/or
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\DelayedExpansion
to either 0x1 or 0x0. The user specific setting takes precedence over the machine setting. The command line switches take precedence over the registry settings.
If delayed environment variable expansion is enabled, then the exclamation
character can be used to substitute the value of an environment variable
at execution time.
File and Directory name completion is NOT enabled by default. You can enable or disable file name completion for a particular invocation of CMD.EXE with the /F:ON or /F:OFF switch. You can enable or disable completion for all invocations of CMD.EXE on a machine and/or user logon session by setting either or both of the following REG_DWORD values in the registry using REGEDT32.EXE:
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\PathCompletionChar
and/or
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\CompletionChar
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\PathCompletionChar
with the hex value of a control character to use for a particular function (e.g. 0x4 is Ctrl-D and 0x6 is Ctrl-F). The user specific settings take precedence over the machine settings. The command line switches take precedence over the registry settings.
If completion is enabled with the /F:ON switch, the two control characters used are Ctrl-D for directory name completion and Ctrl-F for file name completion. To disable a particular completion character in the registry, use the value for space (0x20) as it is not a valid control character.
Completion is invoked when you type either of the two control characters. The completion function takes the path string to the left of the cursor appends a wild card character to it if none is already present and builds up a list of paths that match. It then displays the first matching path. If no paths match, it just beeps and leaves the display alone. Thereafter, repeated pressing of the same control character will cycle through the list of matching paths. Pressing the Shift key with the control character will move through the list backwards. If you edit the line in any way and press the control character again, the saved list of matching paths is discarded and a new one generated. The same occurs if you switch between file and directory name completion. The only difference between the two control characters is the file completion character matches both file and directory names, while the directory completion character only matches directory names.
If file completion is used on any of the built in directory commands (CD, MD or RD) then directory completion is assumed.
The completion code deals correctly with file names that contain spaces or other special characters by placing quotes around the matching path.
Also, if you back up, then invoke completion from within a line, the text to the right of the cursor at the point completion was invoked is discarded.
and it's this option that will let you run commands without the disadvantage of
using batch files.
With this article you'll also have an attached project sample containing an unit
(SysCommand.pas) that implements a small component. The best thing you can do
it's look at the attached sample, anyway here it is a small test sample:
var
FSysCommand: TSysCommand;
begin
FSysCommand := TSysCommand.Create(Self);
FSysCommand.WhenDone := cwdRemain;
FSysCommand.WindowTitle := 'This is a test';
FSysCommand.BkColor := cclBtWhite;
FSysCommand.FgColor := cclLtRed;
FSysCommand.CmdsList.Add('echo Now I will list your windows directory files.');
FSysCommand.CmdsList.Add('pause');
FSysCommand.CmdsList.Add('dir "c:\windows\*.*" /s');
FSysCommand.Execute;
as you can see, it's easy and simple to run a batch of commands throught the
Command Prompt.
== SysCommand.pas ==
unit SysCommand;
// by Fernando J.A. Silva (magico@galaxycorp.com) 2001/08/24
interface
uses
Classes;
type
TCmdWhenDone = (
cwdClose { /C or /R }, // Carries out the command specified by string and then terminates
cwdRemain { /K } // Carries out the command specified by string but remains
);
TCmdAutoRunCmds = (
carDefault,
carDisable { /D } // Disable execution of AutoRun commands from registry
);
// if carDisable was NOT specified, then when the command is launched, it
// looks for the following REG_SZ/REG_EXPAND_SZ registry variables, and if
// either or both are present, they are executed first.
//
// HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
// and/or
// HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
TCmdOutputType = (
cotANSI { /A }, // Causes the output of internal commands to a pipe or file to be ANSI
cotUnicode { /U } // Causes the output of internal commands to a pipe or file to be Unicode
);
TCmdColor = (cclNone, cclBlack {0}, cclBlue {1}, cclGreen {2}, cclAqua {3}, cclRed {4},
cclPurple {5}, cclYellow {6}, cclWhite {7}, cclGray {8}, cclLtBlue {9},
cclLtGreen {A}, cclLtAqua {B}, cclLtRed {C}, cclLtPurple {D}, cclLtYellow {E},
cclBtWhite {F});
TCmdExtensions = (
cexDefault,
cexON, {/E:ON or /X } // Enable command extensions
cexOFF {/E:OFF or /Y } // Disable command extensions
);
// Command Extensions are enabled by default. You may also disable extensions
// for a particular invocation by using the cexOFF. You can enable or disable
// extensions for all invocations of CMD.EXE on a machine and/or user logon
// session by setting either or both of the following REG_DWORD values in the
// registry using REGEDT32.EXE:
//
// HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\EnableExtensions
// and/or
// HKEY_CURRENT_USER\Software\Microsoft\Command Processor\EnableExtensions
//
// to either 0x1 or 0x0. The user specific setting takes precedence over
// the machine setting. The command line switches take precedence over the
// registry settings.
TSysCommand = class(TComponent)
private
FOutputType: TCmdOutputType;
FAutoRunCmds: TCmdAutoRunCmds;
FCmdExtensions: TCmdExtensions;
FWhenDone: TCmdWhenDone;
FBkColor: TCmdColor;
FFgColor: TCmdColor;
FWindowTitle: string;
FCmdsList: TStringList;
function GetParamsString: string;
procedure GetInternalCmdsList(var AList: TStringList);
function GetCommandsString: string;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Execute: Boolean;
published
property OutputType: TCmdOutputType read FOutputType write FOutputType;
property AutoRunCmds: TCmdAutoRunCmds read FAutoRunCmds write FAutoRunCmds;
property CmdExtensions: TCmdExtensions read FCmdExtensions write FCmdExtensions;
property WhenDone: TCmdWhenDone read FWhenDone write FWhenDone;
property BkColor: TCmdColor read FBkColor write FBkColor;
property FgColor: TCmdColor read FFgColor write FFgColor;
property WindowTitle: string read FWindowTitle write FWindowTitle;
property CmdsList: TStringList read FCmdsList write FCmdsList;
end;
implementation
uses
Windows,
SysUtils;
const
FStrWhenDone: array[0..1] of string = (' /C', ' /K');
FStrAutoRun: array[0..1] of string = ('', ' /D');
FStrOutType: array[0..1] of string = (' /A', ' /U');
FStrColors: array[0..16] of string = ('', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
FStrUseExt: array[0..2] of string = ('', ' /E:ON', ' /E:OFF');
constructor TSysCommand.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FOutputType := cotANSI;
FAutoRunCmds := carDefault;
FCmdExtensions := cexDefault;
FWhenDone := cwdClose;
FBkColor := cclNone;
FFgColor := cclNone;
WindowTitle := '';
FCmdsList := TStringList.Create;
end;
destructor TSysCommand.Destroy;
begin
inherited Destroy;
FCmdsList.Destroy;
end;
function TSysCommand.GetParamsString: string;
// Returns a string containing the parameters to be passed to 'COMSPEC'
begin
Result := '';
Result := Result + FStrOutType[Ord(FOutputType)];
Result := Result + FStrAutoRun[Ord(FAutoRunCmds)];
Result := Result + FStrUseExt[Ord(FCmdExtensions)];
Result := Result + FStrWhenDone[Ord(FWhenDone)];
end;
procedure TSysCommand.GetInternalCmdsList(var AList: TStringList);
begin
// Clean string list
AList.Clear;
// Insert all commands
if FWindowTitle '' then
AList.Add('TITLE ' + FWindowTitle);
if (FBkColor cclNone) and (FFgColor cclNone) then
AList.Add('COLOR ' + FStrColors[Ord(FBkColor)] + FStrColors[Ord(FFgColor)]);
end;
function TSysCommand.GetCommandsString: string;
// Return a string with internal commands and user commands
var
FList: TStringList;
idx: Integer;
s: string;
begin
s := '';
// Get internal command list as string
FList := TStringList.Create;
GetInternalCmdsList(FList);
for idx := 0 to FList.Count - 1 do
s := s + FList.Strings[idx] + ' && ';
// Concat with user commands list
for idx := 0 to FCmdsList.Count - 1 do
s := s + FCmdsList.Strings[idx] + ' && ';
// Delete last &&
Delete(s, Length(s) - 3, 4);
// Return commands string
Result := '"' + s + '"';
end;
function TSysCommand.Execute: Boolean;
var
FCmd: string;
FExec: string;
begin
// get name and path of command processor
FCmd := GetEnvironmentVariable('COMSPEC');
FExec := FCmd + ' ' + GetParamsString + ' ' + GetCommandsString;
Result := WinExec(PChar(FExec), SW_SHOWNORMAL) 31;
end;
end.
Note: The TSysCommand probably can be extended to support Linux Terminal Mode.
It would be a fine addition and a good reason to use this component in a
application.