最近学习了一点wmi知识,感觉还很好用,只是在结束远程计算机上的程序时花费了一些时间,在网上找了几天资料,发现大多数是用C#写的,要不就是脚本写的,其中有很多代码都把停止服务当做是结束进程,也有很多人只提供结束本地进程的,说是会写这个就很快会写结束远程进程的,可是对于初学者而言有很大的困难,现就我整理出的代码给大家贴出一份,保证能用,源码比较乱,请大家不要打我就行,下面是我的源码:
Dim num As Integer = L_list.SelectedItems(0).Index '所选行的索引
Dim path As String = L_list.Items(num).SubItems(2).Text '获取第n+1列num行的单元格的值,本例得到路径
Dim proc_name As String = L_list.Items(num).SubItems(1).Text '得到程序名称
Try
'用来实现启动远程计算机上的程序
Dim ip As String = DG_show.CurrentRow.Cells("IP").Value.ToString
Dim conn As New System.Management.ConnectionOptions
Dim jc As String
conn.Username = DG_show.CurrentRow.Cells("用户名").Value.ToString
jc = PulsDes(DG_show.CurrentRow.Cells("密码").Value.ToString,Mkey)
If jc = "1" Then
conn.Password = ""
Else
conn.Password = jc
End If
Dim ms As New System.Management.ManagementScope("//" & ip & "/root/cimv2",conn)
Try
ms.Connect()
&nb
Catch ex As Exception
MessageBox.Show("连接远程主机失败,信息如下:" & ex.Message,"错误提示",MessageBoxButtons.OK,MessageBoxIcon.Error)
Exit Sub
End Try
'结束进程
Dim oq As New ObjectQuery("SELECT * FROM Win32_Process")
Dim query1 As New ManagementObjectSearcher(ms,oq)
Dim queryCollection1 As ManagementObjectCollection = query1.Get()
Dim service As New ManagementObject
For Each service In queryCollection1
If service("Name").ToString() = proc_name Then
service.InvokeMethod("Terminate",Nothing)
End If
Next service
MessageBox.Show("从远程主机成功结束" & proc_name & "程序。","结束程序提示",MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
其中L_list是一个listview控件,本程序在vs2005中可以运行.DG_show是一个datagridview控件,我用来存用户名,密码和IP地址,PulsDes是自己定义的一个解密函数,用来取得真正的密码.关键部分是下面的代码:
Dim
oq As New ObjectQuery("SELECT * FROM Win32_Process") Dim query1 As New ManagementObjectSearcher(ms,oq) Dim queryCollection1 As ManagementObjectCollection = query1.Get() Dim service As New ManagementObject For Each service In queryCollection1 If service("Name").ToString() = proc_name Then service.InvokeMethod("Terminate",Nothing) End If Next service
原文链接:https://www.f2er.com/vb/261407.html