How to use the PowerShell Script Analyzer to Clean Up Your Code
How to use the PowerShell Script Analyzer to Clean Up Your Code
In this video, PowerShell instructor Jason Yoder demonstrates how you can use the PowerShell Script Analyzer to help you format your code to best-practices.
For instructor-led PowerShell training classes, see our course schedule:
Download the PowerShell Analyzer scripts used in this video.
║ PowerShell Script Analyzer ║
║ Interface Technical Training ║
║ Jason A Yoder ║
# Notice that PSScriptAnalyzer is not installed.
# To find or install the PSScriptAnalyzer from the PSGallery, you need
# to install NuGET.
Install-PackageProvider –Name Nuget -Force
# Find the PSScriptAnalyzer module.
Find-Module -Name "PSScriptAnalyzer"
# Install the PSScriptAnalyzer module.
Install-Module -Name "PSScriptAnalyzer" -Force
# List the cmdlets in the PSScriptAnalyzer module.
Get-Command -Module PSScriptAnalyzer
# Show the help file.
Get-Help Get-ScriptAnalyzerRule -ShowWindow
# Show the current rules.
Get-ScriptAnalyzerRule -Severity Error
Get-ScriptAnalyzerRule -Severity Warning
Get-ScriptAnalyzerRule -Severity Information
Invoke-ScriptAnalyzer -Path C:\ps\MyScript1.ps1
Invoke-ScriptAnalyzer -Path C:\ps\MyScript2.ps1 # Corrects: PSAvoidDefaultValueForMandatoryParameter
Invoke-ScriptAnalyzer -Path C:\ps\MyScript3.ps1 # Corrects: PSAvoidUsingWMICmdlet
Invoke-ScriptAnalyzer -Path C:\ps\MyScript4.ps1 # Corrects: PSAvoidUsingWriteHost
Invoke-ScriptAnalyzer -Path C:\ps\MyScript5.ps1 # Corrects: PSUseApprovedVerbs
Invoke-ScriptAnalyzer -Path C:\ps\MyScript5.ps1 # Corrects: PSUseSingularNouns
Hi, I’m Jason Yoder with Interface Technical Training. Today, we’re going to take a look at the PowerShell Script Analyzer and how it can help you when you’re writing your PowerShell code.
I often get asked during my classes, “What are the best practices for coding?” Truth be told, it really depends on your environment. If you’re working with a bunch of other programmers, you’ll need to have some type of standard that you use so that when you read each other’s code, you can understand it better.
[00:29] In the industry, there has been some best practices developed. The PowerShell Script Analyzer’s going to help you match your code against those best practices. Let’s take a look at it.
[00:39] First of all, we’re going to notice is the PowerShell Script Analyzer is not installed on your machines by default. The question is, “Where do I get this from?” That’s easy. It’s out on the PowerShell Gallery.
[00:51] Before we can download any content from the PowerShell Gallery, you need to install a package provider called NuGet. I’m going to go ahead and do this. I’m using the ‑Force parameter, so we don’t get a confirmation window popping up.
[01:04] All right, it’s installed, and now we can start using the PowerShell Gallery. I’m going to search the gallery for a module called PSScriptAnalyzer. Now, again, this is going to be the actual PowerShell Script Analyzer that we’re going to download and place into our machine. There it is. I’m going to go ahead and install this module from the PowerShell Gallery. Again, I’m using the ‑Force parameter so we don’t receive a confirmation box.
[01:28] All right, now that our module’s been installed, let’s take a look at some of the Cmdlets that are available to us. We have three Cmdlets.
[01:39] The first one we’re going to take a look at is Get‑ScriptAnalyzerRule. Now Get‑ScriptAnalyzerRule is going to take our scripts and compare them with 51 rules that are already defined in the system to see if we’re following some best practices in the industry.
[01:56] We can also take a look at these rules manually, if you run Get‑ScriptAnalyzerRule all by itself. It’s going to show you all the rules, but we can also filter based on severity of the rules or warning and information. What we’re going to do is we’re going to run this against a script that I’ve already created called GatherMyDataSets. Let’s run through the code real quick and see what we’re going to be working with.
[02:19] First of all, we have a mandatory parameter called Computer Name. I’ve already assigned it a default value of dc1. dc1 is a valid computer in our network.
[02:30] Next, we’re going to be using Write‑Host to display on the screen where we’re getting our information from. Then, finally, we’re going to use Get‑WMiObject to grab the information from the operating system. When you run this code, you can see it does work.
[02:45] Let’s go ahead and invoke this PowerShell Script Analyzer. The path is going to be where I’ve saved my code. You can see we have a list of issues that have come up.
[02:57] First of all, we have a warning, “Use singular nouns.” The description on it, the Cmdlet gathers my data sets, uses a plural noun. Now, if you know anything about how PowerShell’s naming syntax is supposed to go, it’s verb‑singular noun.
[03:15] What we’re going to do is we’re going to make a change. If you take a look at this second script, we’re going to go ahead and remove, there it is, the S. Now, let’s go ahead and save this code. What I’m going to do next is run that code. We still have all the errors, but we’re not seeing the one about having a plural noun component of our name, so that one’s been fixed.
[03:45] The next one we’re seeing here, “Avoid using WMI cmdlet.” See the file myScript.psi uses WMI Cmdlet for PowerShell 3.0and above. They want us to use the new CIM Cmdlets. We need to fix this.
[04:00] In this next script…we’re going to take away original error there. You’ll see in the next script I’ve replaced Get‑WMiObject with Get‑CimInstance. Now this is the Cmdlet that Microsoft wants us to use moving forward.
[04:15] If you’re still working in an environment where you have PowerShell 2.0deployed, Get‑WMiObject is still available to you, but it’s no longer going to be carried forward. You want to take a look at upgrading those versions of PowerShell, not just so you can maintain compatibility, but also for security reasons.
[04:33] Let’s go ahead and run the script analyzer against this set of code. All right, another error message has disappeared. Let’s take a look at the next one, “Avoid using Write‑Host.”
[04:45] If we take a look at my code, we’re using Write‑Host. Write‑Host skips all the pipelines and goes directly to the screen. We can’t suppress Write‑Host. Whenever you have code that’s projecting anything to the screen, it actually slows down execution. Also, because it’s non‑suppressible, it’s considered a poor practice.
[05:05] What we’re going to do is we’re going to change that Cmdlet to Write‑Verbose, which is one of the Cmdlets that was recommended for us to change it to. Now that we have Write‑Verbose, let’s go ahead and run the script analyzer against this code.
[05:21] All right, that’s one taken care of. It looks like I left an S up here, we have a warning about that. We also have another warning about using approved verbs.
[05:34] If you take a look, I’m using a verb called Gather. If you run the PowerShell Cmdlet, Get‑Verb, this will show you a list of all the approved verbs for Windows PowerShell.
[05:43] Now you can still use your own. The problem is is that part of the discoverability of the Cmdlets involve the verbs, and also the verbs tell us what action’s about to be taken on this particular object or functionality, what have you. If you start using your own verbs, then you’re going to add confusion and make it hard for people to use your code. What we’re going to do is we’re going to switch things over. You can see I’m now using the Cmdlet GetMyDataSet as opposed to Gather.
[06:13] Now when we run this one, I can see that everything has been fixed. That’s how you use the PowerShell Script Analyzer. You run it against your scripts, read what the description tells you to do. Now remember that this may not always apply to you. There is going to be situations where you may write code that has to be done this way. You can always use the Invoke‑ScriptAnalyzer’s parameters to remove rules so you don’t get flagged when they run.
[06:41] I hope this helps you write some better code. It is definitely going to help you keep it conformed to industry standards.
You May Also Like
In this SharePoint training video, I want to talk about the Navigation Controls in SharePoint. They tend to fall into two kind of different categories; one with the navigation controls in a typical Collaboration Site such as a Team Site or a Project Site. These are Sites that are based on the Team Site Template … Continue reading Using Navigation Controls in a Collaboration Site in SharePoint
In this recorded Windows 10 training webinar from December 2, 2015, Windows Server instructor Rick Trader presents the deployment and management of Windows 10 Enterprise and the new Provisioning capability in Windows 10. Learn how to manage Windows 10 deployments using System Center Configuration Manager, Mobile Device Management and Intune. Also included in his presentation … Continue reading Windows 10 Managing, Deploying and Configuring – December 2, 2015
How does an investigator hunt down and identify unknown malware? In this recording of our IT Security training webinar on April 21, 2015, Security expert Mike Danseglio (CISSP / CEH) performed several malware investigations on infected computers and identify symptoms, find root cause, and follow the leads to determine what’s happening. He demonstrated his preferred … Continue reading Detailed Forensic Investigation of Malware Infections – April 21, 2015