compA to tell compB to start/exit program using Vb.net and WMI

remya1000

Well-known member
Joined
Mar 29, 2007
Messages
122
Programming Experience
Beginner
i need computer A to tell computer B to start or Exit a program. and computer B should do Exit or start while computer A gives start or exit direction.
i'm using VB.NET and WMI. and i'm new to WMI. i dont have anyidea how computer A and connect to computer B.
any idea how can i do this.
if you have any idea please help me.
thanks in advance
 
you could modify the code below to terminate the other program simply by seeing if it's running or not:

VB.NET:
    Private Function IsProgramOpen(ByVal ProcessName As String) As Boolean
        Dim prc() As Process
        Dim intNumProcess As Integer = 0I
        prc = System.Diagnostics.Process.GetProcessesByName(ProcessName)
        Dim eprc As IEnumerator = prc.GetEnumerator
        eprc.Reset()

        While eprc.MoveNext
            Dim proc As Process = CType(eprc.Current, Process)
            intNumProcess += 1
            proc = Nothing
        End While

        eprc = Nothing
        prc = Nothing
        If intNumProcess > 0 Then
            Return True
        Else
            Return False
        End If
    End Function

where it says 'intNumProcess += 1' you'd change it to proc.Kill, and make this function a sub instead
 
Download the WMI code creator, then query the remote machine for its processes and the handle of it. Then invoke the Terminate method and insert the handle parameter.

For example: closing firefox on a remote computer:

VB.NET:
  [FONT=&quot]    [COLOR=blue]Private[/COLOR] [COLOR=blue]Sub[/COLOR] btnTerminate_Click([COLOR=blue]ByVal[/COLOR] sender [COLOR=blue]As[/COLOR] System.Object, [COLOR=blue]ByVal[/COLOR] e [COLOR=blue]As[/COLOR] System.EventArgs) [COLOR=blue]Handles[/COLOR] btnTerminate.Click[/FONT]
  [FONT=&quot]        [COLOR=blue]Try[/COLOR][/FONT]
  [FONT=&quot]            [COLOR=blue]Dim[/COLOR] processHandle [COLOR=blue]As[/COLOR] [COLOR=blue]Integer[/COLOR][/FONT]
  [FONT=&quot]            [COLOR=blue]Dim[/COLOR] connection [COLOR=blue]As[/COLOR] [COLOR=blue]New[/COLOR] ConnectionOptions[/FONT]
  [FONT=&quot]            connection.Username = "Your Username here"[/FONT]
  [FONT=&quot]            connection.Password = "Your password here"[/FONT]
  [FONT=&quot]            connection.Authority = "ntlmdomain:DOMAIN" [COLOR=green]'Domain needs to be changed by your domain name[/COLOR][/FONT]
  [FONT=&quot]            [COLOR=blue]Dim[/COLOR] scope [COLOR=blue]As[/COLOR] [COLOR=blue]New[/COLOR] ManagementScope([/FONT][FONT=&quot]"\\FullComputerName\root\CIMV2", connection) [COLOR=green]'Full Computername needs to be changed by the computername[/COLOR][/FONT]
  [FONT=&quot]            scope.Connect()[/FONT]
  
  [FONT=&quot]            [COLOR=blue]Dim[/COLOR] query [COLOR=blue]As[/COLOR] [COLOR=blue]New[/COLOR] ObjectQuery( [/FONT][FONT=&quot]"SELECT * FROM Win32_Process")[/FONT]
  [FONT=&quot]            [COLOR=blue]Dim[/COLOR] searcher [COLOR=blue]As[/COLOR] [COLOR=blue]New[/COLOR] ManagementObjectSearcher(scope, query)[/FONT]
  
  [FONT=&quot]            [COLOR=blue]For[/COLOR] [COLOR=blue]Each[/COLOR] queryObj [COLOR=blue]As[/COLOR] ManagementObject [COLOR=blue]In[/COLOR] searcher.Get()[/FONT]
  [FONT=&quot]                [COLOR=blue]If[/COLOR] queryObj("Caption") = "firefox.exe" [COLOR=blue]Then[/COLOR][/FONT]
  [FONT=&quot]                    processHandle = queryObj("Handle")[/FONT]
  [FONT=&quot]                    [COLOR=blue]Exit[/COLOR] [COLOR=blue]For[/COLOR][/FONT]
  [FONT=&quot]                [COLOR=blue]End[/COLOR] [COLOR=blue]If[/COLOR][/FONT]
  [FONT=&quot]            [COLOR=blue]Next[/COLOR][/FONT]
  
  [FONT=&quot]            [COLOR=blue]Dim[/COLOR] classInstance [COLOR=blue]As[/COLOR] [COLOR=blue]New[/COLOR] ManagementObject(scope,[/FONT][FONT=&quot][COLOR=blue]New[/COLOR] ManagementPath("Win32_Process.Handle='" & processHandle & "'"),[/FONT][FONT=&quot][COLOR=blue]Nothing[/COLOR])[/FONT]
  [FONT=&quot]            [COLOR=blue]Dim[/COLOR] inParams [COLOR=blue]As[/COLOR] ManagementBaseObject = [/FONT][FONT=&quot]classInstance.GetMethodParameters("Terminate")[/FONT]
  [FONT=&quot]            [COLOR=blue]Dim[/COLOR] outParams [COLOR=blue]As[/COLOR] ManagementBaseObject = [/FONT][FONT=&quot]classInstance.InvokeMethod("Terminate", inParams, [COLOR=blue]Nothing[/COLOR])[/FONT]
  [FONT=&quot]        [COLOR=blue]Catch[/COLOR] ex [COLOR=blue]As[/COLOR] Exception[/FONT]
  [FONT=&quot]            MsgBox(ex.ToString)[/FONT]
  [FONT=&quot]        [COLOR=blue]End[/COLOR] [COLOR=blue]Try[/COLOR][/FONT]
  [FONT=&quot]    [COLOR=blue]End[/COLOR] [COLOR=blue]Sub[/COLOR][/FONT]

