如果在Powershell中安装应用程序时Else语句给出错误信息,

时间:2018-09-21 22:31:50

标签: powershell installation echo

创建用于通过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,则运行安装程序,否则将收到一条消息,说明已安装了正确的版本,如果不满足所需的版本条件,我可以安装该应用程序该版本是所需的版本,然后它应回显“已安装正确版本”,但没有,它对如下的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

我ing了很长时间才猜出我错了,在别的声明之后也没有空格了,请帮忙!

1 个答案:

答案 0 :(得分:4)

问题

不幸的是,此错误消息不是很有帮助。大多数语言都会说:

  

否则,如果没有

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"
}