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?
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