Tagged Command Line Parameters (Views: 102)


I needed a flexible way to handle command line parameters. The standard Delphi ParamStr() and FindCmdLineSwitch were not flexible enough as I needed parameter values to be in any order.


The FindCmdLineSwitch was not capable of this because a perfect match is searched for ie. /dsn=oracle1 or /dsn oracle1 would fail, as in the first case searching for FindCmdLineSwitch('dsn',['-','/'],true) would result in false
as "dsn=oracle1" is the switch. In the second case the search would resolve to true, but the second part of the switch is a completely separate parameter and might or might not be a part of /dsn.

I decided to use Tagged Parameter values to solve the value problem

eg.  dsn=oracle1 pass=fred123   {values bound to a param tag}

and use FindCmdLineSwitch for simple boolean switches

eg. /auto -auto etc.            {switch present true or false}

Using a simple but effective function

GetParamVal(const TaggedParm : string;  IgnoreCase : boolean = true) : string;

and Delphi's FindCmdLineSwitch() one can very easily determine
the values of command lines such as

MyExe dsn=oracle1 /auto pass=pass123
MyExe /auto pass=pass123 dsn=oracle1

The order of the parameters and switches are now irrelevant.


DataBase1.AliasName := GetParamVal('dsn');
if GetParamVal('pass') <> 'manager' then ....
if FindCmdLineSwitch('auto',['-','/'],true) then ....

function GetParamVal(const TaggedParm: string;
  IgnoreCase: boolean = true): string;
  Cmd: string;
  i, Len: integer;
  Comp1, Comp2: string;
  Cmd := '';
  Comp1 := TaggedParm + '=';
  if IgnoreCase then
    Comp1 := UpperCase(Comp1);

  Len := length(Comp1);

  for i := 1 to ParamCount do
    Comp2 := copy(ParamStr(i), 1, Len);
    if IgnoreCase then
      Comp2 := UpperCase(Comp2);
    if (Comp1 = Comp2) then
      Cmd := trim(copy(ParamStr(i), Len + 1, length(ParamStr(i))));

  Result := UpperCase(Cmd);

<< Back to main page