Best practices for PowerShell scripts

I. Introduction

This chapter summarizes all the best practices for writing PowerShell scripts, bringing this module on PowerShell scripting to a close and serving as a summary.

II. Summary of PowerShell best practices

Here's a set of best practices and recommendations that I wanted to highlight as part of this course. It's important to follow certain best practices to ensure the clarity, readability, consistency and maintainability of your scripts.

  • See PowerShell help

When writing a PowerShell script, take the time to consult the help for each cmdlet you use, so that you fully understand how it works, what the parameters are for, etc... With practice and the reuse of certain cmdlets, you will of course become more efficient.

Above all, this will enable you to prioritize the use of cmdlets native to PowerShell, rather than potentially seeking to rewrite code that performs an action already covered by a cmdlet.

  • Naming your scripts, functions and variables

The names of scripts, functions and variables must be both clear and descriptive. For script and function names, you must follow the Microsoft rules, i.e. use an approved verb and an approved noun.

When it comes to variables (which will be covered in the next module), you have more freedom, but the name of each variable must be meaningful. This will make it easier to find your way around when you have a multitude of variables in the same script. If the variable is called "UserName", we can assume that it's used to store a user's name, whereas if the same variable is simply called "u" or "user", it's less explicit.

  • Using comments

A good script is a well-documented script. Comments allow you to describe the purpose of your script and each block of code. They help others (and yourself, in the future) to quickly understand what your code does. As a reminder, to add a comment in PowerShell, use the hash character (#) and all the text that follows (on the same line) will be integrated into the comment. Integrating comment-based help is also a good practice.

  • Indicate your code

Code indentation improves the formatting of your PowerShell code, making it easier to read. As we saw earlier, in PowerShell, indentation is generally done with tabs, or possibly with spaces.

  • Aerate your code

In addition to comments and indentation, you can also break up your code by adding line breaks and spaces. For example, when declaring a variable, write :

$MaVariable = "MyValue"

Instead of this:

$MaVariable="MyValue"

What changes? The presence of a space after the variable name (and therefore before the "=" sign) and before the value to be assigned to the variable. In this way, each "part" of the line is easily identifiable.

  • Use autocomplete

Autocompletion is an excellent way of reducing typing errors and saving time when writing PowerShell code. With PowerShell, autocomplete gives you the benefit of suggestions when entering cmdlet names, parameter names or when calling a variable.

  • Using functions

Functions are reusable blocks of code that perform a specific task. By grouping your code into functions, you can reduce duplication and improve the readability of your script. Be careful not to create a function that performs a task already performed by an embedded PowerShell cmdlet.

  • Managing errors

PowerShell offers several mechanisms for handling errors. With these, you can ensure that your script behaves correctly in the event of an error, and provide useful information for troubleshooting. This can also help you take action in the event of an error:"If the previous command returns an error, what do we do?". In a later chapter, we'll take a closer look at this topic, using Try-Catch-Finally.

  • Do not use aliases

When using a PowerShell cmdlet, use its full name. In other words, avoid using aliases as we suggested in the chapter on aliases, and this is also a rule built into the PSScriptAnalyzer module.

  • Limit line length

Some lines of code can be very long, especially if we're using a cmdlet with a large number of parameters, or if we're using the pipeline to string together several commands or filter the result of an initial command. In some cases, this involves scrolling horizontally (to the right and then to the left) to navigate through the script. This is detrimental to the readability of a script, as some of the code may be invisible on screen (depending on resolution, screen size, etc.).

By default, the PowerShell console has a width of 120 characters, but we also need to think about the fact that scripts can be shared on other platforms such as GitHub. For this reason, we recommend limiting the length of a line to 115 characters to ensure readability on as many devices and platforms as possible.

You can break down a line into several lines using the inverted apostrophe. Let's take an example:

Get-Service | Where-Object { $_.Status -eq "Running" } | Select-Object DisplayName, Status | Out-GridView

We could mark a breaking point with the "`" character (on key 7 of an AZERTY keyboard) and write this:

Get-Service | Where-Object { $_.Status -eq "Running" } `
            | Select-Object DisplayName, Status | Out-GridView

And, if need be, we could even go further and chain this character together several times:

Get-Service | Where-Object { $_.Status -eq "Running" } `
            | Select-Object DisplayName, Status `
            | Out-GridView

In this way, we can maintain good readability when the command is too long. In this case, you need to be careful with indentation, and also not to add the "`" character when you reach the end of the command.

  • Write one command per line

You probably don't know it, but you can write several commands on the same line, separated by a semicolon (";"). Although this is possible, it's bad practice, as it will affect the readability of your code. Get into the habit of writing one command per line, except when you're using the pipeline and the command isn't too long (previous recommendation).

To illustrate this recommendation, here's an example in which three commands are written on the same line and separated by a semicolon. This piece of code is correct and will be executed by PowerShell. However, it is not easy to read.

Write-Output "Début du script - Voici la liste des utilisateurs locaux" ; Get-LocalUser ; Write-Output "Fin du script"

In this case, it is preferable to use this syntax :

Write-Output "Début du script - Voici la liste des utilisateurs locaux"
Get-LocalUser
Write-Output "Fin du script"

At runtime, the result will be identical, but the piece of code is easier to read and understand. This is an important detail. I'd also like to point out that it'snot necessary to add a semicolon at the end of a line to mark the end of the command; a line break is sufficient.

III. Conclusion

By following these best practices, your scripts will be easier to read, understand and maintain. In other words, your scripts will be improved by following these few basic rules.


book to learn PowerShell