inno-setupnetsh

Running netsh from using Inno Setup Exec()


I'm trying to create Windows Firewall rule during installation and I'm having trouble understanding how my command is formatted incorrectly. The error returned in ResultCode is "Incorrect Function"

procedure OpenFirewall;
var
  WindowsVersion: Integer;
  ResultCode: Integer;
  W7Command: String;
  WXPCommand: String;
begin
  WXPCommand := 'netsh firewall add portopening TCP 12345 "MyApp"'
  W7Command := 'netsh advfirewall add rule name="MyApp" dir=in action=allow protocol=TCP localport=12345';
  WindowsVersion := GetWindowsVersion();
  case WindowsVersion of
    5:
    begin
      Exec(ExpandConstant('{cmd}'), '/C ' + WXPCommand, '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
    end;
    6:
    begin
      Exec(ExpandConstant('{cmd}'), '/C ' + W7Command, '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
      Log(SysErrorMessage(ResultCode));
    end;
  end;
end;

Solution

  • First, the ResultCode contains a system error, only if the Exec returns False (indicating a failure to start a process). If the Exec succeeds to start the process, the ResultCode contains an exit code of the process. What is likely your case. You cannot pass the exit code to SysErrorMessage.

    Quoting Exec documentation:

    If True is returned and Wait is ewWaitUntilTerminated then ResultCode returns the exit code of the process. If False is returned then ResultCode specifies the error that occurred. Use SysErrorMessage(ResultCode) to get a description of the error.


    The actual problem is your syntax of netsh.

    You are missing a firewall keyword after the advfirewall.

    netsh advfirewall firewall add rule ...
    

    See Netsh AdvFirewall Firewall Commands.

    Did you even bother to test the command from command-line first?


    Side notes: