运行 来自当前桌面的远程桌面上的 powershell 脚本

Running a powershell script on remote desktop from current desktop

所以基本上我的远程服务器上有一个已经运行的脚本。我正在尝试在我的电脑上 运行 一个 powershell 脚本,它会自动进入远程桌面,然后 运行 我的脚本在那边。

我现在使用的简单脚本不起作用:

mstsc /v:Server
Invoke-Expression c:\Scripts\script.ps1
$userName = 'administrator'
$sessionId = ((quser /server:server | Where-Object { $_ -match $userName }) -split ' +')[2]
logoff $sessionId /server:server

如您所见,我的脚本位于 c:\Scripts。事情是忽略远程桌面并打开我电脑的 c:\。

我应该如何 "stay" 在远程桌面上执行我的脚本?

此外,我不确定我的注销代码是否有效。我在一个线程中的某个地方找到了它,如果它的编码正确,我也想要一些澄清。我知道我可以使用计划任务,但我正在努力改用这种方式。

非常感谢!

mstsc /v:Server 可能会为您打开远程桌面,控制台仍在您自己的计算机上,您需要远程重新启动控制台或使用@AdamMnich 在上面的评论中提供的选项。

我什至不想知道您怎么会认为 mstsc /v:Server 可以在脚本中以这种方式工作,但这是一个不错的尝试 ;)

建议的解决方案如下所示:

$RemoteComputer = "ServerHostNameOrIPAdress"
Invoke-Command -Computername $RemoteComputer -ScriptBlock {."c:\Scripts\script.ps1"} #Assuming the script is on the C:\ Drive of the RemoteComputer