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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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: stackoverflow.com/questions/1210942/…
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.