How to use ScriptAnalyzer

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/

sa2

 

After you have downloaded and installed make sure it is available in your session

 

sa3

sa4

Now that you have the module available you need to get the Script Analyzer rules on your computer running the following cmdlet

Get-ScriptAnalyzerRule

sa5.jpg

I am running version 1.20 and there are 38 rules on this version

sa6.jpg

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.

sa7

 

There are three places that you need to pay attention because is going to give you info on the problem.

  1. 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.
  2. Line = It tells you where is the potential problem.
  3. 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

sa8

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s