0

I got this simple line. I try to check if a specific path on a remote machine exists. If not I want QProcess::exitCode() to give me back what I set $global:lastexitcode to.

QProcess p;
auto out = [&]()
{
   qDebug() << "standard out: " << QString::fromStdString(p.readAllStandardOutput().toStdString());
};

QObject::connect(&p, &QProcess::readyReadStandardOutput, out);
p.start("C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe", QStringList{ "Invoke-Command -ComputerName server01 -ScriptBlock {$ret=Test-Path -Path \"C:/anotexisting/path.txt\" -PathType Leaf; if($ret){echo \"pathexists\";$global:lastexitcode=0}else{echo \"pathdoesnotexist\";$global:lastexitcode=-1};echo \"lastexitcode: $global:lastexitcode\"}"});
p.waitForFinished();
qDebug() << "process exitcode:" << p.exitCode();

The lambda function gives me the output I expect. But the exitCode is always 0. I cant really figure out why the exitCode is not being set. The Invoke-Command obviously runs in that process. Why would it not use $global:lastexitcode as its terminating process exitcode?

k_k
  • 83
  • 7

2 Answers2

1

The last command echo is successful. Just add exit $global:lastexitcode at the end.

  • Thank you this actually solved my problem. But I still can't seem to get the exact Exitcode. I get 0 on success and anything else e.g exit -1 or exit 99 I get the QProcess Exitcode 1. Thats why I don't accept it as an answer but upvoted. – k_k Aug 24 '22 at 13:41
  • I want to add that this is only possible for local computers. If the Invoke Command is run on a remote machine there is a work around needed. See this post: https://stackoverflow.com/questions/1210942/catching-return-code-of-a-command-with-invoke-command-powershell-2 – k_k Sep 05 '22 at 11:35
0

The answer for this problem is that there is a work around needed. One can't just get the exitcode for a remote executed command by reading $lastexitcode or $global:lastexitcode because the session closes right after the Invoke-Command. So in case of a remote machine QProcess will always return 0 if there is no error thrown.

Check out this post for possible solutions: catching return code of a command with "invoke-command" - Powershell 2

k_k
  • 83
  • 7