note: Don't forget to import the system.management namespace and add a reference to it.


I haven't been able to test the code but it should work as i copied moest of it out of the WMI code creator.
 
Last edited:
Thanks for your reply's and thanks for the time you spend for me. i will try ur codes now. before receiving ur reply i just tried this codes. just go through this and tell what's wrong. sorry for disturbing u again....

i'm tring to start a calculator in a remote machine from my system. and the codes i tried is this.

VB.NET:
Module Module1
Sub Main()
Dim retValue As String
retValue = RunCommand("calc.exe", "MachineName", "MachineName\UserID", "Password")
Console.WriteLine(retValue)
End Sub
 
Function RunCommand(ByVal strCommand As String, ByVal strMachineName As String, _
ByVal strUserName As String, ByVal strPassword As String) As String
Dim options As New System.Management.ConnectionOptions
options.Username = strUserName
options.Password = strPassword
options.Impersonation = Management.ImpersonationLevel.Impersonate
options.Authentication = Management.AuthenticationLevel.PacketPrivacy
 
Dim path As New System.Management.ManagementPath("\\" & strMachineName & "\root\cimv2:Win32_Process")
Dim scope As New System.Management.ManagementScope(path, options)
 
scope.Connect()
 
Dim opt As New System.Management.ObjectGetOptions
Dim classInstance As New System.Management.ManagementClass(scope, path, opt)
 
Dim inParams As System.Management.ManagementBaseObject = classInstance.GetMethodParameters("Create")
inParams("CommandLine") = strCommand
 
' Execute the method and obtain the return values.
Dim outParams As System.Management.ManagementBaseObject = classInstance.InvokeMethod("Create", inParams, Nothing)
Return "ReturnValue:" & outParams("returnValue") & " Process ID: {0}" & outParams("processId")
 
End Function
 
End Module
******while i tried to connect to some machines this error occurs.

An unhandled exception of type 'System.UnauthorizedAccessException' occurred in system.management.dll
Additional information: Access is denied.

*******and to someother machines and to the local machine this error occurs.

An unhandled exception of type 'System.InvalidCastException' occurred in microsoft.visualbasic.dll
Additional information: Cast from type 'UInt32' to type 'String' is not valid.
and my local machine the calculator is poping up and this above error occurs. but while connecting to remote machine, to some machine access is denied to some other the above error occurs and calc is not popping up too.

and one have anyidea what's wrong with my codes... please help me.
thanks in advance.
 
Last edited by a moderator:
i'm able to terminate the program from remote machine's(the program is opened manually). but while trying to open the program, the program is opened in the background in task manager. but i need to pop up the program.
and i commented this line
Return "ReturnValue:" & outParams("returnValue") & " Process ID: {0}" & outParams("processId")

so the error gone now. but need to display the calculator in front. not in taskmanager.
anyidea how to make the calculator display in screen. if u have anyidea please let me know.
thanks in advance

 
I think the reason it only shows up in the taskmanager is cause it is run by a different user and will only pop up when the program is run as the user who is logged into the machine.
At the moment I'm pretty bussy but as my current project requires me to do the same thing you're trying to do I'll try to give you a sollution by the end of this week :) unless someone beat me to it.
 
You can show the window by adding processstartupinformation. If you want the window to show then you can do it like this:

VB.NET:
                Dim procStart As ManagementClass = New ManagementClass("Win32_ProcessStartup")
                Dim ps As ManagementObject = procStart.CreateInstance
                ps("ShowWindow") = 4

Then with the parameters you insers the object like this:

VB.NET:
                inParams("ProcessStartupInformation") = ps

You can view all the parameters on the msdn site on http://msdn2.microsoft.com/en-us/library/aa394375.aspx
 
