Writing PowerShell Scripts : Tips

Hi all,

Here is a list of things that I think are good practices when writing PowerShell Scripts.
This list is not complete and should be extended with more principles.

  • Indent your code
  • Camelcase your variable name (With of without first letter capitalized)
  • Strong type your variable whenever possible
  • Use the “try catch finally” structure combined with $ErrorActionPreference = ‘Stop’
  • Comment your code !!!!
  • Use the correct “comment” template as advised by Microsoft
  • Split long Cmdlet and complex expression into multiple lines
  • Avoid short coding form if your not “live” scripting -> Think to who will come after you !!!
  • Correctly scope your variable
  • Split your code in “functions” When you have all your functions start with the script logic
  • Write Logs and never forget about the PS Transcript functionality !!!!!!
  • Generalize as much as possible your functions, a function must be generic and anything specific must be passed as parameter so you can reuse your function later for something else
  • A function do only one thing
  • Respect the correct Verb – Noun patern for any of your function
  • Do not forget that even if powershell is “powerfull” it is based on .NET so do not fear using .NET… .NET native functions are sometimes faster
  • Do with .NET what can’t be achieved natively with the Powershell Cmdlets
  • Use “Job” whenever possible
  • Use Multithreading capabilities of Powershell & .Net
  • … To be Continued…

    Leave a Reply

    Your email address will not be published. Required fields are marked *