Indenting your code : why and how ?

I. Introduction

Code indentation is a good practice for formatting source code in a script or program, with the aim of making it more readable. This is recommended for all scripting and programming languages, including PowerShell.

In this chapter, we'll look at several good reasons for indenting your code, and then see how to do it using your code editor, whether Windows PowerShell ISE or Visual Studio Code.

II. Why indent your code?

Here are several arguments in favor of indenting code within a PowerShell script. The principle of indenting code does not apply to the context of command-line administration.

  • Readability: indentation helps to visually distinguish blocks of code, such as loops and conditional structures. This makes the code easier to read and understand.
  • Debugging: well-indented code can help to spot errors more easily, thanks to the fact that the code seems more airy, better organized. For example, if a brace is not correctly aligned, this may indicate that a corresponding brace is missing elsewhere in the code.
  • Maintenance: well-organized and structured code is easier to maintain. If you need to edit your script in several weeks or months, or if someone else needs to work on your code (a colleague, a contributor, etc.), it will be easier to pick up where you left off if the code is well indented.

Now let's see how you can indent your code.

III. How to indent your code

In PowerShell, indentation is generally done with tabs, or possibly with spaces. There are no strict rules, but the important thing is to remain consistent throughout your code. Tabs are more practical, as the associated key on the keyboard allows you to create a large "space" with a single press.

Here's an example of a few lines in PowerShell, with or without indentation, to illustrate the benefits of indentation:

Indenting PowerShell code

In this example, each indentation level is offset by one tab. The definition of the Foreach loop, the Get-ADGroupMember command and its Foreach-Object loop, then the commands integrated into this second loop, are all clearly distinguishable thanks to indentation.

Ultimately, the important thing is to choose an indentation method that works for you and stick to it (including the choice between tab and space). Personally, I find tabbing more effective. The important thing is to adopt indentation to ensure that your code is easy to read and maintain, even if it means complying with other best practices.


book to learn PowerShell