Click here to Skip to main content
15,887,293 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

i'm using the following code to run a copied file from Command line on remote machine.
That works well but my problem is that the return code is instant 0 also if i try a command which is not working.

Here is the code:

C#
ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.EnablePrivileges = true;

ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", reachablehost), connOptions);
manScope.Connect();


ObjectGetOptions objectGetOptions = new ObjectGetOptions();
ManagementPath managementPath = new ManagementPath("Win32_Process");
ManagementClass processClass = new ManagementClass(manScope, managementPath, objectGetOptions);



ManagementBaseObject inParams = processClass.GetMethodParameters("Create");


inParams["CurrentDirectory"] = @"C:\Windows\Temp\swdeploy";
inParams["CommandLine"] = @"cmd /c setup.exe /silent";

ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);


Cursor = Cursors.Default;

if (outParams["returnValue"].ToString() == "0")
{
MessageBox.Show("Die Installation wurde erfolgreich abgeschlossen", "Installation erfolgreich", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Die Installation wurde mit Code " + outParams["returnValue"].ToString() + " abgeschlossen.\n\nFehlertext:\n\n" + outParams["returnText"].ToString(), "Installationsfehler", MessageBoxButtons.OK, MessageBoxIcon.Error);
}


Can someone help me here?

What I have tried:

if i use a:

cmd /c start /wait



it's also not waiting to finish.

Thanks in Advance
Posted
Updated 23-Dec-21 9:09am
Comments
[no name] 23-Dec-21 9:31am    
Implies a deadlock. You should poll if you want to know what an other process is doing; or use a callback.

Have you tried adding a watcher, as described in this documentation?

ManagementObject.InvokeMethod Method (System.Management) | Microsoft Docs[^]
 
Share this answer
 
It returns a 0 because this is a "fire and forget" process. The process of launching a remote process only returns a value for the process of launching the process. It does NOT wait for the launched process to finish executing and return that exit code.

There is no in-built method to "Wait for exit" on a Win32_Process, so you can then get the exit code. You have to write a wrapper around the Win32_Process.Create call to implement that functionality.

Fortunately for you, someone already did that. You can find the code here[^].
 
Share this answer
 
Thanks that helped!

i used the Wrapper and it worked.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900