ActiveState Code

Recipe 66311: Get the Windows service name from the long name


Many programs only show the long service description such as 'Windows Time', but this recipe finds you the actual service name.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import win32api
import win32con

def GetShortName(longName):
    # looks up a services name
    # from the display name
    hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services", 0, win32con.KEY_ALL_ACCESS)
    num = win32api.RegQueryInfoKey(hkey)[0]

    # loop through number of subkeys
    for x in range(0, num):
        # find service name, open subkey
        svc = win32api.RegEnumKey(hkey, x)
        skey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, \
"SYSTEM\\CurrentControlSet\\Services\\%s" % svc, 0, win32con.KEY_ALL_ACCESS)
        try:
            # find short name
            shortName = str(win32api.RegQueryValueEx(skey, "DisplayName")[0])
            if shortName == longName:
                return svc
        except win32api.error: 
            # in case there is no key called DisplayName
            pass
    return None

if __name__=='__main__':
    assert(GetShortName('Windows Time') == 'W32Time')
    assert(GetShortName('FoobarService') == None)

Discussion

This loops through the services on a Windows box (2000/NT) by moving through the registry. For each service it opens the registry key and looks at the key for the Display Name. It then returns it if matched.

It can often be useful since many programs will report "Windows Time" when you need the string "W32Time" in order to restart the service.

Comments

  1. 1. At 2:54 p.m. on 16 jun 2008, Grant Brady said:

    Do it old school. I don't see what the point of writing this code is. Its pointless, its useless. I don't mean to be condescending but idiots like you have forgotten (or have never learned) the beauty, elegance, and finesse of the command line. There is a reason why CLI's are included some 20 years after to GUI was added to operating systems. This whole program can be replaced by "sc GetKeyName DisplayName" where DisplayName is replace with the service you want to look up. Not only that, but sc allows you to stop, start, restart, pause, edit, create, delete (and so on) services.

    I respect you're fine coding but the complete pointlessness of it kills it. Perhaps next you can write an application that can echo a string of text.

Sign in to comment