Using Active Directory Object Picker Dialog to Find and Select a Computer
I often need to write scripts that take the name of a computer as an input. This can be accomplished by prompting the user running the script to enter the name of a computer, but what if the user types the name incorrectly? Or what if the computer has been decommissioned and no longer exists in the directory? These potential issues can be avoided by writing code to specifically launch the object picker dialog from Active Directory Users and Computers.
The dialog looks like this:

It's surprisingly difficult to directly interface to the object picker. Fortunately Sly Gryphon has developed a .NET wrapper for the dialog that is available from CodePlex. I downloaded and compiled the code using Visual Studio 2008 to generate the wrapper (CubicOrange.Windows.Forms.ActiveDirectory.dll). I then created a new Windows console application named FindComp using the code shown below (adding the wrapper and System.Windows.Forms as references). The code ensures the object picker dialog is restricted to selecting a single computer from the current domain. It then writes the fully qualified path of the selected computer to the console window.
Imports CubicOrange.Windows.Forms.ActiveDirectory
Imports System.Windows.Forms
Module Module1
Sub Main()
Dim ObjectPicker As New DirectoryObjectPickerDialog
Dim ObjectPickerResult As DialogResult
Dim SelectedObject As DirectoryObject
ObjectPicker.AllowedObjectTypes = ObjectTypes.Computers
ObjectPicker.DefaultObjectTypes = ObjectTypes.Computers
ObjectPicker.AllowedLocations = Locations.JoinedDomain
ObjectPicker.DefaultLocations = Locations.JoinedDomain
ObjectPicker.MultiSelect = False
ObjectPickerResult = ObjectPicker.ShowDialog()
If ObjectPickerResult = DialogResult.OK Then
SelectedObject = ObjectPicker.SelectedObject
System.Console.Write(SelectedObject.Path)
End If
End Sub
End Module
We can now wrap the compiled application into a command line script as shown below. The script invokes FindComp, displays the object picker, and following the selection of a computer, assigns the fully qualified path of the computer to the variable sComputer, which can then be utlised as required.
Set oShell = CreateObject("WScript.Shell")
Set oExec = oShell.Exec("FindComp.exe");
Do While oExec.StdOut.AtEndOfStream <> True
sComputer = oExec.StdOut.ReadLine
Loop
WScript.Echo sComputer
Note: FindComp.exe will return the fully qualified path of the selected computer in the form of:
LDAP://domain.net/CN=CompName,CN=Computers,DC=domain,DC=net
I used ILMerge to remove the external dependence on CubicOrange.Windows.Forms.ActiveDirectory.dll by merging the DLL with FindComp.exe.
You can download either the resultant merged executable file or the project source code.
The requirements for using this program are the .NET Framework and the Active Directory Users and Computers console.