Share via


PowerShell and Executable Output (with Boats)

What floats your boat?

For me, it’s usually a body of water, but I also like being asked stuff about PowerShell. Here’s one such question:

“How come in a forest with two domains each with two (2008R2) domain controllers I get the following results with PowerShell?

(nltest /dclist:MyDomain)            - gives me the list of domain controllers for the domain (2)

(nltest /dclist:MyDomain).count - gives me the count of domain controllers for the forest (4)…”

 

Here’s the short answer: it’s counting the number of lines of text outputted to the host by nltest…

Why?

Let’s run nltest:

 

             

 

As (almost) everything in PS is an object, the text returned by a legacy executable is actually a series of strings written to an array object:

 

 

Count returns the number of objects in the array and as it’s an array, we can access its elements. Here’s the first string in the array, retrieved using the [0] notation:

 

 

 

Here’s the end of the array, accessed using the [-1] notation:

 

               

 

And just to prove we are dealing with an array of strings:

 

 

 

So, rather than using a legacy binary that returns text, we should use a cmdlet to return objects:

 

(Get-ADDomainController -Filter *).Count

or

Get-ADDomainController -Filter * -Server fabrikam.com | Measure-Object

 

  I do like a good boat.

Comments

  • Anonymous
    January 01, 2003
    Or try this...

    $domain = [directoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
    $dcs = $domain.FindAllDomainControllers()
  • Anonymous
    January 01, 2003
    Here's one that relies on the [ADSI] type accelerator...

    $ou = [ADSI]‘LDAP://OU=Domain Controllers,DC=fabrikam,DC=com‘
    $dcs = $ou.psbase.get_children()
  • Anonymous
    January 01, 2003
    And then filter with this (will work with v2):

    $dcs = $dcs | select Name
  • Anonymous
    May 08, 2014
    Hi,

    nice to know. THX. I must find out from a normal client W7 which DCs are available.
    So no AD modul on client!

    Do you have an idea to get the servernames into an array...from (nltest /dclist:MyDomain) ?
    Or another idea with PSv3?

    Frank