PowerShell Coding Conventions…

Been working a lot lately with PowerShell, and thought I would share my personal PowerShell Coding Conventions.

  • Develop a PowerShell formatting guide and stick with it. I’ve dealt with a lot of code that use Tabs and Spaces at the start of a line interchangeably. However, Visual Studio uses 4 spaces for a tab, and Notepad uses 8 spaces for a tab. Please stick with one or another.
  • If you have to re-format a large project, use a Pretty-Printer tool, like this.
  • If you work in a corporate environment, don’t forget the company copyright (From my days at Microsoft).
  • Use Comment Based Help System http://technet.microsoft.com/en-us/magazine/ff458353.aspx
  • Use Advanced Function Parameters and explicitly declare your variables: http://technet.microsoft.com/en-us/library/hh847743.aspx
  • Use Write-Verbose (with SupportsShouldProcess). Sometimes I’ll use Write-Verbose instead of comments.

Here is an example of some code:  Install-Check.ps1

Installation Check for Component
Returns True if service need to be installed.
Copyright Keith Garner, All rights reserved.
       [string] $Server = ".",
       [string] $ServiceName
 $FoundService = get-wmiobject -class Win32_Service -Filter "Name='$ServiceName' and State='Running'" -ComputerName $Server
 Write-Verbose "Win32_Service.$ServiceName = $FoundService"
 return ($FoundService -isnot [object])


Getting help on the new function is easy, just run:

PS C:\Kodiak\MyProvisioning> help 'C:\InstallCheck.ps1'
    Installation Check for Kodiak
    C:\InstallCheck.ps1 [-Server <String>] [-ServiceName] <String> [-WhatIf] [-Confirm] [<CommonParameters>]
   Returns True if service need to be installed.
    To see the examples, type: "get-help C:\InstallCheck _Small.ps1 -examples".
    For more information, type: "get-help C:\InstallCheck _Small.ps1 -detailed".
    For technical information, type: "get-help C:\InstallCheck _Small.ps1 -full".

<Flame On>  :^)

One thought on “PowerShell Coding Conventions…

  1. Pingback: Powershell how to embedd text files into Powershell Scripts. | Keith's Consulting Blog

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