Scripting Games 2012 Tip: Variable Names That Make Sense

This is something that I am going to do from now until the start of the Scripting Games. Basically I am going to discuss some areas to watch out for when writing scripts for the upcoming games. These are intended to be a short example and not a drawn out thing. I want to also add that these are my own opinions and do not reflect the opinions of the other judges.

Variables

One thing that I have seen during the games and also in everyday scripting are the wide use of variable names. When using variables in PowerShell, it is best to keep it to something that makes so the people reading the scripts know exactly what it is you are using the variable for. Take this example:

$Computername = 'server1','server2'
ForEach ($Computer in $Computername) {$Computer}

We know exactly what is in this variable and do not have to read back up the code to try and determine what might be in it.

Something like this would lead into confusion to figure out what it means.

$Servers = 'server1','server2'
ForEach ($C in $Servers) {$c}

Not a lot of consistency here and worse than that, we need to figure out what exactly $c is.

Another example:

$p = Get-WMIObject Win32_Process
$dt = Get-Date

There are no prizes for the shortest variable name. Take the extra time to write it out so it is more readable.

$processes = Get-WmiObject Win32_Process
$Date = Get-Date

Keep the variables to something that is clear and concise with what they are meant to be used for.

Hungarian notation

Gone are the days where you need to name a variable by its type.

$strComputer=  'server'
$arrComputer = 'server','server1','server2'
$collWmi = Get-WmiObject Win32_Processor

Its just not as important as it used to be in tracking the type of object in a variable. Clarity is the important thing, especially when the code can get long where the person reading the code would just prefer to know what it is being used for rather then knowing what type of object it is.

 

Remember, clarity in variable names are important to your script and also to the person who comes in after you to read your script!

About Boe Prox

Microsoft Cloud and Datacenter MVP working as a SQL DBA.
This entry was posted in Scripting Games 2012 and tagged , . Bookmark the permalink.

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