If Else 语句在 powershell 中安装应用程序时出错

If Else statement giving error while installing an application in powershell

正在通过 PowerShell 创建用于在 windows 上安装软件的脚本,但是遇到错误,下面是它的代码。

 $software = Get-WmiObject -Class win32_product | Where-Object -FilterScript { $_.Name -like "*myapplication*"} 
if ($software.Version -ne "1.0.0")  {msiexec.exe /i 'C:\Program Files\myapplication.msi' /qr} {Write-host "Executing the upgrade"} 
else
{
Write-host "Correct version is installed"
}

这里的逻辑是,如果所需的应用程序版本不等于 v1.0.0,则 运行 安装程序或收到一条消息,安装了正确的版本,如果所需的版本我可以安装应用程序不满足条件但是如果版本是所需的那么它应该回显 "Correct version is installed" 但不,它给出了一些关于 else 语句的错误,如下所示,

The term 'else' 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.
At line:3 char:5
+ else <<<< 
+ CategoryInfo          : ObjectNotFound: (else:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

绞尽脑汁想了半天猜错了,也没有space后面的else语句,求助!

问题

遗憾的是,此错误消息不是很有用。大多数语言会这样说:

Else without if

else 必须作为紧跟在 if 之后的下一个语句块:

if ($software.Version -ne "1.0.0")  {
    msiexec.exe /i 'C:\Program Files\myapplication.msi' /qr
} # If block finished, expecting elseif or else
{
    Write-host "Executing the upgrade"
} 
else # Else without if?!
{
    Write-host "Correct version is installed"
}

分辨率

您应该通过删除 msiexecWrite-Host 之间的右大括号和左大括号来解决问题,将这些语句放入 if 块中,因为它们都需要当该条件为真时执行。

如果必须将 msiexecWrite-Host 语句放在同一行,则使用分号将它们分隔开。例如

if ($software.Version -ne "1.0.0")  {
    msiexec.exe /i 'C:\Program Files\myapplication.msi' /qr;Write-host "Executing the upgrade"
} 
else
{
    Write-host "Correct version is installed"
}