【问题标题】:Installing an MSI file on a remote machine with PowerShell使用 PowerShell 在远程计算机上安装 MSI 文件
【发布时间】:2021-12-01 19:14:28
【问题描述】:

我正在开发一种实用程序来自动化某些流程,其中一项任务是在远程计算机上安装 .msi 文件。该文件位于远程机器上的C:\Users\username 中,为简单起见,文件名为file.msi。我正在使用的命令是:

Invoke-Command -ComputerName $remoteMachine -ScriptBlock{cmd /c start /wait msiexec /i $installPath /quiet}

当我在本地开发机器上执行此操作时,它不会显示任何错误,但不会安装文件。

但是,当我复制括号内的确切命令并在远程计算机上的 PowerShell 脚本中运行它时,它会成功安装。我知道我的$remoteMachine 是正确的,因为我在脚本的其余部分都广泛使用了它。

我知道$installPath 变量也不是问题,因为出于测试目的,我对完整路径进行了硬编码,但它仍然无法安装。

我在远程机器上也有适当的权限,因为在脚本的前面我将.msi 从一台机器复制并粘贴到另一台机器上没有问题。

我尝试了多种命令组合,但在这里停留了一段时间,因此我们将不胜感激!

【问题讨论】:

  • 当您已经在 powershell 中时,为什么要从 cmd 运行安装?为什么不直接在脚本块中开始安装?
  • 我绝对不反对在 PowerShell 中安装,但我已经尝试了多个命令,但没有运气。我似乎很接近使用 cmd 所以我想我会朝这个方向发展。如果我只能使用 PowerShell 找到可行的解决方案,我肯定会使用它。
  • 您必须将参数列表$installpath 传递给脚本块

标签: powershell


【解决方案1】:

理想情况下,这应该可行。

Invoke-Command -ComputerName $remoteMachine -ScriptBlock{msiexec /i $installPath /quiet}

它失败的原因是因为您没有将$installPath 作为参数列表传递。像这样修改它。

Invoke-Command -ComputerName $remoteMachine -ScriptBlock{
param(
    [Parameter(Mandatory=$true,
                   Position=0)]
    $installPath
    )
cmd /c start /wait msiexec /i $installPath /quiet
} -ArgumentList $installPath

但如果它不起作用,这是我不久前使用的一种解决方法。 使用命令msiexec /i $installPath /quiet 创建一个 .bat 文件并将其推送到您推送 msi 文件的位置。

现在从调用脚本块中,只需调用 bat 文件即可。

Invoke-Command -ComputerName $remoteMachine -ScriptBlock{C:\Users\Username\Install.bat}

其中 Install.bat 是您的 bat 文件的名称。

注意:如果您不想导致重新启动,您可能还需要使用 /norestart 开关。取决于您要安装的内容。

【讨论】:

    【解决方案2】:

    从 PowerShell 3.0 开始,您可以使用使用范围修饰符来标识远程命令中的局部变量。

    syntax of Using :- $Using:<VariableName>
    

    在你的情况下:

    Invoke-Command -ComputerName $remoteMachine -ScriptBlock{cmd /c start /wait msiexec /i $Using:installPath /quiet}
    

    https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_variables?view=powershell-7.2#using-local-variables

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 2021-07-05
      相关资源
      最近更新 更多