ScriptAnalyzer is a PowerShell tool that analyzes your code and make suggestions on how to improve your code. This is great a tool for engineers to use because they can check their code before uploading to a version control repository. It is a first step to make sure code is in compliance and you can add new rules that complies with your company coding standards.
The first thing you need to do is make sure ScriptAnalyzer is installed on your computer. You can download the package from the PowerShell Gallery https://www.powershellgallery.com/packages/PSScriptAnalyzer/
After you have downloaded and installed make sure it is available in your session
Now that you have the module available you need to get the Script Analyzer rules on your computer running the following cmdlet
I am running version 1.20 and there are 38 rules on this version
Now we are going to analyze the following script and lets see what happens. Keep in mind I made some mistakes on purpose to demonstrate a couple of rules. The script that we are going to test is the following
And when ScriptAnalyzer is run using Invoke-ScriptAnalyzer it shows the list of suggestions.
There are three places that you need to pay attention because is going to give you info on the problem.
- RuleName = This is rule name but what it is interesting the rule name tells you what is wrong. The first rule is PSAvoidGlobalvars, this self-explanatory do not use global variables.
- Line = It tells you where is the potential problem.
- Message = It gives you a description on why there is a potential problem with that line of code
Now, if I fix my code and run ScriptAnalyzer i will not get any more warnings