Making lines of code easier to read

When helping to spread the Powershell bug, one of the questions I get often is “how can I keep the line length manageable?”.  The easiest answer is to break the line into smaller segments and span multiple lines with the back tick (`).  Using Powershell Snapins like Quest Active Roles ADManagement or vmware PowerCLI the cmdlets come with a multitude of parameters.  The parameter set makes interacting much more flexible and using a quick example you can perform commands with a simple purpose of returning information and because of the parameters you can  avoid lengthy where-object clauses.  For example;

get-qaduser | where {$_.FirstName -eq ‘John’ -and $_.LastName -contains ‘Kava*’}
can be simplified to:
get-qaduser -FirstName ‘John’ -LastName ‘Kava*’

Pretty simple, but when you start adding even more parameters (e.g SizeLimit, SearchRoot, etc…) for a more targeted request the command line can get very lengthy.  So how do we clean that up?  I came across the answer by accident.  When looking at PowerGUI editor enhancements I came across one that revealed the answer.  The answer is to create Splatted Hash Tables to formulate the parameter set.  Using the example above and adding two parameters the new method would look like:

$qaduser = @{
SizeLimit
= 0
SearchRoot
= “dc=somedomain,dc=corp”
LastName = ‘Kava*’
FirstName = ‘John’
}

get-qaduser @qaduser

As you can see all of the parameters are stored in a hast table and then passed to the cmdlet.  As long as the keys match up to the parameters we have boiled down a lengthy string to a concise and easy to read piece of code.

The PowerGUI Script Editor add-on can be found here.  This allows you to take a long piece of code (cmdlet with multiple parameters for example) and press Ctrl+L and it will assemble the splatted hash table and change the command line.  I have found a parameter like “-SizeLimit 0” does not work so well, but easy enough to correct after the add-on does the bulk of the work.

 

PowerGUI-Badge-GetToThePrompt-Pro

Advertisements

2 thoughts on “Making lines of code easier to read

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s