After using somehow tedious interface of WMI Tester, presented in the Part 2 of this series, you might be glad to find out that there is a scripted way of enumerating all namespaces on a local or remote computer. This, however, requires using a recursive function. This term describes a function that calls itself. Most commonly known example of such function is factorial, which is the result of multiplying all integers up to a given number. For example, 3 factorial equals to 3*2*1, 4 factorial is 4*3*2*1, etc. The factorial qualifies as recursive function because it can be defined in the following fashion:
- factorial of 1 is 1
- factorial of n is the result of multiplying n by the factorial of (n-1)
Based on this definition, factorial of e.g. 4, can be written as
4*(factorial of 3) = 4*3*(factorial of 2) = 4*3*2*(factorial of 1) = 4*3*2*1.
We can use similar approach when enumerating namespaces. We will define a function called GetNamespace, that will perform as follows:
- GetNamespace of the bottom level namespace will give us its name
- GetNamespace of a non-bottom level namespace will give us its name and apply GetNamespace to each of its child-namespaces.
As you already know (from the part 2 of the series), you can find all child-namespaces for any namespace by enumerating (listing) all instances of its __NAMESPACE class. By executing GetNamespace function starting at the root, we will get the listing of all namespaces on the computer. Just set the value of sComputer string to the name of the target computer.
In order to make the display more "tree-like", I also used indentation to indicate position of the namespace in the hierarchy.
sNS = "root"
sComputer = "MyComputer"
Call GetNamespace(sNS, 0)
Sub GetNamespace(sNameSpace, iCount)
Dim cNamespaces
Dim oNS
WScript.Echo String(iCount, "---") & sNameSpace
Set cNamespaces = GetObject("winmgmts://" & sComputer & "/" & _
sNameSpace).InstancesOf ("__NAMESPACE")
For Each oNS In cNamespaces
Call GetNamespace(sNameSpace & "/" & oNS.Name, iCount + 3)
Next
End Sub