lundi 18 novembre 2019

Powershell: How to run an external command and checks its success in a single line?

In bash, I can do this:

if this_command >/dev/null 2>&1; then
  ANSWER="this_command"
elif that_command >/dev/null 2>&1; then
  ANSWER="that_command"
else
  ANSWER="neither command"
fi

but in Powershell, I have to do this:

this_command >/dev/null 2>&1
if ($?) {
  ANSWER="this_command"
} else { 
  that_command >/dev/null 2>&1
  if ($?) {
    ANSWER="that_command"
  } else {
    ANSWER="neither command"
  }
}

or something similar with ($LASTEXITCODE -eq 0). How do I make the Powershell look like bash? I'm not a Powershell expert, but I cannot believe that it doesn't not provide some means of running a command and checking its return code in a single statement in a way that could be used in an if-elseif-else statement. This statement would be increasingly difficult to read with every external command that must be tested in this way.

Aucun commentaire:

Enregistrer un commentaire