When we check PowerShell scripts in to our Git repository, one of the things that happens automatically is that the Visual Studio Team Services build agent kicks off the PowerShell Script Analyzer to check the code.
This is a module that the PowerShell team at Microsoft have create to help check for best practices in writing PowerShell. Some of the things that it picks up on are just good things to do for readability of scripts, like not using aliases, but others are more obscure, like having $null on the left side of a comparison operator when you want to see if a variable is null – there’s a good reason for that – just trust it. 😉
This means that scripts that don’t comply with the rules don’t get to be automatically deployed into production, which is a good thing, but it also can block someone else’s working code from getting released. That being the case, it might be worth checking your PowerShell before checking it in. Fortunately that’s only going to add seconds on to the process, and it’s quicker than waiting for the results from the build agent.
There are two basic ways to install Script Analyzer. If you install as an Administrator, it’s going to get the best coverage for use on that specific machine, or if you install it for the current user, it’s going to install in your home directory and follow you round to other machines.
Running PowerShell as an Administrator, type:
Or, running with your normal user account, type:
install-module psscriptanalyzer -scope CurrentUser
PowerShell is going to pop up a warning, saying:
You are installing the modules from an untrusted repository. If you trust this repository, change its Installation Policy value by running the Set-PSRepository cmdlet. Are you sure you want to install the modules from ‘PSGallery’?
We aren’t going to worry about changing the trust, we just need to say ‘Yes’ to this and the module will be installed. (Always be very careful about doing this with any other modules!!)
Now that it’s installed, to check your script once you’ve saved it, you just need to run:
If it’s all good, you’ll see nothing in return (you can always stick a -verbose on the end to see what it’s actually checking as it does it), or you’ll get some feedback about which rules have been broken, which lines they are on, and some guidance on how to get into compliance, like this:
(click on the image to see it full size)
If it’s not clear enough from the feedback, a quick web search for the RuleName should give you plenty to go on.
If you want to know more about Script Analyzer and how it works, it’s all open source on the PowerShell Team’s GitHub repository.