I'm executing a remote CMD line command via WMIC that takes a few seconds to run. I'm currently doing Thread.Sleep(4000) before moving on...there MUST be a better way! Is there a variable 开发者_如何学Cor method I can use to determine if the command I issued finished / a status byte?
Thanks!
Im using the following code to issue the commands:
ManagementClass processTask = new ManagementClass(@"\\" + this.wmiConnection.machineName + @"\root\CIMV2", "Win32_Process", null);
ManagementBaseObject methodParams = processTask.GetMethodParameters("Create");
methodParams["CommandLine"] = command;
methodParams["CurrentDirectory"] = @"C:\";
Just need to figure out how to determine when the command finishes :). Thanks!
In my understanding, when you write this :
ManagementClass processTask = new ManagementClass(@"\\192.168.183.100\root\CIMV2", "Win32_Process", null);
ManagementBaseObject methodParams = processTask.GetMethodParameters("Create");
methodParams["CommandLine"] = "cmd.exe";
methodParams["CurrentDirectory"] = @"C:\";
//Execute the method
ManagementBaseObject outParams = processTask.InvokeMethod("Create", methodParams, null);
You are launching the remote process in a synchronous way, so
outParams["returnvalue"]
outParams["processid"]
Will give the return code and processId as explain in How To: Execute a Method, if you want to run it asynchronously you can read this : How To: Call a Method Asynchronously.
There is a similar question posted here: Wait for service.InvokeMethod to finish - WMI, C#
The following documentation How To: Execute a Method and How To: Call a Method Asynchronously describe semi-synchronous and asynchronous execution. What you are doing is semi-synchronous execution.
As far as I can tell, this provides feedback on where WMI executed the command successfully. If it is a long running command such as running an installer, stopping a service, or executing a batch file, WMI will return when the installer launches, the service was told to start stopping or the batch file process is started.
To really wait for the new process to exit, as far as I can tell, you will need to poll to see if the process is running, or query if the service is stopped. In your case, depending on the command, poll the process id.
I am still looking into this myself as well.
精彩评论