Making PSScriptAnalyzer a first-class citizen in a PowerShell CI pipeline

As you already know if you have read this or this, I’m a big fan of PSScriptAnalyzer to maintain a certain standard of coding style and quality. Where this is especially powerful is inside a continuous integration pipeline because this allows us to enforce that coding standard.

In our CI pipeline, we can easily make the build fail if our code violates one or more PSScriptAnalyzer rule(s). That’s great, but the main point of continuous integration is to give quick feedback to developers about their code change(s). Continuous integration is about catching problems early to fix them early. So, Green/Red or Pass/Fail is OK, but providing meaningful information about a problem to help remediate it is better. And pretty darn important.

So now, the question is :

How can we make our CI tool publish PSScriptAnalyzer results with the information we need to remediate any violation ?

All CI tools have ways to publish test results to make them highly visible, to drill down into a test failure, and even do some reporting on these test results. Since we are talking about a PowerShell pipeline, we are most likely already using Pester to test our PowerShell code. Pester can spit out results in the same XML format as NUnit and these NUnit XML files can be consumed and published by most CI tools.

It makes a lot of sense to leverage this Pester integration as a universal CI glue and run our PSScriptAnalyzer checks as Pester tests. Let’s look at possible ways to do that.

One Pester test checking if the PSScriptAnalyzer result is null :

This is probably the simplest way to invoke PSScriptAnalyzer from Pester :

Describe 'PSScriptAnalyzer analysis' {
    
    $ScriptAnalyzerResults = Invoke-ScriptAnalyzer -Path ".\ExampleScript.ps1" -Severity Warning
    
    It 'Should not return any violation' {
        $ScriptAnalyzerResults | Should BeNullOrEmpty
    }
}
  

 
Here, we are checking all the rules which have a “Warning” severity within one single test. Then, we rely on the fact that if PSScriptAnalyzer returns something, it means that they were at least one violation and if PSScriptAnalyzer returns nothing, it’s all good.

There are 2 problems here :

  • We are evaluating a whole bunch of rules in a single test, so the test name cannot tell us which rule was violated
  • As soon as there are more than one violation, the Pester message gives us useless information

How useless ? Well, let’s see :

useless-pester-stacktrace
 
The Pester failure message gives us the object type of the PSScriptAnalyzer results, instead of their contents. This does not provide what we need to locate and remediate the problem, like the name of the file which violated the rule and the line number in that file where the violation is located.

One Pester test per PSScriptAnalyzer rule :

This is a pretty typical (and better) way of running PSScriptAnalyzer checks via Pester.

Describe 'PSScriptAnalyzer analysis' {
    
    $ScriptAnalyzerRules = Get-ScriptAnalyzerRule -Name "PSAvoid*"

    Foreach ( $Rule in $ScriptAnalyzerRules ) {

        It "Should not return any violation for the rule : $($Rule.RuleName)" {
            Invoke-ScriptAnalyzer -Path ".\ExampleScript.ps1" -IncludeRule $Rule.RuleName |
            Should BeNullOrEmpty
        }
    }
}
  

 
In this case, the first step is to get a list of the rules that we want to evaluate. Here, I changed the list of rules to : all rules which have a name starting with “PSAvoid”.
This is just to show that we can filter the rules by name, as well as by severity.

Then, we loop through this list of rules and have a Pester test evaluating each rule, one by one. As we can see below, the output is much more useful :

psscriptanalyzer-by-rule
 
This is definitely better but we still encounter the same issue as before because there were more than one violation for that “PSAvoidUsingWMICmdlet” rule. So we still don’t get the file name and the line number.

We could use a nested loop : for each rule, we would loop through each file and evaluate that rule against each file one-by-one. That would be more granular and reduce the risk of this particular issue. But if a single file violated the same rule more than once, we would still have the same problem.

So, I decided to go take a different direction to address this problem : taking the output from PSScriptAnalyzer and converting it to a test result file, using the same XML schema as Pester and NUnit.

Converting PSScriptAnalyzer output to a test result file :

For that purpose, I wrote a function named Export-NUnitXml, which is available on GitHub in this module.

