Search code examples
installationnsisnetstat

How to get output from ExecDos::exec


When I execute netstat -a |find /C $portNumber in command prompt I get the total number of lines where the given port number exists.

I want to get that same count in any variable so that I can check whether the port is already occupied or free in NSIS.

I am excuting the below command and I tried in many ways, but I'm not able to get the output of the ExecDos::exec in a variable or in the stack.

ExecDos::exec "netstat -a |find /C '$portNumber'| $output"

Solution

  • To enable shell behavior you have to execute cmd.exe /C yourcommand (Or expand %ComSpec% with ExpandEnvStrings but hardcoding cmd.exe is ok if you don't support Win9x)

    Or you can try the ExecCmd plug-in which does this for you (But it has fewer options so you would have to redirect the output to a file)

    nsExec::ExecToStack with the cmd prefix should also work...

    Edit:

    Here is a working example (I used nsExec since it part of the default install)

    !include LogicLib.nsh
    section
    ExpandEnvStrings $0 %COMSPEC%
    StrCpy $1 445 ;Port number
    nsExec::ExecToStack '"$0" /C netstat -an|find /C ":$1"'
    Pop $0
    ${If} $0 = 0
        Pop $0
        MessageBox mb_ok "Port count=$0"
    ${Else}
        ; Port not open...
    ${EndIf}
    sectionend