<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=1678611822423757&amp;ev=PageView&amp;noscript=1">
Defrag This

| Read. Reflect. Reboot.

Don’t Assume Anything in Code (PowerShell Coding Best Practices)

Adam Bertram| December 05 2017

| IT insights

Don’t ever assume that code is obvious. Write your PowerShell code like you're writing it for your grandma.

Whenever a scripter is first starting out writing PowerShell scripts, there’s always a tendency to assume a lot. The scripter probably doesn’t realize they’re assuming things and it’s no fault of theirs. They simply don’t know what they don’t know yet. As you progress down your PowerShell journey, you’ll soon realize that as a newbie, you were assuming a lot of things. As a result, the code you wrote then may have been run by other less-experienced people, and it’s blown up. Users will run your scripts in ways you can never imagine. Even if that user is you, today’s you is totally different than 2-years-ago-you. At the time, some aspect of the script seems obvious but now you’re left wondering what in the world you were thinking.

Related: Working With Windows Services In PowerShell

We’re here to protect ourselves from 2-years-ago-you as much as possible so let’s write PowerShell scripts the right way the first time by not assuming anything.

What do I mean by “assuming” anyway? I’ll answer this with a code example. Let’s say you’ve got a piece of code that reads the contents of a folder. You’ve been practicing up your PowerShell and create this script using a Path parameter.

param(
    $Path
)

Get-ChildItem -Path $Path
## do more stuff here.

At the time of testing, you’ve got a test folder created called C:\Folder and you’ve got a command in your PowerShell console history that looks like this:

& C:\Get-FilesAndDoStuff.ps1 -Path C:\Folder

Everything works great! You perform your testing and think everything is good to go but wait! Do you realize you’ve assumed a lot of things here? You’re assuming that:

  • This script will always be used with only C:\Folder
  • That the user will automatically know to use the Path parameter
  • That the folder Path points to will always be there
  • That the user will use Path to pass an actual string folder path into

Don’t assume! Restrict. Restrict input and use cases as tightly as possible. Think about all of the different ways this script could be run. Give it to someone else and see how they interact with it. Granted, this is a simple example, but the practice is the same. You must account for every variable imaginable to build great code.

dont-assume-anything-in-code-powershell-best-coding-practices.jpgLet’s remove each of these assumptions one a time. First, and the easiest is to simply remember to test with multiple different folders. Next, we can eliminate the other three assumptions by restricting the type of parameter passed and by using some parameter validation attributes. Defining a type and adding parameter validation is a must for every parameter you build.

param(
    [Parameter(Mandatory)]
    [ValidateScript({ Test-Path -Path $_ -PathType Container })]
    [ValidatePattern('^\w:')]
    [string]$Path
)

Get-ChildItem -Path $Path
## do more stuff here.

The Path parameter has now been transformed into something much better. By using the Mandatory attribute, we will ensure that the Path variable is always used. By using the [string] type, we can always ensure that Path will always be a string value. By using the ValidateScript parameter validation attribute the script now first checks to see if the argument is indeed a folder and I’ve even taken it a step further, and by using the ValidatePattern attribute I’m forcing the Path argument to be a local path; UNC paths are not allowed.

Dependence on legacy file transfer systems is a critical mistake IT teams make.  Read this whitepaper to learn how to fix this. 

I’ve added safeguards in this script. I’ve limited the usage scenarios down to exactly what I expect and am leaving nothing to chance. You can be sure that when this script is run in the future, it will be run as expected because it’s forcing the user to comply.

Don’t ever assume that code is obvious. Write your PowerShell code like you're writing it for your grandma. Make it simple, intuitive and only be able to run the way you expect it to.

Topics: IT insights

Leave a Reply

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

THIS POST WAS WRITTEN BY Adam Bertram

Adam Bertram is a 20-year veteran of IT. He’s currently an automation engineer, blogger, independent consultant, freelance writer, author, and trainer. Adam focuses on DevOps, system management, and automation technologies as well as various cloud platforms. He is a Microsoft Cloud and Datacenter Management MVP and efficiency nerd that enjoys teaching others a better way to leverage automation.

Free Trials

Getting started has never been easier. Download a trial today.

Download Free Trials

Contact Us

Let us know how we can help you. Focus on what matters. 

Send us a note

Subscribe to our Blog

Let’s stay in touch! Register to receive our blog updates.