我如何从WMI旋转远程进程获得退出代码

本文关键字:进程 代码 退出 程进程 WMI 旋转 | 更新日期: 2023-09-27 18:09:49

我正在通过WMI (Win32_Process Create)远程执行进程,但我无法弄清楚我如何确定进程何时完成执行。当我第一次发出命令时,有一个退出代码(0表示成功),但这只是告诉我进程已成功生成。

有没有办法让我知道这个过程什么时候结束?谢谢!

我如何从WMI旋转远程进程获得退出代码

遇到同样的问题,写了一个简单的VMI包装器:

var exitStatus = WmiOperations.Run("notepad.exe", wait:10);

Run的概要:

int Run(string command, // Required
        string commandline = null, // (default=none)
        string machine = null, // (default=local)
        string domain = null, // (default=current user domain)
        string username = null, // (default=current user login)
        string password = null, // (default=current user password)
        SecureString securePassword = null, // (default=current user password)
        double wait = double.PositiveInfinity); // (default=wait til command ends);

源代码可从这里下载。

给凯撒应得的,代码的灵感来自于这个。简单:

  • 将东西重构为静态类
  • 添加了更多远程参数控制
  • 重新设计事件监视器以抑制不吸引人的CheckProcess测试

这是一个在。net对象上创建的例子,但用Powershell编写,很容易转换为c#

Clear-Host
# Authentication object
$ConOptions = New-Object System.Management.ConnectionOptions
$ConOptions.Username = "socite'administrateur"
$ConOptions.Password = "adm"
$ConOptions.EnablePrivileges = $true
$ConOptions.Impersonation = "Impersonate"
$ConOptions.Authentication = "Default"
$scope = New-Object System.Management.ManagementScope("''192.168.183.220'root'cimV2", $ConOptions)
$ObjectGetOptions = New-Object System.Management.ObjectGetOptions($null, [System.TimeSpan]::MaxValue, $true)
# Equivalent to local :
# $proc = [wmiclass]"''.'ROOT'CIMV2:Win32_Process"
$proc = New-Object System.Management.ManagementClass($scope, "''192.168.183.220'ROOT'CIMV2:Win32_Process", $ObjectGetOptions)
# Now create the process remotly
$res = $proc.Create("cmd.exe")
# Now create an event to detect remote death
$timespan = New-Object System.TimeSpan(0, 0, 1)
$querryString = "SELECT * From WIN32_ProcessStopTrace WHERE ProcessID=$($res.ProcessID)"
$query = New-Object System.Management.WQLEventQuery ($querryString)
$watcher = New-Object System.Management.ManagementEventWatcher($scope, $query)
$b = $watcher.WaitForNextEvent()
$b