我有一个非常简单的脚本,我想使用远程 powershell 在多台计算机上运行。我目前正在公司基于 GUI 的远程 Powershell 解决方案上使用它,一次连接一台计算机,但他们无法使用该应用程序进行批量会话。
当我运行现在的命令时,它只显示 Write-Host 命令,并且不会弹出任何错误。当我检查计算机查看软件是否已更新时,它没有更新。我不确定哪里出了问题。这是我所拥有的:
$computers = "C:\Examplepath\computernames.txt\"
$variable1 = "This first variable contains organization/registration keys for the software"
$variable2 = "This second variable contains the info to uninstall the existing version of the application for msiexec"
$installPath = "This contains the path of the application installer on the computer"
foreach ($computer in $computers) {
Write-Host "Executing on $computer..."
$session = New-PSSession -ComputerName $computer
Invoke-Command -Session $session -ScriptBlock {
param ($variable1, $variable2)
Write-Host "Uninstalling existing software version..."
$uninstallCommand = "msiexec.exe"
$uninstallArguments = "variable2"
Start-Process -FilePath $uninstallCommand -ArgumentList $uninstallArguments -Wait
Write-Host "Now installing the software..."
$installArguments = "variable1"
Start-Process -FilePath $installPath -ArgumentList $installArguments
} -ArgumentList $variable1, $variable2, $installPath
Remove-PSSession -Session $session
}
任何帮助将不胜感激,我觉得这很简单,但我似乎无法理解。
我可以看到两件事:
首先,您的
param
部分缺少 $installvariable
变量。
Invoke-Command -Session $session -ScriptBlock {
param ($variable1, $variable2)
但它存在于你的
ArgumentList
} -ArgumentList $variable1, $variable2, $installPath
其次,我不确定这是否是旧 PS 版本中必需的/曾经是必需的/只是我第一次这样做时看到的所有示例中是如何完成的,而且我从未更改过我的代码,但是我认为您不能在
-Argumentlist
和 param
行中使用相同的变量名称。所以我会把它们写成:
Invoke-Command -Session $session -ScriptBlock {
param ($var1, $var2, $instPath)
Write-Host "Uninstalling existing software version..."
$uninstallCommand = "msiexec.exe"
$uninstallArguments = "var2"
Start-Process -FilePath $uninstallCommand -ArgumentList $uninstallArguments -Wait
Write-Host "Now installing the software..."
$installArguments = "var1"
Start-Process -FilePath $instPath -ArgumentList $installArguments
} -ArgumentList $variable1, $variable2, $installPath
因此
-ArgumentList
声明了脚本主体中定义的变量并传递给 Invoke-Command
,而 params
定义了如何在 ScriptBlock
中引用它们。