如何使用 powershell 在远程机器上执行程序?
答案1
答案2
您还可以使用 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"
答案3
这里是 psexec/powershell 链接。
答案4
此代码帮助我远程执行了一个 bat 文件,希望将来能对某人有所帮助。您需要替换此脚本顶部的 creds 和 ComputerName 变量。
$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