Blog

Stop Service Running on Remote Computer

By crystal boy Blogs | Visual Basic .NET Oct 25, 2012
In this blog, we will see how to Stop service running on remote computer.
Write the code in Button click event:
 

        Try
             '#Region "Code to stop the service"
             'Assign the name of the service you want to stop on the remote machine
            Dim serviceName As String = "Enter Remote system service name here"
             'Assign the user name and password of the account to ConnectionOptions object
             'which have administrative privilege on the remote machine.
            Dim connectoptions As New ConnectionOptions()
             'connectoptions.Impersonation = ImpersonationLevel.Impersonate;  
             connectoptions.Username = "Enter Remote system login id here"
             connectoptions.Password = "Enter Remote system login password here"
             'IP Address of the remote machine
            Dim ipAddress As String = "Enter remote system ip Address here"
            Dim scope As New ManagementScope("\\" + ipAddress + "\root\cimv2")
            scope.Options = connectoptions
             'Define the WMI query to be executed on the remote machine
            Dim query As New SelectQuery("select * from Win32_Service where name = '" + serviceName + "'")
            Using searcher As New ManagementObjectSearcher(scope, query)
                Dim collection As ManagementObjectCollection = searcher.[Get]()
                For Each service As ManagementObject In collection

                    If service("Started").Equals(True) Then
                        'Stop the service
                         service.InvokeMethod("StopService", Nothing)
                    End If
                 Next
            End Using

             '#End Region
            Console.ReadLine()

        Catch ex As Exception
             'Log exception in exception log.
             'Logger.WriteEntry(ex.StackTrace);
            Console.WriteLine(ex.StackTrace)
        End Try

 
To start the service

If service("Started").Equals(True) Then
'Stop the service
service.InvokeMethod("StopService", Nothing)
End
If

COMMENT USING