首页 > 解决方案 > 如何在远程计算机上运行 PowerShell 脚本?

问题描述

我的目标是在远程计算机上运行用于安装 Google Chrome 的脚本。本地安装的脚本已经保存在我的电脑上(\localhost\c$\Chrome\Chrome Installer.ps1")。

我正在考虑先将脚本复制到远程机器,然后远程运行脚本。您能否建议远程运行该脚本的最佳方法?先感谢您

最好的问候,斯坦

您可以在下面找到脚本:

$Installer = "$env:temp\chrome_installer.exe"
$url = 'http://dl.google.com/chrome/install/375.126/chrome_installer.exe'
Invoke-WebRequest -Uri $url -OutFile $Installer -UseBasicParsing
Start-Process -FilePath $Installer -Args '/silent /install' -Wait
Remove-Item -Path $Installer
$login = Read-Host "Please enter login id"
$comp = Read-Host "Please enter computer name or IPV4 adress"
Copy-Item -Path "\\localhost\c$\Chrome\Chrome Installer.ps1"  -Dest "\\$($comp)\c$\temp"

标签: powershell

解决方案


我正在考虑先将脚本复制到远程机器,然后远程运行脚本。

您实际上不需要先将其复制到远程主机 - 您可以Invoke-Command从远程计算机上的本地文件系统运行脚本,如下所示:

Invoke-Command -ComputerName $comp -FilePath "C:\Chrome\Chrome Installer.ps1"

要传递远程计算机的凭据,请将帐户名称指定为参数的-Credential参数,PowerShell 将提示您输入密码:

$login = Read-Host "Enter the user name for the remote host"
Invoke-Command -ComputerName $comp -FilePath "C:\Chrome\Chrome Installer.ps1" -Credential .\$login

推荐阅读