使用PowerShell在远程计算机上执行程序

如何使用PowerShell在远程计算机上执行程序?

WinRM是一个很酷的新方法。 我已经在Windows Server 2008 R2上看到了这个demo,尽pipe在其他windows操作系统下有powershell v2和WinRM的下载。

不太酷(或新)的方法是使用psexec ,而不是powershell,但我确定有一些方法可以通过powershell-esque语法调用它。

您也可以使用WMI并远程启动一个进程。 它不会互动,你将不得不相信,它会自行结束。 除了WMI的开放端口以外,这不需要任何远程计算机。

Function New-RemoteProcess { Param([string]$computername=$env:computername, [string]$cmd=$(Throw "You must enter the full path to the command which will create the process.") ) $ErrorActionPreference="SilentlyContinue" Trap { Write-Warning "There was an error connecting to the remote computer or creating the process" Continue } Write-Host "Connecting to $computername" -ForegroundColor CYAN Write-Host "Process to create is $cmd" -ForegroundColor CYAN [wmiclass]$wmi="\\$computername\root\cimv2:win32_process" #bail out if the object didn't get created if (!$wmi) {return} $remote=$wmi.Create($cmd) if ($remote.returnvalue -eq 0) { Write-Host "Successfully launched $cmd on $computername with a process id of" $remote.processid -ForegroundColor GREEN } else { Write-Host "Failed to launch $cmd on $computername. ReturnValue is" $remote.ReturnValue -ForegroundColor RED } } 

示例用法:

 New-RemoteProcess -comp "puck" -cmd "c:\windows\notepad.exe" 

这是psexec / powershell链接。

有趣的是,我用它在远程计算机上运行记事本,并没有出现。 我检查了任务pipe理器和调用返回的进程ID确实存在!

Windows表示这是一个安全概念,这个过程将会隐藏起来或者在后台运行!

这段代码帮助我远程执行一个bat文件,希望这有助于将来的某个人。 您需要replace脚本顶部的creds和ComputerName vars。

 $Username = "username" $Password = "password" $ComputerName = "remote.machine.hostname" $Script = {C:\test.bat > C:\remotelog 2>&1} #Create credential object $SecurePassWord = ConvertTo-SecureString -AsPlainText $Password -Force $Cred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $Username, $SecurePassWord #Create session object with this $Session = New-PSSession -ComputerName $ComputerName -credential $Cred #Invoke-Command $Job = Invoke-Command -Session $Session -Scriptblock $Script -AsJob $Null = Wait-Job -Job $Job #Close Session Remove-PSSession -Session $Session 

RE:Nick的回答

是的,PowerShell v2(带有WinRM 2.0)与Server 2008 R2和Windows 7捆绑在一起。XP,Vista,2003和2008即将推出一个低级版本。

你总是可以select使用WMI来运行远程的东西,但它必须与控制台交互,这不是一个可行的方法。