Powershell Best Practice #9: Use custom folding regions

By | May 22, 2015

Best Practice: It is recommended to use region statement to split your code into logical parts in your scripts.

regions expand and collapse powershell

 

Explanation:

Since PowerShell v3, ISE supports code folding (feature of some editors/IDEs that allows the user to hide/display some “fold” sections).

In English, the verb “fold” means:

folding

So, you can fold/unfold  by clicking the + / – sign on the left side.
Regions are used to collapse/expand custom blocks of code you define and makes the code easier to read and to navigate.

Do not use regions inside your methods as it will be a code smell (anti-pattern), you should refactor instead.
One method should be kept as small as possible doing one and one thing. Having regions inside a method would mean that the method is too long and having too many responsibilities (check the SRP from the SOLID principles).

Note that the keywords”region” and “endregion” are case sensitive (lower case required).
To expand/collapse in Powershell ISE : Control + M


previous-buttonnext-button

Leave a Reply

Your email address will not be published.