Here are the high-level steps of what Export-NUnitXml does :

  • Take the output of PSScriptAnalyzer as its input (zero or more objects of the type [Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord]
  • Create an XML document containing a “test-case” node for each input object(s).
  • Write this XML document to the file specified via the Path parameter.

Here is an example of how we can use this within a build script (in Appveyor.com as the CI tool, in this case) :

$ScriptAnalyzerRules = Get-ScriptAnalyzerRule -Severity Warning
$ScriptAnalyzerResult = Invoke-ScriptAnalyzer -Path ".\CustomPSScriptAnalyzerRules\ExampleScript.ps1" -IncludeRule $ScriptAnalyzerRules
If ( $ScriptAnalyzerResult ) {
  
    $ScriptAnalyzerResultString = $ScriptAnalyzerResult | Out-String
    Write-Warning $ScriptAnalyzerResultString
}
Import-Module ".\Export-NUnitXml\Export-NUnitXml.psm1" -Force
Export-NUnitXml -ScriptAnalyzerResult $ScriptAnalyzerResult -Path ".\ScriptAnalyzerResult.xml"

(New-Object 'System.Net.WebClient').UploadFile("https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path .\ScriptAnalyzerResult.xml))

If ( $ScriptAnalyzerResult ) {        
    # Failing the build
    Throw "Build failed because there was one or more PSScriptAnalyzer violation. See test results for more information."
}
   

 
And here is the result in Appveyor :

appveyor-overview
 
Just by reading the name of the test case, we get the essential information : the rule name, the file name and even the line number. Pretty nice, huh ?

Also, we can expand any failed test (by clicking on it) to get additional information. For example, the last 2 tests are expanded below :

appveyor-test-details
 
The “Stacktrace” section provides additional details, like the rule severity and the actual offending code. Another nice touch is that the “Message” section gives us the rule message, which normally provides an actionable recommendation to remediate the problem.

But, what if PSScriptAnalyzer returns nothing ?
Export-NUnitXml does handle this scenario gracefully because its ScriptAnalyzerResult parameter accepts $Null.
In this case, the test result file will contain only one test case and this test passes.

Let’s test this :

Import-Module -Name 'PsScriptAnalyzer' -Force
Import-Module ".\Export-NUnitXml\Export-NUnitXml.psm1" -Force
Export-NUnitXml -ScriptAnalyzerResult $Null -Path ".\ScriptAnalyzerResult.xml"

(New-Object 'System.Net.WebClient').UploadFile("https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path .\ScriptAnalyzerResult.xml))
  

 
Here is what it looks like in Appveyor:

appveyor-passed-psscriptanalyzer-tests
 
There’s nothing more beautiful than a green test…

So now, as developers, we not only have quick feedback on our adherence to coding standards, but we also get actionable guidance on how to improve.
And remember, this NUnit XML format is widely supported in the CI/CD world, so even though I only showed Appveyor, this would work similarly in TeamCity, Microsoft VSTS, and others…

Where to start your automation efforts ? An analogy for IT infrastructure folks

Nowadays, many IT shops look a lot like the first few pages of The Phoenix Project : lack of automation and communication which leads to manual and unpredictable deployments, which in turn, leads to lots of firefighting. Fortunately, many of these shops are starting to understand the value of implementing some of the DevOps principles.

Of all the DevOps principles, automation is probably the easiest to grasp so that’s where most IT organisations start. I’m not saying this is the best starting point, but this is the most typical starting point of a DevOps journey. At this point, IT folks who are traditionally infrastructure-focused are asked to move their focus “up-the-stack” and towards automation. This is a difficult shift to make, especially for those who are not willing to adapt and learn new skills. But even for those who are willing to make that shift, it can be confusing.

OK, I’m going to automate stuff, but where do I start ? What should I automate first ?


I’ll attempt to answer that question drawing on my 8 years of hard-learned lessons in technical support and using a metaphor that most infrastructure-focused IT folks can relate to.

Storage performance troubleshooting :

Users are complaining that a specific application is “very slow”, so you go and check the resources usage for the virtual machine running that particular application. You notice frequent storage latency spikes of up to 3 seconds ! Now, you need to identify where this latency is coming from. It is easier said than done, storage infrastructure is complex, especially SAN-based storage. The latency can come from many different areas : from within the virtual machine (or the application itself), from the hypervisor, from the SAN fabric (cables and switches) or from the storage array.

But ultimately, whatever the transport protocol, it boils down to encapsulated SCSI commands. So you need to consider the storage system as a whole and try to picture it as a pipeline transporting SCSI commands from a VM to a disk. Any component which is struggling to keep up will eventually slow down the entire pipeline. Why ?

Because the SCSI commands, or frames, or packets, or whatever the unit of work is at this stage, are going to be stored in the queue (or buffer) of the struggling component. And what happens when the struggling component’s queue is full ? The queue of another component, located upstream in the pipeline, starts to fill up. In the meantime, any component located downstream in the pipeline is left with no work to do, waiting, waiting, waiting…

So you need to check the latency metrics at each components in the pipeline and single out which one introduces the most latency : the big bad bottleneck. It’s not always obvious and sometimes the victim can be confused with the culprit, but that’s where your expertise comes in. That’s why you are paid the big bucks, right ?

Let’s say you have identified the latency introduced in each areas, like so :

  • Virtual machine : 10 milliseconds
  • Hypervisor : 25 milliseconds
  • SAN fabric : 50 milliseconds
  • Storage array : variable, up to almost 3 seconds

Now, if you reduce the latency at the storage array level by 2 seconds, how much latency improvement are you going to see on the whole storage system end-to-end ?
2 seconds.
If you reduce the latency the SAN fabric level by 30 milliseconds, how much latency improvement are you going to see on the whole storage system end-to-end ?
None.
This seems quite obvious but this is to emphasize a very important point : the energy, time and resources spent on anything else than the bottleneck are 100% waste. So where do you start ? You identify the bottleneck and focus all your efforts on improving the performance of that component.

After further investigation, it turns out there was 2 dead disks in the RAID set where the virtual machine was stored. You replace the 2 disks and now the latency at the storage array level is only 30 milliseconds. That’s great, you have eliminated the first bottleneck, but now you have new one : the SAN fabric. Yep, in any pipeline, at any given time, there is one (and only one) bottleneck. So now, you can focus all your efforts on the fabric, unless the current performance is acceptable for your application(s).

This is in a nutshell how to prioritize performance improvements in a storage system, but what the hell does it have to do with automation ?
Everything.

IT service delivery as a pipeline :

pipeline
 
The “Lean” thinking (and all the stuff that came from it, like Agile) originated from applying the principles of Lean manufacturing (pioneered by Toyota) to the software industry. It compares a software delivery pipeline with a manufacturing assembly line. This is a very powerful analogy and many fascinating learnings have been drawn from it. If you are not convinced, I suggest you read this : Lean Software Development: An Agile Toolkit.

With the emergence of DevOps and “Lean IT“, some people started to realize that it doesn’t necessarily have to be software, these principles can be applied to IT operations as well. IT service delivery can be considered as a pipeline, pretty much like a storage system. It transports a continuous flow of tickets, feature requests, change requests, or work items instead of SCSI commands, frames or packets. The destination of the services it delivers is one or more end-users, instead of a disk.

The components involved in the different stages along the pipeline vary a lot depending on the type and scope of the request : application team, systems team, maybe network and storage team, security team, possibly some kind of QA, a manager and/or procurement approval depending on the cost, etc… It can be potentially be very complex, but you need to gather an exhaustive list of all the parts involved in the pipeline, even outside of IT. This requires to take a step back from your IT bubble and look at the bigger picture, which is not easy, but it is important to have a holistic view of “the system”.

This mental model of a pipeline allows to “troubleshoot” the performance of your IT service delivery. Just like any pipeline, the 2 main ways to measure performance are :

  • Throughput (the amount of work that can go through the pipeline in a given amount of time)
  • Latency (the time it takes for a single unit of work to go from the beginning of the pipeline to the end)

Similarly to most storage admins, Agile and DevOps tend to focus more on latency as a performance indicator. Agile talks a lot about “velocity” and DevOps uses the term “lead times“. So again, you need to determine the latency at each stage of the IT service delivery pipeline and identify the component which adds the most latency : the big bad bottleneck.

Like in a storage infrastructure, bottlenecks tend to manifest themselves as a queue filling up with work in progress. But this work waiting to be processed is not often obvious in the context of IT services, because you cannot touch it (except for hardware). You can easily see car parts piling up in a warehouse, but can you see the 1s and 0s piling up ? A nice way to make work more visible is to use tools like Kanban boards.

When the bottleneck is identified, you know where to focus your efforts. Not just your automation efforts, ALL efforts should be focused on addressing the bottleneck. Yes, automation may very well be only a part of the solution and in some cases, it might even be a very small portion of the solution. This is because technology may only be a small part of the problem. The bigger problem may very well be lack of communication, or lack of skills, or information retention, or overly complex processes, etc… This means your automation efforts need to be integrated into a broader effort to eliminate the bottleneck. It is about IT and “the business” working together towards a common goal.

When the latency of the struggling component in the IT service delivery pipeline has been reduced enough to not be the bottleneck anymore (using automation and any other means), you know that you have improved the performance of your entire IT organization, and by how much. By the way, this information can come in handy for your next pay review. After that, you can move on and focus all your energy (and newly acquired automation skills) on the next bottleneck.

So there is no ready-made recipe to tell you where to start your automation efforts. It is not easy because every business is different and because it requires a shift in mindset, thinking about the bigger picture. But hopefully, this article provides some guidance on how to prioritize your efforts. It is very much about optimizing the impact of your work by focusing on relieving the most crippling pain your IT organization has, and by doing so, making yourself more valuable.

If you want more on these topics, here is a pretty deep perspective on automation, infrastructure (networking in this case) and bottlenecks.

Searching code, repos, issues, pull requests and users on GitHub using PowerShell

Coding, especially in PowerShell, is not about remembering the exact syntax of how to do something, it is more about knowing how to try things out and how to find the information you need to do whatever you need to accomplish.

Quite often, even though we don’t remember the exact syntax, we know the thing we want to do is something we’ve already done before. So there is a good chance it’s already in the code base we have published on GitHub over the years.
If only we could use GitHub as an extension of our brain and, even better, directly from our PowerShell console …

This is why I wrote the PowerShell module PSGithubSearch, available on the PowerShell Gallery and (off course) on GitHub. It uses the extensive GitHub Search API to search the following items on GitHub.com :

  • Code
  • Repositories
  • Issues
  • Pull requests
  • Users
  • Organisations

Let’s have a look at a few examples to illustrate how we can use its 4 cmdlets.

Find-GitHubCode :

Maybe you are working on a new PowerShell function which could really use a -Confirm parameter, let’s say Invoke-NuclearRedButton.
You know that this requires the SupportsShouldProcess cmdletBinding attribute but you never ever remember exactly how to use it inside the function. Then, you could do that :

C:\> Find-GitHubCode -Keywords 'SupportsShouldProcess' -User $Me -Language 'PowerShell' | Select-Object -First 1


FileName               : Update-ChocolateyPackage.psm1
FilePath               : Update-ChocolateyPackage/Update-ChocolateyPackage.psm1
File Url               : https://github.com/MathieuBuisson/Powershell-Utility/blob/5dde8e9bb4fa6244953fee4042e2100acfc6
                         ad72/Update-ChocolateyPackage/Update-ChocolateyPackage.psm1
File Details Url       : https://api.github.com/repositories/28262426/contents/Update-ChocolateyPackage/Update-Chocolat
                         eyPackage.psm1?ref=5dde8e9bb4fa6244953fee4042e2100acfc6ad72
Repository Name        : MathieuBuisson/Powershell-Utility
Repository Description : Various generic tools (scripts or modules) which can be reused from other scripts or modules
Repository Url         : https://github.com/MathieuBuisson/Powershell-Utility

 

OK, but you might want to see the actual file content with the code. This is not built into the cmdlet because it requires an additional API call and the GitHub search API limits the number of unauthenticated requests to 10 per minute, so I tried to limit as much as possible the number of API requests. Anyway, here is how to get the actual code :

C:\> $FileUrl = (Find-GitHubCode -Keywords 'SupportsShouldProcess' -User $Me -Language 'PowerShell' | Select-Object -First 1).url
C:\> $Base64FileContent = (Invoke-RestMethod -Uri $FileUrl).Content
C:\> [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Base64FileContent)) -split '\n' |
 Where-Object { $_ -match 'ShouldProcess' }

    [CmdletBinding(SupportsShouldProcess)]
                If ($PSCmdlet.ShouldProcess($($CurrentPackage.Name), "Install-Package")) {

 
Yep, not that easy.
The original result provides us with a URL that we can query to get more information on that file.
This additional query gives us the content of the file but as a Base64 encoded string, that’s why we need to decode it as UTF8.
But then, it is still a single (large) string, that’s why we needed to split it on each new line character (\n).

This is not very practical for large files, so you can restrict the search to files of a certain size (in bytes), like so :

C:\> Find-GitHubCode -Repo "$Me/Powershell-Utility" -Keywords 'SupportsShouldProcess' -SizeBytes '<4000'


FileName               : Update-ChocolateyPackage.psm1
FilePath               : Update-ChocolateyPackage/Update-ChocolateyPackage.psm1
File Url               : https://github.com/MathieuBuisson/Powershell-Utility/blob/5dde8e9bb4fa6244953fee4042e2100acfc6
                         ad72/Update-ChocolateyPackage/Update-ChocolateyPackage.psm1
File Details Url       : https://api.github.com/repositories/28262426/contents/Update-ChocolateyPackage/Update-Chocolat
                         eyPackage.psm1?ref=5dde8e9bb4fa6244953fee4042e2100acfc6ad72
Repository Name        : MathieuBuisson/Powershell-Utility
Repository Description : Various generic tools (scripts or modules) which can be reused from other scripts or modules
Repository Url         : https://github.com/MathieuBuisson/Powershell-Utility

 

There are other parameters which can help narrow down the search to get exactly what we need. We’ll leave that as homework, because we have 3 other cmdlets to cover.

Find-GitHubRepository :

As an example, we might want to know what interesting project one of our favorite automation hero is currently working on :

C:\> $WarrenRepos = Find-GitHubRepository -Keywords 'PowerShell' -User 'RamblingCookieMonster'
C:\> $WarrenRepos | Sort-Object -Property pushed_at -Descending | Select-Object -First 1


Name         : PSDepend
Full Name    : RamblingCookieMonster/PSDepend
Owner        : RamblingCookieMonster
Url          : https://github.com/RamblingCookieMonster/PSDepend
Description  : PowerShell Dependency Handler
Fork         : False
Last Updated : 2016-08-28T15:48:52Z
Last Pushed  : 2016-09-29T16:06:04Z
Clone Url    : https://github.com/RamblingCookieMonster/PSDepend.git
Size (KB)    : 202
Stars        : 10
Language     : PowerShell
Forks        : 2

 
Warren has been working on this new project for a good month, and this project already has 10 stars and 2 forks. It definitely looks like an interesting project.

We can also sort the results by popularity (number of stars) or by activity (number of forks). For example, we could get the 5 most popular PowerShell projects related to deployment, like so :

C:\> $DeploymentProjects = Find-GitHubRepository -Keywords 'Deployment' -In description -Language 'PowerShell' -SortBy stars
C:\> $DeploymentProjects | Select-Object -First 5

Name         : AzureStack-QuickStart-Templates
Full Name    : Azure/AzureStack-QuickStart-Templates
Owner        : Azure
Url          : https://github.com/Azure/AzureStack-QuickStart-Templates
Description  : Quick start ARM templates that deploy on Microsoft Azure Stack
Fork         : False
Last Updated : 2016-10-01T19:16:20Z
Last Pushed  : 2016-09-28T22:03:44Z
Clone Url    : https://github.com/Azure/AzureStack-QuickStart-Templates.git
Size (KB)    : 11617
Stars        : 118
Language     : PowerShell
Forks        : 74

Name         : unfold
Full Name    : thomasvm/unfold
Owner        : thomasvm
Url          : https://github.com/thomasvm/unfold
Description  : Powershell-based deployment solution for .net web applications
Fork         : False
Last Updated : 2016-09-25T03:55:03Z
Last Pushed  : 2014-10-10T07:28:22Z
Clone Url    : https://github.com/thomasvm/unfold.git
Size (KB)    : 1023
Stars        : 107
Language     : PowerShell
Forks        : 13

Name         : AppRolla
Full Name    : appveyor/AppRolla
Owner        : appveyor
Url          : https://github.com/appveyor/AppRolla
Description  : PowerShell framework for deploying distributed .NET applications to multi-server environments inspired
               by Capistrano
Fork         : False
Last Updated : 2016-09-20T10:29:29Z
Last Pushed  : 2013-08-25T18:04:13Z
Clone Url    : https://github.com/appveyor/AppRolla.git
Size (KB)    : 546
Stars        : 91
Language     : PowerShell
Forks        : 10

Name         : SharePointDsc
Full Name    : PowerShell/SharePointDsc
Owner        : PowerShell
Url          : https://github.com/PowerShell/SharePointDsc
Description  : The SharePointDsc PowerShell module provides DSC resources that can be used to deploy and manage a
               SharePoint farm
Fork         : False
Last Updated : 2016-09-05T12:05:18Z
Last Pushed  : 2016-09-27T17:07:10Z
Clone Url    : https://github.com/PowerShell/SharePointDsc.git
Size (KB)    : 3576
Stars        : 80
Language     : PowerShell
Forks        : 48

Name         : PSDeploy
Full Name    : RamblingCookieMonster/PSDeploy
Owner        : RamblingCookieMonster
Url          : https://github.com/RamblingCookieMonster/PSDeploy
Description  : Simple PowerShell based deployments
Fork         : False
Last Updated : 2016-09-27T17:33:51Z
Last Pushed  : 2016-09-29T09:42:46Z
Clone Url    : https://github.com/RamblingCookieMonster/PSDeploy.git
Size (KB)    : 665
Stars        : 76
Language     : PowerShell
Forks        : 18

 
We used the In parameter to look for the “Deployment” keyword in the description field of repositories, we could look only in the repositories name or ReadMe, if we wanted to.

Now let’s dive into the heart of GitHub collaboration with issues and pull requests.

Find-GitHubIssue :

Maybe, we want to know the most commented open issue on the PowerShell project which hasn’t been assigned to anyone yet. This is pretty easy to do :

C:\> Find-GitHubIssue -Repo 'PowerShell/PowerShell' -Type issue -State open -No assignee -SortBy comments |
 Select-Object -First 1


Title        : Parameter binding problem with ValueFromRemainingArguments in PS functions
Number       : 2035
Id           : 172737066
Url          : https://github.com/PowerShell/PowerShell/issues/2035
Opened by    : dlwyatt
Labels       : {Area-Language, Issue-Bug, Issue-Discussion}
State        : open
Assignees    :
Comments     :
Created      : 2016-08-23T15:51:55Z
Last Updated : 2016-09-29T14:45:43Z
Closed       :
Body         : Steps to reproduce
               ------------------

               Define a PowerShell function with an array parameter using the ValueFromRemainingArguments property of
               the Parameter attribute.  Instead of sending multiple arguments, send that parameter a single array
               argument.

               ```posh
                & {
                    param(
                        [string]
                        [Parameter(Position=0)]
                        $Root,

                        [string[]]
                        [Parameter(Position=1, ValueFromRemainingArguments)]
                        $Extra)
                    $Extra.Count;
                    for ($i = 0; $i -lt $Extra.Count; $i++)
                    {
                       "${i}: $($Extra[$i])"
                    }
                } root aa,bb
               ```

               Expected behavior
               -----------------
               The array should be bound to the parameter just as you sent it, the same way it works for cmdlets.
               (The "ValueFromRemainingArguments" behavior isn't used, in this case, it should just bind like any
               other array parameter type.)  The output of the above script block should be:

               2
               0: aa
               1: bb

               Actual behavior
               ---------------
               PowerShell appears to be performing type conversion on the argument to treat the array as a single
               element of the parameter's array, instead of checking first to see if more arguments will be bound as
               "remaining arguments" first.  The output of the above script block is currently:

               1
               0: aa bb

               Additional information
               ------------------

               To demonstrate that the behavior of cmdlets is different, you can use this code:

               ```posh
               Add-Type -OutputAssembly $env:temp\testBinding.dll -TypeDefinition @'
                   using System;
                   using System.Management.Automation;

                   [Cmdlet("Test", "Binding")]
                   public class TestBindingCommand : PSCmdlet
                   {
                       [Parameter(Position = 0)]
                       public string Root { get; set; }

                       [Parameter(Position = 1, ValueFromRemainingArguments = true)]
                       public string[] Extra { get; set; }

                       protected override void ProcessRecord()
                       {
                           WriteObject(Extra.Length);
                           for (int i = 0; i < Extra.Length; i++)
                           {
                               WriteObject(String.Format("{0}: {1}", i, Extra[i]));
                           }
                       }
                   }
               '@

               Import-Module $env:temp\testBinding.dll

               Test-Binding root aa,bb
               ```

               Environment data
               ----------------

               <!-- provide the output of $PSVersionTable -->

               ```powershell
               > $PSVersionTable
               Name                           Value
               ----                           -----
               PSEdition                      Core
               PSVersion                      6.0.0-alpha
               PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
               WSManStackVersion              3.0
               GitCommitId                    v6.0.0-alpha.9-107-g203ace04c09dbbc1ac00d6b497849cb69cc919fb-dirty
               PSRemotingProtocolVersion      2.3
               CLRVersion
               SerializationVersion           1.1.0.1
               BuildVersion                   3.0.0.0
               ```

 
That is a pretty detailed and complex issue.

Now, we might wonder who is the top contributor (in terms of Pull requests) to the PowerShell documentation project :

C:\> $DocsPR = Find-GitHubIssue -Type pr -Repo 'PowerShell/PowerShell-Docs'
C:\> $DocsPR | Group-Object { $_.user.login } |
 Sort-Object -Property Count -Descending | Select-Object -First 10

Count Name                      Group
----- ----                      -----
  141 eslesar                   {@{url=https://api.github.com/repos/PowerShell/PowerShell-Docs/issues/650; repositor...
   81 HemantMahawar             {@{url=https://api.github.com/repos/PowerShell/PowerShell-Docs/issues/656; repositor...
   59 alexandair                {@{url=https://api.github.com/repos/PowerShell/PowerShell-Docs/issues/627; repositor...
   32 juanpablojofre            {@{url=https://api.github.com/repos/PowerShell/PowerShell-Docs/issues/657; repositor...
   28 neemas                    {@{url=https://api.github.com/repos/PowerShell/PowerShell-Docs/issues/107; repositor...
   26 joeyaiello                {@{url=https://api.github.com/repos/PowerShell/PowerShell-Docs/issues/554; repositor...
   20 Dan1el42                  {@{url=https://api.github.com/repos/PowerShell/PowerShell-Docs/issues/645; repositor...
   10 PlagueHO                  {@{url=https://api.github.com/repos/PowerShell/PowerShell-Docs/issues/330; repositor...
    9 JKeithB                   {@{url=https://api.github.com/repos/PowerShell/PowerShell-Docs/issues/605; repositor...
    8 saldana                   {@{url=https://api.github.com/repos/PowerShell/PowerShell-Docs/issues/455; repositor...
   

 
Wow, some people are really into documentation.

Find-GithubUser :

GitHub.com is the largest open-source software community, so it is a great place to find passionate and talented coders who are willing to share their craft with the community.

Let’s say you are a recruiter or a hiring manager and you are looking for a PowerShell talent in Ireland. The cmdlet Find-GithubUser can facilitate that search :

C:\> Find-GithubUser -Type user -Language 'PowerShell' -Location 'Ireland' | Where-Object { $_.Hireable }


UserName      : JunSmith
Full Name     : Jun Smith
Type          : User
Url           : https://github.com/JunSmith
Company       :
Blog          :
Location      : Ireland
Email Address :
Hireable      : True
Bio           :
Repos         : 12
Gists         : 0
Followers     : 7
Following     : 4
Joined        : 2015-01-17T13:27:24Z

UserName      : TheMasterPrawn
Full Name     : Rob Allen
Type          : User
Url           : https://github.com/TheMasterPrawn
Company       : Unity Technology Solutions IRL
Blog          :
Location      : Ireland
Email Address :
Hireable      : True
Bio           : I.T/Dev guy, gamer, geek living and working in Ireland.
Repos         : 3
Gists         : 0
Followers     : 0
Following     : 0
Joined        : 2014-06-10T11:09:20Z

 
2 users only. That’s helpful … It highlights the huge PowerShell skill gap we have in Ireland.

Let’s focus on UK and organizations, then. Organizations don’t have followers (or following) so we cannot filter them on the number of followers they have, but we can narrow down the search to those which have 5 or more repos :

C:\> Find-GithubUser -Type org -Language 'PowerShell' -Location 'UK' -Repos '>=5'


UserName      : SpottedHyenaUK
Full Name     : Spotted Hyena UK
Type          : Organization
Url           : https://github.com/SpottedHyenaUK
Company       :
Blog          : http://www.spottedhyena.co.uk
Location      : Leeds, UK
Email Address :
Hireable      :
Bio           :
Repos         : 5
Gists         : 0
Followers     : 0
Following     : 0
Joined        : 2015-02-03T14:38:16Z

UserName      : VirtualEngine
Full Name     : Virtual Engine
Type          : Organization
Url           : https://github.com/VirtualEngine
Company       :
Blog          : http://virtualengine.co.uk
Location      : UK
Email Address : info@virtualengine.co.uk
Hireable      :
Bio           :
Repos         : 17
Gists         : 0
Followers     : 0
Following     : 0
Joined        : 2014-03-21T14:51:14Z

 
That was just a few examples, but since each of these cmdlets have many parameters, this was just scratching the surface of what can be done with them.
For the full list of parameters (and how to use them), please refer to the README file on GitHub or use Get-Help.

Also, I’m aware it’s not perfect (yet) so issues and pull requests are very much welcome.

Getting the members of a type, without an instance of the type

I read yesterday’s article from Jeff Hicks on “Dancing on the table with PowerShell“. The content is really quite fascinating (go read it !), but I got hung up on something.

He creates a new object of the type [System.Data.DataTable], pipes it to Get-Member and shows that we can’t discover the members of this object type, like so :

C:\> $table = New-Object -TypeName 'System.Data.DataTable'
C:\> $table | Get-Member
Get-Member : You must specify an object for the Get-Member cmdlet.
At line:1 char:10
+ $table | Get-Member
+          ~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Get-Member], InvalidOperationException
    + FullyQualifiedErrorId : NoObjectInGetMember,Microsoft.PowerShell.Commands.GetMemberCommand

 
My understanding is that Get-Member is complaining because at this point, $Table is not a fully formed object. Even though it has a type :

C:\> $table.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     DataTable                                System.ComponentModel.MarshalByValueComponent

 
Anyway, my thought was :

“There has to be a way to get the members of a type, even without an instance of that type”

So, let’s see how we can do that.

First, we get a type object from our type name :

C:\> $TypeObj = 'System.Data.DataTable' -as [type]
    

 
Then, this [Type] object surely has a property or a method allowing us to view the members associated with that type. So we can try something like this :

C:\> $TypeObj | Get-Member -Name "*Members*"


   TypeName: System.RuntimeType

Name              MemberType Definition
----              ---------- ----------
FindMembers       Method     System.Reflection.MemberInfo[] FindMembers(System.Reflection.MemberTypes memberType, Sy...
GetDefaultMembers Method     System.Reflection.MemberInfo[] GetDefaultMembers(), System.Reflection.MemberInfo[] _Typ...
GetMembers        Method     System.Reflection.MemberInfo[] GetMembers(), System.Reflection.MemberInfo[] GetMembers(...

 
Yep, the GetMembers() method (if it does what it says) is exactly what we want.
Let’s try it :

C:\> $TypeObj.GetMembers() | Select-Object -Property Name,MemberType

Name                    MemberType
----                    ----------
get_CaseSensitive           Method
set_CaseSensitive           Method
get_IsInitialized           Method
set_RemotingFormat          Method
get_RemotingFormat          Method
get_ChildRelations          Method
get_Columns                 Method
get_Constraints             Method
get_DataSet                 Method
get_DefaultView             Method
set_DisplayExpression       Method
get_DisplayExpression       Method
get_ExtendedProperties      Method
get_HasErrors               Method
set_Locale                  Method
get_Locale                  Method
get_MinimumCapacity         Method
set_MinimumCapacity         Method
get_ParentRelations         Method
get_PrimaryKey              Method
set_PrimaryKey              Method
get_Rows                    Method
set_TableName               Method
get_TableName               Method
set_Namespace               Method
get_Namespace               Method
get_Prefix                  Method
set_Prefix                  Method
set_Site                    Method
get_Site                    Method
get_Container               Method
get_DesignMode              Method
GetObjectData               Method

# Ouput cut for brevity

C:\> ($TypeObj.GetMembers() | Select-Object -Property Name,MemberType).Count
159

 
There are a lot of members for this type. This method also allows us to see some members that we wouldn’t see by default using Get-Member, because it even gets non-public members. And there are some duplicates :

C:\> ($TypeObj.GetMembers() | Select-Object Name,MemberType -Unique).Count
120

 
By the way, in case we are only interested in the properties of our type, there is another method (aptly named GetProperties) which gets only the properties :

C:\> $TypeObj.GetProperties() | Select-Object -Property Name,MemberType

Name               MemberType
----               ----------
CaseSensitive        Property
IsInitialized        Property
RemotingFormat       Property
ChildRelations       Property
Columns              Property
Constraints          Property
DataSet              Property
DefaultView          Property
DisplayExpression    Property
ExtendedProperties   Property
HasErrors            Property
Locale               Property
MinimumCapacity      Property
ParentRelations      Property
PrimaryKey           Property
Rows                 Property
TableName            Property
Namespace            Property
Prefix               Property
Site                 Property
Container            Property
DesignMode           Property

 
That’s pretty much all we need to know to view the members associated with a type, without having to create an object of that type.
We can package this knowledge into a function, for convenient reuse, like so :

Function Get-MemberFromTypeName
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$True)]
        [string]$TypeName
    )
    $TypeObj = $TypeName -as [type]
    $RawMembers = $TypeObj.GetMembers()

    [System.Collections.ArrayList]$OutputMembers = @()

    Foreach ( $RawMember in $RawMembers ) {
        
        $OutputProps = [ordered]@{
                                'Name'= $RawMember.Name
			                    'MemberType'= $RawMember.MemberType
                        }

        $OutputMember = New-Object -TypeName psobject -Property $OutputProps
        $OutputMembers += $OutputMember
    }
    $OutputMembers | Select-Object -Property * -Unique
}

 

Using Pester to validate deployment readiness for a large number of machines

Recently, I had to roll out an upgrade of our software for a customer. The upgrade failed for about 80 client machines (out of around 400). There was a lot of head-scratching and quite a few “It was working in the Test environment !”. Because we couldn’t afford much more downtime for end-users, I had to develop an ugly workaround to allow machines to upgrade. But even so, this upgrade rollout went well over the planned maintenance window.

In short, it was a pain. And you know what ?
Pains are great learning opportunities and powerful incentives to take action. The first lesson was that there was a multitude of different causes which boiled down to misconfiguration, due to inconsistently managed client machines.

The second lesson was that we needed some kind of tool to validate the upgrade (or deployment) readiness of a bunch of machines to prevent this kind of mess in the future. This tool would allow to check whether all the machines meet the prerequisites for a new deployment or upgrade before rolling it out. This should also provide a nice, visual report so that non-technical stakeholders can see :

  • The overall number and percentage of machines not ready
  • Which machines are ready
  • Which ones are not ready
  • Which prerequisites (and prerequisite categories) are met
  • Which prerequisites (and prerequisite categories) are not met

The report should also allow technical stakeholders to drill down to see for a specific machine which prerequisite(s) were not met and why.

Knowing that Pester can be used to validate the operation of a system, I figured I could build a tool leveraging Pester tests to validate prerequisites. So I wrote the DeploymentReadinessChecker PowerShell module and made it available on the PowerShell Gallery. Yes, anyone can use it because it is designed as BYOPS (Bring Your Own Pester Script).

Regarding the HTML report, I didn’t reinvent the wheel, this is using a great utility named ReportUnit.

Basic usage :

First, we need :

  • PowerShell 4.0 (or later).
  • The Pester module should be installed on the machine from which we run DeploymentReadinessChecker.
  • A Pester script containing tests for the prerequisites we want to validate and optionally, “Describe” blocks to group tests in “prerequisite categories”.
  • If the above Pester script (validation script) takes parameters, the values for the parameters we need to pass to it.
  • A list of computer names for the machines we want to check the prerequisites against.
  • Credentials to connect to all the target machines

Now that we have everything we need, let’s get to it.

The module comes with an example validation script : Example.Tests.ps1 and that is what we are going to use here. For your own deployments or upgrades, you will need a validation script containing tests for your own prerequisites : hardware prerequisites, OS requirements, runtime or other software dependencies, network connectivity prerequisites… whatever you need.

Here are a few examples from the first 2 “Describe” blocks of Example.Tests.ps1 :

Describe 'Hardware prerequisites' -Tag 'Hardware' {
    
    It 'Has at least 4096 MB of total RAM' {

        Invoke-Command -Session $RemoteSession {
        (Get-CimInstance -ClassName Win32_PhysicalMemory).Capacity / 1MB } |
        Should Not BeLessThan 4096
    }
}
Describe 'Networking prerequisites' -Tag 'Networking' {

    It 'Can ping the Management server by name' {

        Invoke-Command -Session $RemoteSession { param($ManagementServerName)
        Test-Connection -ComputerName $ManagementServerName -Quiet } -ArgumentList $ManagementServerName |
        Should Be $True
    }
    It 'Can ping the Deployment server by name' {

        Invoke-Command -Session $RemoteSession { param($DeploymentServerName)
        Test-Connection -ComputerName $DeploymentServerName -Quiet } -ArgumentList $DeploymentServerName |
        Should Be $True
    }
    It 'Has connectivity to the Management server on TCP port 80' {

        Invoke-Command -Session $RemoteSession { param($ManagementServerName)
        (Test-NetConnection -ComputerName $ManagementServerName -CommonTCPPort HTTP).TcpTestSucceeded } -ArgumentList $ManagementServerName |
        Should Be $True
    }
    It 'Has the firewall profile set to "Domain" or "Private"' {

        Invoke-Command -Session $RemoteSession {
        $FirewallProfile = (Get-NetConnectionProfile)[0].NetworkCategory.ToString();
        $FirewallProfile -eq 'Domain' -or $FirewallProfile -eq 'Private' } |
        Should Be $True
    }
}

As we can see, it is the validation script’s responsibility to handle the remoting to the target machines.
The validation script should be located in $Module_Folder\ReadinessValidationScript\, for example : C:\Program Files\WindowsPowerShell\Modules\DeploymentReadinessChecker\1.0.0\ReadinessValidationScript\Example.Tests.ps1.

Also, its extension should be “.Tests.ps1” because that’s what Invoke-Pester looks for.

There is no support for multiple validation scripts, so before adding your own validation script in there, rename Example.Tests.ps1 by changing its extension to something else than “.Tests.ps1“. This is to ensure that the example script is ignored by Invoke-Pester.

UPDATE :
I added support for multiple validation scripts being present in $Module_Folder\ReadinessValidationScript\.
Test-DeploymentReadiness can only invoke one validation script at a time, but if there is more than one validation script present, a dynamic parameter named ValidationScript is made available (mandatory, even) to specify the name of the validation script.

It is highly recommended to group related tests into distinct and meaningful “Describe” blocks because, as we’ll see later on, some items in the report are displayed on a per-Describe block basis.

Optionally, “Describe” blocks can have tags and the tool can use these tags to include or exclude some tests, just like Invoke-Pester does.

The module contains a single cmdlet : Test-DeploymentReadiness.

Our computer names list can be fed to the -ComputerName parameter at the command line, from a file, or via pipeline input. For example, for a single computer, this could look like :

C:\> Test-DeploymentReadiness -ComputerName Computer1 -Credential $Cred -OutputPath $env:USERPROFILE\Desktop\Readiness\ |
Invoke-Item

Here is the console output :

Simple example with Invoke-Item

So we get the normal output from Invoke-Pester for each target machine specified via the -ComputerName parameter and a little bit more text at the end. All of this is just written to the console (using Write-Host) but it outputs a single object to the pipeline : a FileInfo object for the Index.html of the report. That way, if we want instant gratification, we can directly open the report in our default browser by piping the output of Test-DeploymentReadiness to Invoke-Item, as seen above.

Off course, it generates a bunch of files, as well. These are generated in the current directory by default, or in the directory specified via the -OutputPath parameter. Invoke-Pester generates one test result file (.xml) per target machine and ReportUnit.exe generates one HTML report per target machine and the overall report Index.html. To view the report, we only need to open the Index.html because it has the links to machine-specific files if we want to drill down to the per-machine reports.

Filtering the tests using tags :

As said earlier, all the Pester tests representing the prerequisites should be in a single validation script, so we can potentially end up with a script containing a very large number of tests. To make this more modular and flexible, we can group tests related to the same topic, purpose, or component into distinct “Describe” blocks and give these “Describe” blocks some tags.

Then, Test-DeploymentReadiness can include only the tests contained in the “Describe” blocks which have the tag(s) specified via the -Tag parameter. Let’s see what it looks like :

Simple example with tag

Similarly, we can exclude the tests contained in the “Describe” blocks which have the tag(s) specified via the -ExcludeTag parameter.

Passing parameters to the validation script :

It is more than likely that the Pester-based validation script takes parameters, especially since it remotes into the target machines, so it may need a -ComputerName and a -Credential parameter. If your validation script has parameter names matching “ComputerName” or “Credential“, then Test-DeploymentReadiness does a bit of work for you.

If the validation script has a ComputerName parameter, Test-DeploymentReadiness passes one computer at a time to its ComputerName parameter, via the Script parameter of Invoke-Pester.

If the validation script has a Credential parameter, the Test-DeploymentReadiness passes the value of its own Credential parameter to the validation script, via the Script parameter of Invoke-Pester.

Cool, but what about any other parameters ?
That’s where the -TestParameters parameter comes in. The parameter names and values can be passed as a hashtable to the -TestParameters parameter of Test-DeploymentReadiness. Then, Test-DeploymentReadiness passes these into the Script parameter of Invoke-Pester, when calling the validation script.

The example validation script Example.Tests.ps1 takes quite a few parameters, among them are DeploymentServerName and ManagementServerName . We can pass values to these 2 parameters, like so :

C:\> $TestParameters= @{ DeploymentServerName = 'DeplServer1'
                      ManagementServerName = 'Mgmtserver1'
                   }
C:\>
C:\> 'Computer1','Computer2','Computer3','Computer4','Computer5' |
Test-DeploymentReadiness -Credential $Cred -OutputPath $env:USERPROFILE\Desktop\Readiness\ -TestParameters $TestParameters
   

 

The Reports :

As mentioned earlier, we only need to open the generated Index.html and this opens the overview report. After running the above command, here is what this looks like :

Overview Report

Fixture summary” gives us the number of ready machines and not-so-ready machines whereas the “Pass percentage” gives us the percentage of machines which are ready.

We can see that Computer4 is the only machine which failed more than 1 prerequisite. We can see what’s going on with it in more detail by clicking on the link named “Computer4” :

Computer4 Report

We can clearly see 4 distinct prerequisite categories, which corresponds with “Describe” blocks in our validation script. Here, “Fixture summary” tells us which prerequisite categories contained at least one failed prerequisite(s). In this case, there were 2.

Let’s check which Networking prerequisite(s) were not met by clicking on “Networking prerequisites” :

Network Prerequisites Details

So now, we have can a good idea of what the issue is (the actual usefulness of the Pester error message will depend on how the test was written).

Pretty neat, huh ? I can see this saving me hours and hours of work, and considerably reduce the maintenance windows in future deployments and upgrades.

If this tool doesn’t exactly fit your needs or if you think of an enhancement, the code is on GitHub, feel free to submit an issue, or even better, to fork it and improve it.

A Boilerplate for Unit testing DSC resources with Pester

Unit testing PowerShell code is slowly but surely becoming mainstream. Pester, the awesome PowerShell testing framework is playing a big part in that trend.
But why the hell would you write more PowerShell code to test your PowerShell code ? Because :

  • It can give you a better understanding of your code, its design, its assumptions and its behaviour.
     
  • When you make changes and the unit tests pass, you can be pretty confident that you didn’t break anything.
    This makes changes less painful and scary and this is a very important notion in DevOps : removing fear and friction to make changes painless, easy, fast and even … boring.
     
  • It helps writing more robust , less buggy code.
     
  • Given the direction that PowerShell community is taking and the way the DevOps movement is permeating the IT industry, this is becoming a valuable skill.
     
  • There is an initial learning curve and it takes time, effort and discipline, but if you do it often enough, it can quickly become second nature.
     

To help reduce this time and effort, I wanted to a build Pester script template which could be reused for unit testing any DSC resource. After all, DSC resources have a number of specific requirements and best practices, for example : Get-TargetResource should return a hashtable, or Test-TargetResource should return a boolean… So we can write tests for all these requirements and these tests can be readily reused for any other DSC resource (non class-based).

Without further ado, here is the full script (which is also available on GitHub) and then we’ll elaborate on the main bits and pieces :

$Global:DSCResourceName = 'My_DSCResource'  #<----- Just change this

Import-Module "$($PSScriptRoot)\..\..\DSCResources\$($Global:DSCResourceName)\$($Global:DSCResourceName).psm1" -Force

# Helper function to list the names of mandatory parameters of *-TargetResource functions
Function Get-MandatoryParameter {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True)]
        [string]$CommandName
    )
    $GetCommandData = Get-Command "$($Global:DSCResourceName)\$CommandName"
    $MandatoryParameters = $GetCommandData.Parameters.Values | Where-Object { $_.Attributes.Mandatory -eq $True }
    return $MandatoryParameters.Name
}

# Getting the names of mandatory parameters for each *-TargetResource function
$GetMandatoryParameter = Get-MandatoryParameter -CommandName "Get-TargetResource"
$TestMandatoryParameter = Get-MandatoryParameter -CommandName "Test-TargetResource"
$SetMandatoryParameter = Get-MandatoryParameter -CommandName "Set-TargetResource"

# Splatting parameters values for Get, Test and Set-TargetResource functions
$GetParams = @{
    
}
$TestParams = @{
    
}
$SetParams = @{
    
}

Describe "$($Global:DSCResourceName)\Get-TargetResource" {
    
    $GetReturn = & "$($Global:DSCResourceName)\Get-TargetResource" @GetParams

    It "Should return a hashtable" {
        $GetReturn | Should BeOfType System.Collections.Hashtable
    }
    Foreach ($MandatoryParameter in $GetMandatoryParameter) {
        
        It "Should return a hashtable with key named $MandatoryParameter" {
            $GetReturn.ContainsKey($MandatoryParameter) | Should Be $True
        }
    }
}

Describe "$($Global:DSCResourceName)\Test-TargetResource" {
    
    $TestReturn = & "$($Global:DSCResourceName)\Test-TargetResource" @TestParams

    It "Should have the same mandatory parameters as Get-TargetResource" {
        # Does not check for $True or $False but uses the output of Compare-Object.
        # That way, if this test fails Pester will show us the actual difference(s).
        (Compare-Object $GetMandatoryParameter $TestMandatoryParameter).InputObject | Should Be $Null
    }
    It "Should return a boolean" {
        $TestReturn | Should BeOfType System.Boolean
    }
}

Describe "$($Global:DSCResourceName)\Set-TargetResource" {
    
    $SetReturn = & "$($Global:DSCResourceName)\Set-TargetResource" @SetParams

    It "Should have the same mandatory parameters as Test-TargetResource" {
        (Compare-Object $TestMandatoryParameter $SetMandatoryParameter).InputObject | Should Be $Null
    }
    It "Should not return anything" {
        $SetReturn | Should Be $Null
    }
}

 
That’s a lot of information so let’s break it down into more digestible chunks :

$Global:DSCResourceName = 'My_DSCResource'  #<----- Just change this

 
The “My_DSCResource” string is only part in the entire script which needs to be changed from one DSC resource to another. All the rest can be reused for any DSC resource.

Import-Module "$($PSScriptRoot)\..\..\DSCResources\$($Global:DSCResourceName)\$($Global:DSCResourceName).psm1" -Force

The relative path to the module containing the DSC resource is derived from a standard folder structure, with a “Tests” folder at the root of the module and a “Unit” subfolder, containing the resulting unit tests script, for example :

O:\> tree /F "C:\Git\FolderPath\DscModules\DnsRegistration"
Folder PATH listing for volume OS

│   DnsRegistration.psd1
│
├───DSCResources
│   └───DnsRegistration
│       │   DnsRegistration.psm1
│       │   DnsRegistration.schema.mof
│       │
│       └───ResourceDesignerScripts
│               GenerateDnsRegistrationSchema.ps1
│
└───Tests
    └───Unit
            DnsRegistration.Tests.ps1

 
We load the module because we’ll need to use the 3 functions it contains : Get-TargetResource, Set-TargetResource and Test-TargetResource.

By the way, note that this script is divided into 3 Describe blocks : this is a more or less established convention in unit testing with Pester : one Describe block per tested function. The “Force” parameter of Import-Module is to make sure that, even if the module was already loaded, we get the latest version of the module.

Function Get-MandatoryParameter {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True)]
        [string]$CommandName
    )
    $GetCommandData = Get-Command "$($Global:DSCResourceName)\$CommandName"
    $MandatoryParameters = $GetCommandData.Parameters.Values | Where-Object { $_.Attributes.Mandatory -eq $True }
    return $MandatoryParameters.Name
}

 
This is a helper function used to get the mandatory parameter names for the *-TargetResource functions. If you use a more than a few helper functions in your unit tests, then you should probably gather them in a separate script or module.

# Splatting parameters values for Get, Test and Set-TargetResource functions
$GetParams = @{
     
}
$TestParams = @{
     
}
$SetParams = @{
     
}

 
These are placeholders to be completed with the parameters and values for Get-TargetResource, Test-TargetResource and Set-TargetResource, respectively. Splatting makes them more readable, especially for resources that have many parameters. We might use the same parameters and parameter values for all 3 functions, in that case, we can consolidate these 3 hashtables into a single one.

$GetReturn = & "$($Global:DSCResourceName)\Get-TargetResource" @GetParams

 
Specifying the resource name with the function allows to unambiguously call the Get-TargetResource function from the DSC resource we are currently testing and not the one from another resource.

It "Should return a hashtable" {
        $GetReturn | Should BeOfType System.Collections.Hashtable
    }

 
The first actual test ! This is validating that Get-TargetResource returns a object of the type [hashtable]. The “BeOfType” operator is designed specifically for verifying the type of an object so it’s a great fit.

Foreach ($MandatoryParameter in $GetMandatoryParameter) {
        
        It "Should return a hashtable with key named $MandatoryParameter" {
            $GetReturn.ContainsKey($MandatoryParameter) | Should Be $True
        }
    }

 
An article from the PowerShell Team says this :

The Get-TargetResource returns the status of the modeled entities in a hash table format. This hash table must contain all properties, including the Read properties (along with their values) that are defined in the resource schema.

I’m not sure this is a hard requirement because this is not enforced, and Get-TargetResource is not automatically called by the DSC engine. So this may not be ideal but we are getting the names of the mandatory parameters of Get-TargetResource and we check that the hashtable returned by Get-TargetResource has a key matching each of these parameters. Maybe, we could check against all parameters, not just the mandatory ones ?

Now, let’s turn our attention to Test-TargetResource :

    $TestReturn = & "$($Global:DSCResourceName)\Test-TargetResource" @TestParams

    It "Should have the same mandatory parameters as Get-TargetResource" {
        (Compare-Object $GetMandatoryParameter $TestMandatoryParameter).InputObject | Should Be $Null
    }

 
This test is validating that the mandatory parameters of Test-TargetResource are the same as for Get-TargetResource. There is a PSScriptAnalyzer rule for that, with an “Error” severity, so we can safely assume that this is a widely accepted and important best practice :

GetSetTest Parameters
 
Reading the name of this “It” block, we could assume that it is checking against $True or $False. But here, we use Compare-Object and validate that there is no difference between the 2 lists of mandatory parameters. This is to make the message we get in case the test fails more useful : it will tell us the offending parameter name(s).

    It "Should return a boolean" {
        $TestReturn | Should BeOfType System.Boolean
    }

 
The function Test-TargetResource should always return a boolean. This is a well known requirement and this is also explicitly specified in the templates generated by xDSCResourceDesigner, so there is no excuse for not knowing/following this rule.

Now, it is time to test Set-TargetResource :

    It "Should have the same mandatory parameters as Test-TargetResource" {
        (Compare-Object $TestMandatoryParameter $SetMandatoryParameter).InputObject | Should Be $Null
    }

 
The same as before, but this time we validate that the mandatory parameters of the currently tested function (Set-TargetResource) are the same as for Test-TargetResource.

    It "Should not return anything" {
        $SetReturn | Should Be $Null
    }

 
Set-TargetResource should not return anything. Again, you don’t have to take my word for it, PSScriptAnalyzer is our source of truth :

Set should not return anything
 
That’s it for the script. But then, a boilerplate is more useful when it is readily available as a snippet on your IDE of choice. So I also converted this boilerplate into a Visual Studio Code snippet, this is the first snippet in the custom snippet file I made available here.

The path of Visual Studio Code PowerShell snippet file is : %APPDATA%\Code\User\snippets\PowerShell.json.
Or, for those of us using the PowerShell extension, we can modify the following file : %USERPROFILE%.vscode\extensions\ms-vscode.PowerShell-0.6.1\snippets\PowerShell.json.

Obviously, this set of tests is pretty basic and doesn’t cover the code written specifically for a given resource, but it’s a pretty good starting point. This allows to write basic unit tests for our DSC resources in just a few minutes, so now, there’s no excuse for not doing it.

How to create a custom rule for PSScriptAnalyzer

As you probably already know, PSScriptAnalyzer is a static code analysis tool, which checks PowerShell code against rules representing best practices and style guidelines. This is a fantastic tool to set coding style, consistency and quality standards, and if we want to, we can easily enforce these standards within a build pipeline.

The PowerShell community was very much involved in the definition of PSScriptAnalyzer rules, so these rules really make a lot of sense as general guidelines and they are widely accepted by the PowerShell community. However, a given company or project might have specific coding standards which may contain different or more specific rules. Or maybe, you feel like Silicon Valley’s Richard regarding Tabs vs Spaces.

Fortunately, PSScriptAnalyzer allows us to create and use custom rules. In this article, we are going to learn how to do that with a simple example. Let’s say we have coding standards which specifies that all variables names should follow a consistent capitalization style, in particular : PascalCasing. So we are going to write a PSScriptAnalyzer rule to check our code against that convention in the form of a function.

To write this function, our starting point should be this documentation page.
First, how are we going to name our function ? If we look at the CommunityAnalyzerRules module, we see that all the functions names use the verb “Measure“. Why ? I don’t know, but it seems like a sensible convention to follow. That way, if we have multiple rules stored in a single module, we can export all of of them by simply adding the following in the module :

Export-ModuleMember -Function Measure-*

 
So, given our rule is about PascalCasing, the function name “Measure-PascalCase” makes sense.

Next, we need a proper comment-based help for our function. This looks like this :

Function Measure-PascalCase {
<#
.SYNOPSIS
    The variables names should be in PascalCase.

.DESCRIPTION
    Variable names should use a consistent capitalization style, i.e. : PascalCase.
    In PascalCase, only the first letter is capitalized. Or, if the variable name is made of multiple concatenated words, only the first letter of each concatenated word is capitalized.
    To fix a violation of this rule, please consider using PascalCase for variable names.

.EXAMPLE
    Measure-PascalCase -ScriptBlockAst $ScriptBlockAst

.INPUTS
    [System.Management.Automation.Language.ScriptBlockAst]

.OUTPUTS
    [Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord[]]

.NOTES
    https://msdn.microsoft.com/en-us/library/dd878270(v=vs.85).aspx
    https://msdn.microsoft.com/en-us/library/ms229043(v=vs.110).aspx
#>

 
The DESCRIPTION part of the help is actually used by PSScriptAnalyzer so it is important. It should contain an explanation of the rule, as well as a brief explanation of how to remediate any violation of the rule. Here, we don’t want to assume that all users know what PascalCase means, so we give a succinct but (hopefully) clear definition of PascalCase.

In the INPUTS field, we tell the user that the only parameter for our function takes an object of the type : [System.Management.Automation.Language.ScriptBlockAst], but it could be other types of AST objects. But wait, What is AST ?

The short(ish) version is that PowerShell 3.0 introduced a new parser and that Parser relies on AST to expose various elements of the PowerShell language as objects. This facilitates parsing PowerShell code and extract objects corresponding to language elements like : variables, function definitions, parameter blocks, parameters, arrays, hashtables, Foreach statements, If statements, the list goes on and on … And PSScriptAnalyzer relies heavily on this AST-based parser.

In the OUTPUTS field, we explicitly tell the user that the function will return one or more objects of the type [Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord[]]. But the actual user will be PSScriptAnalyzer, so this is really a contract between our function and PSScriptAnalyzer. This is more formally declared with the following function attribute :

[OutputType([Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord[]])]

 
But even with this declaration, PowerShell doesn’t enforce that. So it’s our responsibility to ensure our code doesn’t return anything else, otherwise, PSScriptAnalyzer will not be happy.

Now it is time to tackle the code inside our function. Looking at the CommunityAnalyzerRules module most functions have the same basic structure :

#region Define predicates to find ASTs.

[ScriptBlock]$Predicate = {
    Param ([System.Management.Automation.Language.Ast]$Ast)

    [bool]$ReturnValue = $False
    If ( ... ) {

        ...

    }
    return $ReturnValue
}
#endregion

#region Find ASTs that match the predicates.
[System.Management.Automation.Language.Ast[]]$Violations = $ScriptBlockAst.FindAll($Predicate, $True)

If ($Violations.Count -ne 0) {

    Foreach ($Violation in $Violations) {

        $Result = New-Object `
                -Typename "Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord" `
                -ArgumentList  ...
          
        $Results += $Result
    }
}
return $Results
#endregion

 
We don’t have to follow that structure but it is a very helpful scaffolding. As we can see above, the function is divided in 2 logical parts: the first one is where we define one or more predicates corresponding to our rule and the second one is where we actually use the predicate(s) against input (PowerShell code) to identify any violation(s) of our rule.

Defining predicates

First, what is a predicate ?
It is a scriptblock which returns $True or $False and it is used to filter objects. We have a bunch of objects that we feed to our predicate then, we keep the objects for which the predicate returned $True and we filter out the objects for which the predicate returned $False. Sounds complicated ? It’s not, and you are using predicates. All. The. Time :

C:\> $ThisIsAPredicate = { $_.Name -like "*.ps*1" }
C:\> Get-ChildItem -Recurse | Where-Object $ThisIsAPredicate

 
In the context of our PSScriptAnalyzer rule function, the predicate is used to identify violations of our rule. Any piece of PowerShell code which returns $True when fed to our predicate has a violation of our rule. We can use multiple methods to detect violations, so we can define multiple predicates if we need/want to. Here, this is a simple example so we are going to define a single predicate.

Our predicate should take input (pieces of PowerShell code) via a parameter. Here, the parameter is named Ast and it takes objects of the type [System.Management.Automation.Language.Ast]. This is the generic class for AST, this allows the predicate’s parameter to accept objects of child classes like [System.Management.Automation.Language.ScriptBlockAst], [System.Management.Automation.Language.StatementAst], etc…

            [ScriptBlock]$Predicate = {
                Param ([System.Management.Automation.Language.Ast]$Ast)

                ...

 
Our rule for PascalCasing relates only to variable names, so we first need to identify variables. What is most relevant for naming is when variables are defined, or assigned a value, not really when they are referenced. So the arguably best way to identify variables for our particular purpose is to identify variable assignments, like so :

If ($Ast -is [System.Management.Automation.Language.AssignmentStatementAst]) {

    ...

 
Next, we need to identify any variable names which don’t follow PascalCasing. For that, we’ll use the comparison operator -cnotmatch and a regex. As you probably know, PowerShell is not case sensitive. But our rule is all about casing, it is case hypersensitive. This makes the “c” in -cnotmatch crucial for our predicate to work :

[System.Management.Automation.Language.AssignmentStatementAst]$VariableAst = $Ast
    If ($VariableAst.Left.VariablePath.UserPath -cnotmatch '^([A-Z][a-z]+)+$') {
        $ReturnValue = $True
    }

 
To extract only the variable names from our variable assignment objects, we take their “Left” property (what’s on the left side of the assignment operator), then the “VariablePath” property and then the “UserPath” nested property. This gives us only the variable name as a [string]. If that string doesn’t match our regular expression, the predicate returns $True, which means there is a violation.

A brief explanation of the regex used above ([A-Z][a-z]+) :
this means one upper case letter followed by one or more lower case letter(s). This particular pattern can be repeated so we put it between parenthesis and append a “+”. And all this should strictly between the beginning of the string “^” and the end of the string “$”.

Off course, this detection method is limited because there is no intelligence to detect words of the English language (or any language) which may be concatenated to form the variable name :

PS C:\> "FirstwordSecondword" -cmatch '^([A-Z][a-z]+)+$'
True

PS C:\> "FirstwoRdsecoNdword" -cmatch '^([A-Z][a-z]+)+$'
True

 
Also, I’m not a big fan of using digits in variable names but if you want the rule to allow that, you can use the following regex :

PS C:\> "Word1Word2" -cmatch '^([A-Z]\w+)+$'
True

 

Using the predicate to detect violations

Now, we can use our predicate against whatever PowerShell code is fed to our Measure-PascalCase function via its $ScriptBlockAst parameter. The input PowerShell code is an object of the type [System.Management.Automation.Language.ScriptBlockAst], so like most AST objects, it has a FindAll() method which we can use to find all the elements within that object which match a predicate.

[System.Management.Automation.Language.Ast[]]$Violations = $ScriptBlockAst.FindAll($Predicate, $True)

 
The second parameter of the FindAll() method ($True) tells it to search recursively in nested elements.

Now, for any violation of our rule, we need to create an object of the type [Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord], because PSScriptAnalyzer expects our function to return an array of object(s) of that specific type :

Foreach ($Violation in $Violations) {

    $Result = New-Object `
            -Typename "Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord" `
            -ArgumentList "$((Get-Help $MyInvocation.MyCommand.Name).Description.Text)",$Violation.Extent,$PSCmdlet.MyInvocation.InvocationName,Information,$Null
          
    $Results += $Result
}

 
Pay particular attention to the 5 values passed to the -ArgumentList parameter of the cmdlet New-Object. To see what each of these values correspond to, we can have a look at the constructor(s) for this class :

C:\> [Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord]::new

OverloadDefinitions
-------------------
Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord new()
Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord new(string message,
System.Management.Automation.Language.IScriptExtent extent, string ruleName,
Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticSeverity severity, string scriptName, string ruleId)

 
For the “Message” property of our [DiagnosticRecord] objects, hard-coding a relatively long message would not look nice, so here, we are reusing our carefully crafted description from the comment-based help. We don’t have to do this, but that way, we don’t reinvent the wheel.

Then, each resulting object is added to an array : $Results.
Finally, when we are done processing violations, we return that array for PSScriptAnalyzer‘s consumption :

            }
            return $Results
            #endregion
        }

 
That’s it. The module containing the full function is on this GitHub page.

Now, let’s use our custom rule with PSScriptAnalyzer against an example script :

C:\> Invoke-ScriptAnalyzer -Path .\ExampleScript.ps1 -CustomRulePath .\MBAnalyzerRules.psm1 |
 Select-Object RuleName, Line, Message | Format-Table -AutoSize -Wrap

RuleName                           Line Message
--------                           ---- -------
MBAnalyzerRules\Measure-PascalCase   15 Variable names should use a consistent capitalization style, i.e. : PascalCase.
                                        In PascalCase, only the first letter is capitalized. Or, if the variable name
                                        is made of multiple concatenated words, only the first letter of each
                                        concatenated word is capitalized.
                                        To fix a violation of this rule, please consider using PascalCase for variable
                                        names.
MBAnalyzerRules\Measure-PascalCase   28 Variable names should use a consistent capitalization style, i.e. : PascalCase.
                                        In PascalCase, only the first letter is capitalized. Or, if the variable name
                                        is made of multiple concatenated words, only the first letter of each
                                        concatenated word is capitalized.
                                        To fix a violation of this rule, please consider using PascalCase for variable
                                        names.
MBAnalyzerRules\Measure-PascalCase   86 Variable names should use a consistent capitalization style, i.e. : PascalCase.
                                        In PascalCase, only the first letter is capitalized. Or, if the variable name
                                        is made of multiple concatenated words, only the first letter of each
                                        concatenated word is capitalized.
                                        To fix a violation of this rule, please consider using PascalCase for variable
                                        names.
MBAnalyzerRules\Measure-PascalCase   88 Variable names should use a consistent capitalization style, i.e. : PascalCase.
                                        In PascalCase, only the first letter is capitalized. Or, if the variable name
                                        is made of multiple concatenated words, only the first letter of each
                                        concatenated word is capitalized.
                                        To fix a violation of this rule, please consider using PascalCase for variable
                                        names.

 
That’s cool, but we probably want to see the actual variable names which are not following our desired capitalization style. We can obtain this information like so :

VariableNames
 
We can see that in the case of this script (pun intended), the case of variable names is all over the place, and we can easily go and fix it.

Adding ConfigurationData dynamically from a DSC configuration

When writing a DSC configuration, separating the environmental data from the DSC configuration is a best practice : it allows to reuse the same configuration logic for different environments, for example the Dev, QA and Production environments . This generally means that the environment data is stored in separate .psd1 files. This is explained in this documentation page.

However, these configuration data files are relatively static, so if the environment changes frequently these files might end up containing outdated information. A solution is to keep the static environment data in the configuration data files and then adding the more dynamic data on the fly from the DSC configuration itself.

A good example of this use case is a web application, where the configuration is identical for all web servers but these servers are treated not as pets but as cattle : we create and kill them on a daily basis. Because they are cattle, we don’t call them by their name, in fact we don’t even know their name. So the configuration data file doesn’t contain any node names :

@{
    # Node specific data
    AllNodes = @(

       # All the Web Servers have following information 
       @{
            NodeName           = '*'
            WebsiteName        = 'ClickFire'
            SourcePath         = '\\DevBox\SiteContents\'
            DestinationPath    = 'C:\inetpub\wwwroot\ClickFire_Content'
            DefaultWebSitePath = 'C:\inetpub\wwwroot\ClickFire_Content'
       }
    );
    NonNodeData = ''
}

 
By the way, the web application used for illustration purposes is an internal HR app, codenamed “Project ClickFire”.

Let’s assume the above configuration data is all the information we need to configure our nodes. That’s great, but we still need some node names, otherwise there will be no MOF file generated when we run the configuration. So we’ll need the query some kind of database to get the names of the web servers for this application, Active Directory for example. This is easy to do, especially if these servers are all in the same OU and/or there is a naming convention for them :

C:\> $DynamicNodeNames = Get-ADComputer -SearchBase "OU=Project ClickFire,OU=Servers,DC=Mat,DC=lab" -Filter {Name -Like "Web*"} |
Select-Object -ExpandProperty Name

C:\> $DynamicNodeNames

Web083
Web084
Web086
  

 
Now that we have the node names, we need to add a hashtable for each node into the “AllNodes” section of our configuration data. To do that, we first need to import the data from the configuration data file and we store it into a variable for further manipulation. There is a new cmdlet introduced in PowerShell 5.0 which makes this very simple : Import-PowerShellDataFile :

C:\> $EnvironmentData = Import-PowerShellDataFile -Path "C:\Lab\EnvironmentData\Project_ClickFire.psd1"
C:\> $EnvironmentData

Name                           Value
----                           -----
AllNodes                       {System.Collections.Hashtable}
NonNodeData


C:\> $EnvironmentData.AllNodes

Name                           Value
----                           -----
DefaultWebSitePath             C:\inetpub\wwwroot\ClickFire_Content
NodeName                       *
WebsiteName                    ClickFire
DestinationPath                C:\inetpub\wwwroot\ClickFire_Content
SourcePath                     \\DevBox\SiteContents\
  

 
Now, we have our configuration available to us as a PowerShell object (a hashtable) and the “AllNodes” section inside of it is also a hashtable. More accurately, the “AllNodes” section is an array of Hashtables because each node entry within “AllNodes” is a hashtable :

C:\> $EnvironmentData.AllNodes.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array


C:\> $EnvironmentData.AllNodes | Get-Member | Select-Object TypeName -Unique

TypeName
--------
System.Collections.Hashtable
  

 
So now, what we need to do is to inject a new node entry for each node returned by our Active Directory query into the “AllNodes” section :

C:\> Foreach ( $DynamicNodeName in $DynamicNodeNames ) {
     $EnvironmentData.AllNodes += @{NodeName = $DynamicNodeName; Role = "WebServer"}
 }
  

 
For each node name, we add a new hashtable into “AllNodes”. These hashtables are pretty simple in this case, this is just to give our nodes a name and a role (in case we need to differentiate with other server types, like database servers for example).

The result of this updated configuration data is equivalent to :

@{
    # Node specific data
    AllNodes = @(

       # All the Web Servers have following information 
       @{
            NodeName           = '*'
            WebsiteName        = 'ClickFire'
            SourcePath         = '\\DevBox\SiteContents\'
            DestinationPath    = 'C:\inetpub\wwwroot\ClickFire_Content'
            DefaultWebSitePath = 'C:\inetpub\wwwroot\ClickFire_Content'
       }
       @{
            NodeName           = 'Web083'
            Role               = 'WebServer'
       }
       @{
            NodeName           = 'Web084'
            Role               = 'WebServer'
       }
       @{
            NodeName           = 'Web086'
            Role               = 'WebServer'
       }
    );
    NonNodeData = ''
}

 
So that’s it for the node data, but what if we need to add non-node data ?
It is very similar to the node data because the “NonNodeData” section of the configuration data is also a hashtable.

Let’s say we want to add a piece of XML data that may be used for the web.config file of our web servers to the “NonNodeData” section of the configuration data. We could do that in the configuration data file, right :

@{
    # Node specific data
    AllNodes = @(

       # All the Web Servers have following information 
       @{
            NodeName           = '*'
            WebsiteName        = 'ClickFire'
            SourcePath         = '\\DevBox\SiteContents\'
            DestinationPath    = 'C:\inetpub\wwwroot\ClickFire_Content'
            DefaultWebSitePath = 'C:\inetpub\wwwroot\ClickFire_Content'
       }
    );
    NonNodeData =
    @{
        DynamicConfig = [Xml](Get-Content -Path C:\Lab\SiteContents\web.config)
    }
}

Nope :

SafeGetValueErrorNew
 
This is because to safely import data from a file, the cmdlet Import-PowerShellDataFile kinda works in RestrictedLanguage mode. This means that executing cmdlets, or functions, or any type of command is not allowed in a data file. Even the XML type and a bunch of other things are not allowed in this mode. For more information : about_Language_Modes.

It does make sense : data files should contain data, not code.

OK, so we’ll do that from the DSC configuration script, then :

C:\> $DynamicConfig = [Xml](Get-Content -Path "\\DevBox\SiteContents\web.config")
C:\> $DynamicConfig

xml                            configuration
---                            -------------
version="1.0" encoding="UTF-8" configuration


C:\> $EnvironmentData.NonNodeData = @{DynamicConfig = $DynamicConfig}
C:\>
C:\> $EnvironmentData.NonNodeData.DynamicConfig.configuration


configSections      : configSections
managementOdata     : managementOdata
appSettings         : appSettings
system.web          : system.web
system.serviceModel : system.serviceModel
system.webServer    : system.webServer
runtime             : runtime
  

 
With this technique, we can put whatever we want in “NonNodeData”, even XML data, as long as it is wrapped in a hashtable. The last command shows that we can easily access this dynamic config data because it is stored as a tidy [Xml] PowerShell object.

Please note that the Active Directory query, the import of the configuration data and the manipulation of this data are all done in the same script as the DSC configuration but outside of the DSC configuration itself. That way, this modified configuration data can be passed to the DSC configuration as the value of its -ConfigurationData parameter.

Putting it all together, here is what the whole DSC configuration script looks like :

configuration Project_ClickFire
{
    Import-DscResource -Module PSDesiredStateConfiguration
    Import-DscResource -Module xWebAdministration
    
    Node $AllNodes.Where{$_.Role -eq "WebServer"}.NodeName
    {
        WindowsFeature IIS
        {
            Ensure          = "Present"
            Name            = "Web-Server"
        }
        File SiteContent
        {
            Ensure          = "Present"
            SourcePath      = $Node.SourcePath
            DestinationPath = $Node.DestinationPath
            Recurse         = $True
            Type            = "Directory"
            DependsOn       = "[WindowsFeature]IIS"
        }        
        xWebsite Project_ClickFire_WebSite
        {
            Ensure          = "Present"
            Name            = $Node.WebsiteName
            State           = "Started"
            PhysicalPath    = $Node.DestinationPath
            DependsOn       = "[File]SiteContent"
        }
    }
}

# Adding dynamic Node data
$EnvironmentData = Import-PowerShellDataFile -Path "$PSScriptRoot\..\EnvironmentData\Project_ClickFire.psd1"
$DynamicNodeNames = (Get-ADComputer -SearchBase "OU=Project ClickFire,OU=Servers,DC=Mat,DC=lab" -Filter {Name -Like "Web*"}).Name

Foreach ( $DynamicNodeName in $DynamicNodeNames ) {
    $EnvironmentData.AllNodes += @{NodeName = $DynamicNodeName; Role = "WebServer"}
}

# Adding dynamic non-Node data
$DynamicConfig = [Xml](Get-Content -Path "\\DevBox\SiteContents\web.config")
$EnvironmentData.NonNodeData = @{DynamicConfig = $DynamicConfig}

Project_ClickFire -ConfigurationData $EnvironmentData -OutputPath "C:\Lab\DSCConfigs\Project_ClickFire"
  

 
Running this script indeed generates a MOF file for each of our nodes, containing the same settings :

C:\> & C:\Lab\DSCConfigs\Project_ClickFire_Config.ps1

    Directory: C:\Lab\DSCConfigs\Project_ClickFire


Mode                LastWriteTime         Length Name                                       
----                -------------         ------ ----                                       
-a----         6/6/2016   1:37 PM           3986 Web083.mof                                 
-a----         6/6/2016   1:37 PM           3986 Web084.mof                                 
-a----         6/6/2016   1:37 PM           3986 Web086.mof        
  

 
Hopefully, this helps treating web servers really as cattle and give its full meaning to the expression “server farm“.

Integrating PSScriptAnalyzer in an Appveyor Continuous Integration pipeline

Many of us who are writing PowerShell code are using the free (and awesome) Appveyor service for Continuous Integration (especially for personal projects). And most of us use this to run Pester tests. Automated testing is great, it allows to set a certain standard of code quality without slowing down code delivery. But, this is just checking that the code behaves as we intended to.

What about code consistency, style, readability and following best practices ?

This is where a static code analysis tool like PSScriptAnalyzer comes in. Even though PSScriptAnalyzer is a perfect fit in a PowerShell “build” process, searching the web for “integrating PSScriptAnalyzer and Appveyor” doesn’t yield very helpful results. So here is the solution I came up with :

version: 1.0.{build}

os: WMF 5

# Skip on updates to the readme
skip_commits:
  message: /readme*/
  
install:
  - ps: Install-PackageProvider -Name NuGet -Force
  - ps: Install-Module PsScriptAnalyzer -Force
  
build: false

test_script:
  - ps: |
      Add-AppveyorTest -Name "PsScriptAnalyzer" -Outcome Running
      $Results = Invoke-ScriptAnalyzer -Path $pwd -Recurse -Severity Error -ErrorAction SilentlyContinue
      If ($Results) {
        $ResultString = $Results | Out-String
        Write-Warning $ResultString
        Add-AppveyorMessage -Message "PSScriptAnalyzer output contained one or more result(s) with 'Error' severity.`
        Check the 'Tests' tab of this build for more details." -Category Error
        Update-AppveyorTest -Name "PsScriptAnalyzer" -Outcome Failed -ErrorMessage $ResultString
        
        # Failing the build
        Throw "Build failed"
      }
      Else {
        Update-AppveyorTest -Name "PsScriptAnalyzer" -Outcome Passed
      }

This the content of my appveyor.yml file, which is the file from which Appveyor gets the build configuration.

Line 3 : This indicates from which VM template the build agent will be deployed. As its name indicates, this allows to have a build agent running in a VM with PowerShell version 5. If you believe only what you can see, add $PSVersionTable in the appveyor.yml and check the result in the build console. PowerShell 5 means we can easily add PowerShell scripts, modules and DSC resources to our build agent from the PowerShell Gallery using PackageManagement.

Line 10-11 : This is exactly what we do here. But first, because the PowerShell Gallery relies on NuGet, we need to install the NuGet provider. Then, we can install any PowerShell module we want from the PowerShell Gallery, PsScriptAnalyzer in this case. We didn’t specify the repository because the PowerShell Gallery is the default one.

Line 13 : This refers specifically to MSBuild and we don’t need or want MSBuild for a PowerShell project.

Line 15-End : This is where all the PSScriptAnalyzer stuff goes. So from an Appveyor point of view, this will be a test. Even though static code analysis is not testing, it kinda makes sense : we are assessing the code against a set of rules which represent a certain standard and we want a “Pass” or a “Fail” depending on whether the code meets the standard or not.

Line 16 : In YAML, the pipe character “|” allows values to span multiple lines. This is very convenient for code blocks, like here. That way, we don’t need to add “- ps:” at the beginning of each line.

Line 17 : Appveyor doesn’t have a direct integration with PSScriptAnalyzer like it has for some testing frameworks (NUnit, MSTest, etc…) but it’s OK. The Appveyor worker (the actual build agent) provides a REST API and even a few PowerShell cmdlets leveraging this API. One of these cmdlets is Add-AppveyorTest. Using this cmdlet, we are adding a new test, giving it a name and telling the build agent that the test is in the “Running” state.

Line 18 : We run PSScriptAnalyzer against all the files in the current directory, recursively. We specify the “Error” severity to output only the violations of level “Error“, because we don’t want a violation of severity “Information” or even “Warning” to make the test fail. We store the result in a variable for later use.

Line 20 : If there are any “errors” from PSScriptAnalyzer perspective, we want to display them as a message in the build console and in the error message of the “test”. That’s why we need to convert the output object(s) from PSScriptAnalyzer to a string.

Line 21 : Writing the violation(s) to the build console. We could use Write-Host or Write-Output as well but as we’ll see in a later screenshot, the warning stream makes it stand out more visibly.

Line 22 : This Appveyor-specific cmdlet adds a message to the build’s “Messages” tab. Specifying “Error” for the category just displays the message with a touch of red on its left :

Appveyor Message fail
 
Line 24 : Update-AppveyorTest is another cmdlet leveraging the Appveyor build worker API. Here, we are using it to update the status of our existing test and add an error message to it. This message is PSScriptAnalyzer output converted to a string, so we can check the test message to see exactly what the problem is :

Appveyor Test fail
 

Line 27 : We need to use “Throw” to explicitly fail the build. Otherwise, the build is considered as succeeded, even if the “test” fails.

Line 30 : If PSScriptAnalyzer didn’t output anything, meaning if there were no violation of the “Error” severity in any file scanned by PSScriptAnalyzer, we considered that our project passes the test. Again, we use Update-AppveyorTest but this time, we tell it that the outcome of the “test” is a pass.

Now, let’s see how this looks like when we run a build :

Appveyor Build success
 
Not much output, because all is well. Also, the test is green :

Appveyor Test Success
 
Do you like watching “Fail” videos on Youtube ? If yes, you are probably dying to see my build fail, right ? So, here we go :

Appveyor Build fail
 
Wow, the yellow background of the warning stream is not elegant but it sure stands out !

Also, if you want to see the “Passing” Appveyor badge on the GitHub repository, head over THERE.

This is it.
PSScriptAnalyzer is an important tool that any PowerShell scripter should use. Appveyor is awesome, so combining both of these tools is pretty powerful.

Automating, learning, sharing