Splatting in PowerShell
2017-MAY-02

While changing all scripts that touches Active Directory from using Quest ActiveDirectory module to the built in ActiveDirectory module I discovered Splatting. Apparently this has been around since PowerShell v2, so perhaps other PowerShell users aren't aware that this exists, like me.

This technique allows a code like this:

Get-ADUser -Filter * -Properties * | Select-Object 'Name',
 @{Name = "Username"; Expression = {$_.SamAccountName}}, @{Name = "Title"; Expression = {$_.Title}}, @{Name = "Title (FR)"; Expression = {$_.ExtensionAttribute1}}, @{Name = "Department "; Expression = {$_.Department}}, @{Name = "Department (FR)"; Expression = {$_.ExtensionAttribute2}}, @{Name = "Accreditation"; Expression = {$_.ExtensionAttribute3}}

to something that's more readable like this:

$Properties = @{
   Property = 'Name',
   @{Name = "Username"; Expression = {$_.SamAccountName}},
   @{Name = "Title"; Expression = {$_.Title}},
   @{Name = "Title (FR)"; Expression = {$_.ExtensionAttribute1}},
   @{Name = "Department "; Expression = {$_.Department}},
   @{Name = "Department (FR)"; Expression = {$_.ExtensionAttribute2}},
   @{Name = "Accreditation"; Expression = {$_.ExtensionAttribute3}}
   }
Get-ADUser -Filter * -Properties * | Select-Object @Properties

It makes it super easy to take a look at what I'm trying to do here, and the best part is that it makes it so easy to edit. Give it a try in your own script.