Reputation: 525
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.
Upvotes: 1
Views: 1338
Reputation: 17154
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
}
Upvotes: 1
Reputation: 15518
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!"}
Upvotes: 2