Module Module1
Sub Main()
Dim retValue As String
retValue = RunCommand("calc.exe", "MachineName", "MachineName\UserID", "Password")
Console.WriteLine(retValue)
End Sub

Function RunCommand(ByVal strCommand As String, ByVal strMachineName As String, _
ByVal strUserName As String, ByVal strPassword As String) As String
Dim options As New System.Management.ConnectionOptions
options.Username = strUserName
options.Password = strPassword
options.Impersonation = Management.ImpersonationLevel.Impersonate
options.Authentication = Management.AuthenticationLevel.PacketPrivacy

Dim path As New System.Management.ManagementPath("\\" & strMachineName & "\root\cimv2:Win32_Process")
Dim scope As New System.Management.ManagementScope(path, options)

Dim procStart As ManagementClass = New ManagementClass("Win32_ProcessStartup")
Dim ps As ManagementObject = procStart.CreateInstance
ps("ShowWindow") = 4

scope.Connect()

Dim opt As New System.Management.ObjectGetOptions
Dim classInstance As New System.Management.ManagementClass(scope, path, opt)

Dim inParams As System.Management.ManagementBaseObject = classInstance.GetMethodParameters("Create")
inParams("CommandLine") = strCommand
inParams("ProcessStartupInformation") = ps

' Execute the method and obtain the return values.
Dim outParams As System.Management.ManagementBaseObject = classInstance.InvokeMethod("Create", inParams, Nothing)

End Function

End Module


is this the way we need to add Win32_ProcessStartup inside my program.
sorry for disturbing you again. actually i dont have much idea about WMI. i'm new to this. that's why.
if any thing wrong in this codes, please let me know. while running its not creating any errors, but not displaying the calculator in windows. that's why...
thanks in advance and thanks for your help....
 
still the calculator is opening inside the taskmanager, not pop up in windows. can you have any idea what's wrong in my codes. if you have please let me know how can i display calculator as pop up window in remote machine.
 
i just tried this code too... in a button click. but it too opening calculator in taskmanger insted of popup. if you have any idea please let me know.

Dim processHandle As Integer
Dim connection As New ConnectionOptions

connection.Username = "aa"
connection.Password = "aa"

Dim strMachineName As String
strMachineName = txtMachinename.Text

Dim scope As New ManagementScope("\\" & strMachineName & "\root\CIMV2", connection)
scope.Connect()

Dim processClass = New ManagementClass("Win32_Process")
processClass.Scope = scope

Dim inParams = processClass.GetMethodParameters("Create")

Dim startup = New ManagementClass("WIN32_ProcessStartup")
Dim ps As ManagementObject = startup.CreateInstance
Const SW_NORMAL = 1
ps("ShowWindow") = SW_NORMAL 'SW_NORMAL --- Activates and displays a window.
startup.Scope = scope

inParams("CommandLine") = "calc.exe"
inParams("ProcessStartupInformation") = startup

Dim outParams = processClass.InvokeMethod("Create", inParams, Nothing)


thanks in advance
 
anyidea what's wrong with my codes.
any idea how can i display calculator in remote machine from my machine.
if you have anyidea or anything wrong in my code please let me know about that.
or any other way i can display it other than using WMI.
Actually no idea how to proceed :confused: that's why. i'm new to this WMI and all.
Thanks in advance
 
Read what JohnH posted. I've gone through this same routine only to find the exact same article he linked. You can no longer startup an INTERACTIVE process using WMI. If you need to start the process, either use a tool like psexec found at sysinternals or use the work around with scheduled tasks that john referenced. I've used both and they both work flawlessly and with little effort.

You will not get WMI to start up an interactive process.
 
can you be more specific.
i'm new to this field. and no experiance. only 3 month i enter this filed.
so can you please give more specification how to display calculator in remote machine as pop up. in what method or tool i can display it. or can you send an example for that. it will great helpfull to me.
thanks for your help and thanks in advance.
 
remy,

You asked for an example.

Go here: http://www.microsoft.com/technet/sysinternals/Networking/PsTools.mspx

It explains what each tool in the PSTools suite does. You will find a download link at the bottom of the page. Download the file. Unzip them where ever it makes sense to you. I would suggest putting that directory in your path then. Makes using them a bit easier. If you read the usage of the tools, you'll find the instructions on how to launch a process on a remote PC. However, here is what it might look like from a command line:

psexec \\remotePC -s -i -d calc.exe

Thats it ... Pretty simple. If you want to use it in an application, just run it in a shell. Was the easiest way for me. Something like:

VB.NET:
Dim RemotePC as string = "yourmachine"
Dim process as string = "sol.exe"

shell("\\" & RemotePC & " -s -i -d " & process, AppWinStyle.Hide)

That would launch solitaire on the RemotePC.

I would try this first before trying to use task scheduler. Both are moderately easy to do, but this one is probably the easiest. It just requires downloading some extra software.

Hope this helps!
 
Back
Top