Provisior Tech Blog

Self-service by default

Single post

The power of splatting in PowerShell

While working on a PowerShell script to add users in Azure AD recently, I walked into a situation you will sometimes have as a PowerShell scripter. You need to call some command, but given the input the parameters to supply differs. You could write a couple of “if this-input then this-call-with-these-params” statements, but this would certainly not be labeled as “clean code”.

Splatting is a perfect solution for this! If you don’t know what splatting is, you can read all about it here. In short:

Splatting is a method of passing a collection of parameter values to a command as unit.

If you look at the “New-AzureADUser” command, you can see it has a pretty long list of parameters. It really depends on the input what to pass as parameters. Do we need to set the user’s mobile phone number or address? By setting up a hashtable of parameters to pass, you can easily leave out cetain parameters based on input.

#Set up the parameters that will be passed all the time
$parameters = @{
    GivenName = $firstName 
    Surname = $lastName
    DisplayName = $displayName
    PasswordProfile = $PasswordProfile
    UserPrincipalName = "$($userid)@mycompany.com"
    AccountEnabled = $true
    Department = $departmentName
    CompanyName = "My company" 
    Country = "NL"
}

#Add additional parameters if needed
if (![string]::IsNullOrEmpty($jobTitle)) {
    $parameters.Add("JobTitle", $jobTitle)
}
if (![string]::IsNullOrEmpty($street)) {
    $parameters.Add("StreetAddress", "$street $houseNo".Trim())
}
if (![string]::IsNullOrEmpty($postalCode)) {
    $parameters.Add("PostalCode", $postalCode)
}
#etc.

In this example I first create a hash table with the parameters I’d like to add in any case and afterwards I add additional parameters where needed. Last thing to do is passing the hash table to the command like this (Note the @ instead of $):

$newUser = New-AzureADUser @parameters

A positive side effect is that the code is much easier to read than providing a long list of parameters to a command, often divided over multiple lines.

Write a Comment

Your email address will not be published. Required fields are marked *