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.