【问题标题】:CloseMainWindow not work in invoke-commandCloseMainWindow 在调用命令中不起作用
【发布时间】:2017-12-08 11:07:38
【问题描述】:

我想从本地 powershell 脚本远程停止一个 winform 应用程序,但 CloseMainWindow 函数似乎不起作用

---这是连接远程服务器执行closeApp.ps1的本地命令,它存储在服务器上--

$remoteSession = New-PSSession -computerName 'xxx' -credential $cred  
Invoke-Command -session $remoteSession -command {F:\AutoDeployment\closeApp.ps1}  
Remove-pSSession -session $remoteSession 

---这是closeApp.ps1的主要内容,它获取活动进程并尝试关闭它--

$app = Get-Process AppName -ErrorAction SilentlyContinue  
if($app)  
{  
  $app.MainWindowTitle  
  $app.CloseMainWindow()  
}  

我希望它应该像本地一样正确关闭应用程序。

但现在它为 mainWindowTitle 行返回 null,为 closeMainWindow 返回 False。 该脚本直接运行在服务器上运行良好,但通过invoke-command执行时,MainWindow似乎无效且不起作用。

我通过 jenkins 插件 powershell 调用这个命令

更新:

closeMainWindow 没有通过 invoke-command 的错误日志,但它总是返回“假”,预期为“真”。

此外,如果closeMainWindow 失败,我还有一个步骤将尝试发送关键操作以使该应用停止。我使用[System.Windows.Forms.SendKeys]::SendWait 来实现这一点。 它也可以在本地工作,但在带有日志的服务器上通过invoke-command 失败:

sendkeys 的错误日志:

Exception calling "SendWait" with "1" argument(s): "Access is denied" + CategoryInfo : NotSpecified: (Exception calli...cess is denied":String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError

【问题讨论】:

    标签: powershell jenkins


    【解决方案1】:

    我怀疑在远程调用期间未加载 Winforms 的程序集,因此您没有可用的 CloseMainWindow 函数。尝试显式加载程序集,如下所示:

    Add-Type -AssemblyName System.Windows.Forms
    $Form = New-Object system.Windows.Forms.Form
    

    由于您没有提供有关错误代码的足够信息,您可以尝试以下方法,通过绕过该运行来排除执行策略限制:

    $remoteSession = New-PSSession -computerName 'xxx' -credential $cred
    
    Invoke-Command -session $remoteSession -command {powershell.exe -execution Bypass -file 'F:\AutoDeployment\closeApp.ps1'}
    
    Remove-pSSession -session $remoteSession
    

    【讨论】:

    • 感谢您的评论,但实际上closeMainWindow 是 Process 类而不是 Forms 的函数,尽管我在脚本中为“System.Windows.Forms”和“Microsoft.VisualBasic”添加了程序集负载供进一步使用,但它仍然在 closeMainWindow 上返回 False
    【解决方案2】:

    我想我知道为什么现在会出现这个问题,并希望这对任何人都有帮助。

    Windows 只是阻止任何远程操作来调用交互式进程(据我所知),所以每次我尝试通过远程计算机中的invoke-command 启动进程时,它只会启动一个“幽灵”进程它是不可见的。所以我认为这就是为什么我不能正确使用closeMainWindow 函数的原因,因为它与 UI 相关。

    我的目的是对远程上的可见程序做一些事情(发送密钥)以进行自动部署,所以我发现唯一的方法是使用schtasks 来安排远程操作并让远程自己做 UI 部分。这行得通现在对我来说很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-11
      • 2011-05-08
      • 2015-05-20
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多