Friday, April 06, 2018

Method Chaining–A Neat PowerShell Trick

I discovered an interesting  with PowerShell. It’s known as method chaining. Before explaining it – look at an example:

# c:\foo\testit.ps1
# Test of method chaining
$StringBuilder = [System.Text.StringBuilder]::New()
# Build up string contents
[string] $S1 = Get-ChildItem -Path c:\*.pdf | out-string
# Now build the string
$Null = $StringBuilder.
   AppendLine('Using String Builder as opposed to string concatenation').
   AppendFormat('This uses a cool feature: {0}', 'Method Chaining').
   AppendLine('.NET has other "builder" classes operate the same way.').
# Output the resultant string

This produces the following output:


With Method Chaining, you have an object with methods. You specify the object name (i.e. $StringBuilder) followed by a ‘.’ character. On subsequent lines you specify a method call followed by another ‘.’ character. In this case, I created the $StringBuilder object, then chained several method calls. Each method call added lines to the $StringBuilder object. You end the method chaining by omitting the .’ on the final method in the chain (the directory listing).

I’m not too sure I’d advocate using this. It is an obscure trick of the PowerShell parser and as such might fail my “3:00 in the Morning Test” (if woken at 3:00, could you figure this out before a cup of coffee?). But is pretty cool. Yet another example of how awesome the PowerShell parser is!