Powershell Start-Process 不启动远程机器上的进程

Powershell Start-Process does not start the process on remote machine

我正在处理一个必须启动应用程序的项目,该应用程序应在后台保持 运行。我尝试了 Start-Process cmdlet,如下所示:

try {
    Invoke-Command -Session $newsession -Scriptblock {
      Write-Host "Cd'ing and starting Vesper on" $loadvm
      Start-Process cmd -ArgumentList "/c C:\vesper_cpt\Vesper.exe -auto" -verb runas
    } -ErrorAction Stop
} catch [Exception] {
    echo "Error while running the remote command", $_.Exception.GetType().FullName, $_.Exception.Message
    Remove-PSSession $newsession
    exit 1
}

删除-PSSession $newsession

发生的事情是,我可以看到它在目标机器上启动了一个 cmd 进程,但随后它立即消失了。我不确定我应该在这里做什么才能启动该过程并且始终 运行。另一方面,我也尝试了 Invoke-Expression cmdlet,通过这个我可以看到进程在远程机器上启动正常,但 powershell 脚本从来没有 returns 那就是为什么想到使用 Start-Process。有什么建议吗?

在尝试了很多类似 Invoke-Expression、Start-Process 的方法后,我找到了我的进程在远程机器上启动后立即退出的原因。原因是我 运行ning 的应用程序是 Java 应用程序。而且,JVM 不允许守护线程 运行 机器上的进程。另一方面,如果至少有一个用户线程处于活动状态,则 Java 运行 时间不会终止您的应用程序。

在我的设置中,我 运行 在远程机器上安装应用程序(在本例中 Vesper.exe)所以我创建了一个 New-PSSession最后,我是 Removing-PSSession。因此,没有用户线程留给 运行 应用程序,因此应用程序正在关闭。

此问题的解决方案不是 Removing-PSSession,而是 Exit-PSSession。 Exit-PSSession,使线程保持活动状态并且您的应用程序不会终止。请注意,您将负责如何退出应用程序,因为即使您的程序已完成,应用程序仍会 运行ning 在远程计算机上。

try {
    Invoke-Command -Session $newsession -Scriptblock {
      Write-Host "Cd'ing and starting Vesper on" $loadvm
      Start-Process cmd -ArgumentList "/c C:\vesper_cpt\Vesper.exe -auto" -verb runas
    } -ErrorAction Stop
} catch [Exception] {
    echo "Error while running the remote command", $_.Exception.GetType().FullName, $_.Exception.Message
    Remove-PSSession $newsession
    exit 1
}

Exit-PSSession

这取决于您在捕获到异常时想要做什么。您可以根据您的环境设置删除或退出会话。

我从以下两个问题中找到了答案:

  • will main thread exit before child threads complete execution?

希望对您有所帮助。

谢谢