How to fetch output of command of powershell with

2019-08-15 08:38发布

问题:

i implemented program of network statistics with help of powershell scrpit. the program is running successfully and giving me perfact output as well . below is my program.

int main(int argc, char *argv[])
{
       string strPath = "C:\\Get-NetworkStatistics.ps1";
      char str[50] =  "C:\\Get-NetworkStatistics.ps1";

       char command[500];

//access function:
       //The function returns 0 if the file has the given mode.
       //The function returns –1 if the named file does not exist or does not have the given mode
       if(access(strPath.c_str(),0) == 0)
       {


_snprintf(command, sizeof(command), "Start Powershell.exe -noexit Set -executionpolicy;.'%s';Get-NetworkStatistics",str);
system(command);



       }

       else 
       {
              system("cls");
              cout << "File is not exist";
              system("pause");
        }
return 0;
}

! here is the output of above program

as you can see the output is in the powershell windows.. i want to fetch all this data of powershell output and want to display it in console. how should it possible?

please help me..

回答1:

Unless you need to do display the info in realtime as it becomes available, just redirect it to a file, then read that file from C++.

Since netstat was lobotomized in Windows XP SP 2 or thereabouts I can understand using Powershell.

But it may just be that netstat will serve your needs, and then you don't have to deal with any of that complication.


By the way, I recommend using a scripting language for scripting tasks. There is of course the complication that Powershell scripting is disabled by default, otherwise using the Powershell scripting facility would be indicated. But e.g. in this case a [cmd.exe] batch file would be more natural than doing its job from C++.

The Windows Script Host shell objects, available from JScript and VBScript, provide functionality for process execution with output grabbing.

There is a little snag in that you then have to poll the output, but I think it's still easier than doing this at the C/C++ API level.