PowerShell script best practices

I would like to share some ideas that I believe is best practices in PowerShell development

Script prefixing

In the beginning of all my scripts I add

#requires -version 2.0

[CmdletBinding()]
param
(
)

$script:ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest
$PSScriptRoot = $MyInvocation.MyCommand.Path | Split-Path

Line 1 – enforcing PowerShell version

Line 3 – Automatically implement the standard -Verbose, -Debug, -ErrorAction, -ErrorVariable, -Confirm, and -? arguments for you and maybe some other minor stuff.

Line 8 – Enforces all errors to become terminating unless you override with per-command -ErrorAction parameters or wrap in a try-catch block
script: prefix is used to fix some known issue with PSv3CTP2 ISE bug

Line 9 – Ensures you only refer to variables that exist (great for typos) and enforces some other “best-practice” coding rules.

Line 10 – This gets the absolute path of the folder containing the script that is running. This is useful when referring to other files relative to the script without relying on the current working directory. The variable name is chosen as such because this is the name of the variable PowerShell gives you for free when you write a module thereby making future refactoring to a module easier.
Also I would like to mention that this variable became automatically set in PowerShell 3 for ps1 scripts, so Line 10 is not be needed if you are targetting PowerShell 3 only.

Most of these descriptions were stolen word-by-word from Jason Stangroome (http://blog.codeassassin.com/)

Readability

I think readability of the scripts is very important.
So

  • Always use proper indents in your script files
  • Never use aliases, use vanilla cmdlets instead.
    Bad: dir
    Good: Get-ChildItem
  • Always use full property names rather than shorthands
    Bad: Get-ChildItem -ea 0
    Good: Get-ChildItem -ErrorAction SilentlyContinue

See here also

Advertisements

About mnaoumov

Senior .NET Developer in Readify
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

3 Responses to PowerShell script best practices

  1. Pingback: PowerShell $PSScriptRoot vs dot-sourcing | mnaoumov.NET

  2. I disagree with not using well known aliases. There is readability in terseness. I would recommend against using the unix aliases (ls, rm, etc) in favor of the windows one (dir, del, etc).

  3. Pingback: Set-StrictMode and legacy code issues | mnaoumov.NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s