如何从WMI spun远程进程获取退出代码

时间:2011-09-26 18:49:25

标签: c# wmi

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

有什么方法可以让我知道这个过程何时结束?谢谢!

2 个答案:

答案 0 :(得分:3)

面对同样的问题并写了一个简单的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);

可以从here下载源代码。

给凯撒他的到期,代码的灵感来自this one。简单地:

  • 将事物重构为静态类
  • 添加了对远程处理参数的更多控制
  • 重新设计的事件监视器,用于抑制无法提及的CheckProcess测试

答案 1 :(得分:0)

这是一个在.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