未加星标

PSScriptAnalyzer deep dive Part 4 of 4

字体大小 | |
[系统(windows) 所属分类 系统(windows) | 发布者 店小二05 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

Summary: Thomas Rayner, Microsoft Cloud and Datacenter Management MVP, shows how to write a custom PSScriptAnalyzer rule.

Hello! I’m Thomas Rayner, a Cloud and Datacenter Management Microsoft MVP, filling in for The Scripting Guy this week. You can find me on Twitter ( @MrThomasRayner ), or posting on my blog, workingsysadmin.com . This week, I’m presenting a four-part series about how touse PSScriptAnalyzer.

Part 1 Getting started with PSScriptAnalyzer

Part 2 Suppressing, including, excluding rules

Part 3 Wrapping PSScriptAnalyzer with Pester to get formatted results

Part 4 Writing custom rules

This is Part 4, so let’s look at how to write your own custom PSScriptAnalyzer rules.

At this time, PSScriptAnalyzer comes with a total of 45 rules that are based on community best practices. PowerShell team members at Microsoft and the community developed these rules. The built-in rules are a great baseline, and a good starting point that will quickly tell you if a script or module has any glaring flaws before you get too deep into it. That’s great, but what if you or your team has some more stringent standards, or you want to borrow the PSSA engine to check scripts for some other reason? You’ll need a custom rule.

Before we go further, here’s the script that I’m going to be testing today, saved as MyScript.ps1. It’s pretty useless because I’m just trying to highlight some PSSA functionality.

function Get-Something {

param ( [string]$Words

)

Write-Host "You said $Words"

}

function Get-MYVar {

param ( [string]$VariableName

)

$results = $null

Get-Variable -Name $VariableName

}

Like with most of my other pieces of example code in this series, and especially if you’ve been following the rest of this series, you should already see some things that are going to trigger some PSSA rule violations.


PSScriptAnalyzer deep dive   Part 4 of 4

I’m declaring a variable that I never actually use, and I’m using Write-Host . Both actions are violations of standard PSSA rules.

Maybe there are more issues with my script, though. Perhaps in my organization, it is against my style and standards guidelines to have a function that has adjacent capital letters. Instead of having Get-MYVar , I should have Get-MyVar . Plenty of people support this rule because it increases readability. Instead of something like Get-AzureRMVM , you can have Get-AzureRmVm , which is more readable.

PSSA didn’t tell me about my function whose name has adjacent capital letters, though. I know that I can use the regex pattern ‘[A-Z]{2,}’ to detect two capital letters in a row, but how do I write a PSSA rule?

To write custom PSScriptAnalyzer rules, you’ll need at least basic knowledge of the PowerShell abstract syntax tree. The PowerShell abstract syntax tree is a tree-style representation of the code that makes up whatever you’ve written. Tools that are built into .NET and PowerShell parse files for examination by tools like, but not limited to, PSSA. Doing a deep dive on the abstract syntax tree could be its own five-part series. If that’s something you’d like to see, contact me by using my information at the beginning of this post. If the demand is there, I will put one together. For now, I’m just going to recommend that you do a little independent learning if what you see in this post is too far over your head. The abstract syntax tree is a bit of an abstract concept (pun intended) to get into, but a few really good blog posts and info pages are out there already.

So, let’s get into it. PSSA custom rules are just PowerShell functions. I’m going to make a new file named MyRule.psm1 and start to build my function. Note that the file needs to be a .psm1. Otherwise, it won’t work properly.

function Test-FunctionCasing {

[CmdletBinding()] [OutputType([PSCustomObject[]])] param ( [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [System.Management.Automation.Language.ScriptBlockAst]$ScriptBlockAst

)

}

My custom rule is going to be named Test-FunctionCasing . Custom PSSA rules output PSCustomObject objects and take some form of abstract syntax tree object as input. For this scenario, I want to use the ScriptBlockAst objects in my script because that’s the part of the tree that will give me what I need to check function names.

Note: I’ve started a module, called AstHelper, that’s geared towards helping people discover and use the abstract syntax tree. It’s available on the PowerShell Gallery ( Find-Module AstHelper ), and if you’d like to contribute, the source is on GitHub ( https://github.com/ThmsRynr/AstHelper ). At this time, it’s very much in it’s infancy, but I still use it to discover what types of abstract syntax tree objects are in PowerShell scripts and modules, and what kind of objects are in there that are of “AST type ___”. Jason Shirk also built a cool module for exploring abstract syntax tree ( https://github.com/lzybkr/ShowPSAst ).

Back to our custom rule. I’m going to add a process block next.

process {

try {

$functions = $ScriptBlockAst.FindAll( { $args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $args[0].Name -cmatch '[A-Z]{2,}' }, $true )

}

catch {

$PSCmdlet.ThrowTerminatingError( $_ )

}

}

Here, I’m getting all the functions that have a name that matches my regex pattern of “two adjacent capital letters”. I’ve wrapped this in a try / catch , just in case. The .FindAll() syntax is somewhat robust, and it can be daunting if you are not familiar with it. Microsoft has it well documented at Ast.FindAll Method (Func<Ast, Boolean>, Boolean) .

Now, I just need a foreach loop to go through all the functions that matched the pattern and report them to PSSA.

foreach ( $function in $functions ) {

[PSCustomObject]@{ Message = "Avoid function names with adjacent caps in their name" Extent = $function.Extent RuleName = $PSCmdlet.MyInvocation.InvocationName Severity = "Warning" }

}

All I need to do is specify a message, an extent (built in to the result stored in $function ), the rule name that it violated (which is the name of the PowerShell function I’m building), and severity.

My entire, assembled rule looks like this.

function Test-FunctionCasing {

[CmdletBinding()] [OutputType([PSCustomObject[]])] param ( [Parameter(Mandatory)] [ValidateNot

本文系统(windows)相关术语:三级网络技术 计算机三级网络技术 网络技术基础 计算机网络技术

主题: PowerShellGitGitHubWordTwitter
分页:12
转载请注明
本文标题:PSScriptAnalyzer deep dive Part 4 of 4
本站链接:http://www.codesec.net/view/532006.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 系统(windows) | 评论(0) | 阅读(53)