Saturday 25 June 2016

Hidden Formatting in PowerShell

Recently I was working on a PowerShell project and faced a challenge which I came to know as very important to share when I got the solution.

ITS NOT A GOTCHA !!!

Lets start with the same cmdlet I used,


I used the above cmdlet and got the output as expected,










My intention was to get IPv4 DNS Addresses only , So I tried to filter with 'Address Family' and the output was null, nothing !!!



I thought of investigation it and tried Select-Object on AddressFamily property and I got bellow output which is really unexpected.






So there is some formatting happening behind the scene. Lets explore it ...

First we need to know in which module this cmdlet is in to explore the module specific formatting file.
As usual , Get-Command -Name Get-DnsClientServerAddress | Select-Object -Property module

I got to know that this cmdlet belongs to 'DnsClient' module, so next we have to go to the module folder for further investigation.
Lets open the module folder with a one liner.

Get-Module -Name (Get-Command -Name Get-DnsClientServerAddress | Select-Object -ExpandProperty module) | Select-Object -Property path | Split-Path -Parent | Invoke-Item














Here we got the Module specific formatting file for DnsClient module, now we need the type of object generated by Get-DnsClientServerAddress cmdlet.


As usual using Get-Member

Get-DnsClientServerAddress | Get-Member


Lets open the formatting file and search how they configured formatting for this type of objects.


Here we got how the formatting is done for this cmdlet. you can see here for the Property AddressFamily there is a respective script block which outputs 'IPv4' and 'IPv6' based on the actual value for AddressFamily.

Similar formatting is done for many other PowerShell cmdlets like Get-Process, Get-ChildItem etc.


Have Fun Exploring PowerShell