The VBScript Network and Systems Administrator's Cafe

Dec 4 2008   9:22PM GMT

Using WMI’s WIN32_Process class to remotely kill a process



Posted by: Jerry Lees
VBScript, kill, win32_process, Kill processes, pkill, kill process

Recently I had a situation where I had to kill a number of processes on a number of servers in a short period of time so we could update the executable file quickly so the processes could be safely respawned. This presented a challenge because it needed to be done quickly both before users respawned the process multiple times on each server and because the number of servers involved did not lend itself to simply logging onto the server and killing the processes one server at a time.

So I pulled out the scripting hat and went to work making use of the WMI Win32_Process class to create the following function that gets passed the process name you want to kill and the remote server name where you want to kill the processes.   Worked like a champ! One hitch was that there were users still on the server, but that was solved by simply running the script multiple times while we copied the new files to the servers.

So, here is the function I spoke about… hopefully you can add it to your list of script tools in your scripting tool belt!
Function RemoteKill( StrComputer1, ProcessName)

    Dim objWMIService, colItems, objItem

    On Error Resume Next
    ‘ error control block
    Set objWMIService = GetObject(”winmgmts:{impersonationLevel=impersonate}//” &  strComputer1 & “\root\cimv2″)
    Set colItems = objWMIService.ExecQuery (”Select * from Win32_Process Where Name = ‘” & ProcessName & “‘”)
    For Each objItem in colItems
        RemoteKill = RemoteKill & VbCrLf & strComputer1 & “: “
        RemoteKill = RemoteKill & objItem.name & “(PID: ” & objItem.processid & “) Terminated.”
        ObjItem.terminate
    Next
    On Error GoTo 0
End Function

Comment on this Post


You must be logged-in to post a comment. Log-in/Register