Skip to content

PowerShell Best Practices To Follow When Coding

It is important to follow best practices when coding in PowerShell to ensure that your codes are efficient, maintainable, and secure.


Specify The Variable Types Explicitly

🚫 Don't do this

$Var = 5

✅ Do this instead

[System.Int32]$Var = 5


Use Full Type Names Instead of Type Accelerators

🚫 Don't do this

[String]$Var = 'Hello'

✅ Do this instead

[System.String]$Var = 'Hello'


Use Single Quotes Instead of Double Quotes Unless Absolutely Necessary

🚫 Don't do this

$Var = "Hello"

✅ Do this instead

$Var = 'Hello'

This is because double quotes allow for string interpolation, which can be a security risk if the string is not sanitized properly and also slightly slower than single quotes.


Use Full Cmdlet Names Instead of Aliases

🚫 Don't do this

Gci
cls

✅ Do this instead

Get-ChildItem
Clear-Host


Use Pascal Casing for Everything

🚫 Don't do this

$myvariable
get-childitem
new-item

🚫 or this (camelCase)

$myVariable
get-ChildItem
new-Item

✅ Do this instead

$MyVariable
Get-ChildItem
New-Item


Use Regions to Organize Your Code

✅ Using regions like this allows you to collapse and expand sections of your code for better readability.

#Region Functions
function Get-MyFunction1 {
    # Function code here
}
function Get-MyFunction2 {
    # Function code here
}
function Get-MyFunction3 {
    # Function code here
}
#EndRegion


Use Visual Studio Code PowerShell Extension For Automatic Best Practice Formatting

You can access the settings page of PowerShell extension in VS Code and enable options that automatically apply some of the aforementioned best practices when you format your code with (CTRL + Shift + F) shortcut.


More Resources From Microsoft That You Should Check Out