1

I am trying to run the docker command in a PowerShell script and test if the command was not successful, but I am failing to do so. I am using:

if (!Invoke-Expression -Command docker ps -q -f name=php72) {
    #some other code here
}

The error that I get after running this is:

Line |
  31 |  if (!Invoke-Expression -Command docker ps -q -f name=php72) {
     |      ~~~~~~~~~~~~~~~~~~
     | The term '!Invoke-Expression' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a
     | path was included, verify that the path is correct and try again.

I have tried the -not operator to no avail as well.

2 Answers 2

2

Add another bracket:

if (!(Invoke-Expression -Command docker ps -q -f name=php72)){
    #some other code here
}

Unless here !Invoke-Expression is evaluated, which is invalid.

Best way is to use like this:

docker ps -q -f name=php72 >$null 2>&1
if($lastExitCode -eq 1){"FAILED!"}
Sign up to request clarification or add additional context in comments.

Comments

1

Your syntax is invalid. PowerShell has 2 parsing modes: Expression and argument. The latter is the one where you work with commands. There, the name of the command (e.g. Invoke-Expression) must always come first.

In short: you have to wrap the command either with the grouping opterator () or subexpression operator $() to use it inside an expression:

-not (Invoke-Expression ...)
# or
-not $(Invoke-Expression ...)

(-not and ! work exactly the same)

But as @WasifHasan pointed out, docker is an external program, so the best way to check for success is using the $? automatic variable, which will be $false if $LASTEXITCODE is any other value than 0:

docker ps -q -f name=php72 2>&1>$null
if ($?} {
    # your other code here
}

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.