Powershell Splatting

Powershell Splatting

Have you ever worked on a Powershell command that has grown to the point where you pass so many parameters that reading it becomes a mission? For example, if you want to create a new user in AD, you can easily require 10 parameters to perform a basic user setup. For a lot of commands, everything can fit cleanly on one line and within either the standard 80-character width of a standard prompt or the full-screen width of your favourite editor. But sometimes you will want to specify a LOT of parameters, and some of those parameter values may be lengthy in nature. The last thing you want to do is scroll sideways through your code to read and edit it. Powershell Splatting is a technique that offers a convenient way to format and send arguments to cmdlets and functions. Instead of a long list of parameters or those same parameters separated by error-prone backticks, you can leverage splatting to make your code more readable and easier to use.

Below is two examples of code with and without Powershell Splatting

Here is what this would look like on one line without splatting:

New-ADUser -Name "Supertechman" -GivenName "Super" -Surname "Techman" -DisplayName "Test User" -SamAccountName "supertechman" -UserPrincipalName "[email protected]" -AccountPassword (ConvertTo-SecureString "PassW0rd!" -AsPlainText -Force) -Enabled $true -City "Brisbane" -State "QLD" -Department "I.T" -Path "ou=Users, ou=LAB, dc=lab, dc=supertechman, dc=com"

See how this can become hard to read.

Here is what this would look like on one line with splatting:

$params = @
    Enabled = $true;
    Accountpassword = (ConvertTo-SecureString PassW0rd! -AsPlainText -Force);
    Path = "ou=Users, ou=LAB, dc=lab, dc=supertechman, dc=com";
    ChangePasswordAtLogon = $true;
    UserPrincipalName="[email protected]";
    City = 'Brisbane';

New-ADUser @params

How to Splat?

To splat a set of parameters, you first need to create a hashtable. Basically, all you are doing is creating a bunch of lines containing key/value pairs of each parameter and parameter argument.

Then, once you have the hashtable built, pass that set of parameters to the command using @<hashtable name>.

For example, you can create a hashtable called $Params and then pass that set of parameters defined in the hashtable to the New-ADUser cmdlet as shown above.

Splatting parameters to functions and cmdlets is an extremely useful technique for code readability and functionality. You will find it is easier to manipulate hashtables and add, modify and remove values.

Leave a Reply