I am writing an app that runs on my Hypervisor (Hyper-V) that can: report VM statuses via network, manipulate VM states, monitor applications on said VMs. I am using Get-VM to retrieve the statuses of the VMs, which I am gathering using Patrick B's solution that can be found here. Call Get-VM, get the output, parse it.
My slightly edited version of Patrick's code (to get all of the lines of Get-VMs output):
std::vector<std::string> exec(const char* cmd){
std::array<char, 128> buffer;
std::vector<std::string> result;
auto pipe(popen(cmd, "r"));
if (!pipe) throw std::runtime_error("popen() failed!");
while (!feof(pipe)){
if (fgets(buffer.data(), 128, pipe) != nullptr){
std::string line = buffer.data();
result.push_back(line);
}
}
auto rc = pclose(pipe);
return result;
}
A snippet of how I am calling exec():
std::string command = "powershell Get-VM";
std::vector<std::string> result = exec(command.c_str());
Now here is my problem... When you call Get-VM from a fresh powershell instance it takes ~a second to return the info. Subsequent calls are near instant. Unfortunately for me/my implementation, each new exec()/popen() call is a fresh instance of the Get-VM call which makes my program slow to a crawl.
My question to you, is there a way that I can call all of the Get-VM commands in the same instance of popen? Or is there another way I can be doing this? I don't have any loyalty to popen, it's just what is filling the gap.