PSScriptAnalyzer

Also included in the PowerShell extension for VSCode is the PSScriptAnalyzer module. It comes preloaded, and the static code analysis is triggered automatically for any piece of PowerShell code you are working on. We already covered the command-line use of PSScriptAnalyzer in Chapter 5, Writing Reusable Code.

PSScriptAnalyzer can be used very comfortably from within VSCode. A couple of rules are enabled by default, and by bringing up the command palette, you can select all of the rules you want to be applied:


This especially makes sense if you want to apply some enterprise-wide code policies that can be checked with the script analyzer. Any issues will be flagged in the Problems tab, and some of those issues, such as the use of Aliases, can be corrected automatically. This makes it easy even for inexperienced PowerShell developers to find and fix issues:

Once you have selected a set of rules, you can try them in the following code sample. You can either edit the code sample in VSCode, which will immediately test against all selected rules. Or you can save the script file and use the cmdlet Invoke-ScriptAnalyzer on it to get a report of all violations.

# Code flagged by additional rules

# You should use the CIM cmdlets!
# PSAvoidUsingWMICmdlet
Get-WmiObject Win32_Process

# Don't leak passwords!
# PSAvoidUsingConvertToSecureStringWithPlainText)
$Credential = New-Object pscredential('user',('ClearTextPassword' | ConvertTo-SecureString -AsPlainText -Force))

# Use proper function names
# PSUseSingularNouns
function Get-SomeObjects
{

}

# Don't catch errors just to ignore them
# PSAvoidUsingEmptyCatchBlock
try
{
Get-Item C:DoesNotCompute -ErrorAction Stop
}
catch
{ }

In  order to distribute a standard set of PSSA settings, you can also define the code analysis rules to use in a template for a workspace, or for all of your users. Simply hit Ctrl +, (macOS: Command key +,) to bring up the settings and select the script analyzer settings. The settings file needs to point to an existing psd1 file with the desired settings configured:

The settings file that you reference in the VSCode settings section can look like the following code sample. The hashtable key IncludeRules specifies which rules should be checked in your workspace, and is a simple array of strings. In case you have selected rules with the IncludeRules key, the default rules will not be used any longer. You could also use ExcludeRules to exclude certain default rules from being checked.

@{
IncludeRules = @('PSAvoidDefaultValueSwitchParameter',
'PSMisleadingBacktick',
'PSMissingModuleManifestField',
'PSReservedCmdletChar',
'PSReservedParams',
'PSShouldProcess',
'PSUseApprovedVerbs',
'PSAvoidUsingCmdletAliases',
'PSUseDeclaredVarsMoreThanAssignments')
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.19.27.178