powershell - 无法在PowerShell中使用Invoke-Expression识别运算符

标签 powershell

我正在尝试在PowerShell脚本中运行docker命令,并测试该命令是否失败,但是我没有这样做。我在用:

if (!Invoke-Expression -Command docker ps -q -f name=php72) {
    #some other code here
}
运行此命令后出现的错误是:
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.
我尝试过-not运算符也无济于事。

最佳答案

您的语法无效。 PowerShell有2个parsing modes:表达式和参数。后者是您使用命令的地方。此处,命令名称(例如Invoke-Expression)必须始终排在最前面。
简而言之:您必须使用grouping opterator ()subexpression operator $()包装命令,以在表达式中使用它:

-not (Invoke-Expression ...)
# or
-not $(Invoke-Expression ...)
(-not!same完全一样)
但是正如@WasifHasan指出的那样,docker是一个外部程序,所以检查是否成功的最佳方法是使用$? automatic variable,如果$false$LASTEXITCODE以外的任何其他值,则它将是0:
docker ps -q -f name=php72 2>&1>$null
if ($?} {
    # your other code here
}

关于powershell - 无法在PowerShell中使用Invoke-Expression识别运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64409103/

相关文章:

相当于 "tail"命令的 Powershell 几乎可以远程工作

Powershell 2 和 .NET : Optimize for extremely large hash tables?

powershell - 如何通过远程服务器上的 Invoke-Command 运行多个命令

powershell - 使用 Powershell 将 arraylist 行更改为列

Powershell - 将字符串输出为 CSV 和格式

powershell - 密码中包含 "$"的 SQL Server 连接字符串

powershell - 如何按需加载 PowerShell 函数?

powershell - 使用 PowerShell ARM 脚本将磁盘添加到 Azure VM

powershell - 根据创建时间搜索文件

c# - 在 C# 中运行 powershell,运气不太好!