Tests/Invoke-PsScriptAnalyzer.tests.ps1
#$here = (Split-Path -Parent $MyInvocation.MyCommand.Path).Replace("tests", "") $scriptsModules = Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath "..") -Include *.psd1, *.psm1, *.ps1 -Exclude *.tests.ps1 -Recurse #$scriptsModules = Get-ChildItem $here -Include *.psd1, *.psm1, *.ps1 -Exclude *.tests.ps1 -Recurse Describe 'General - Testing all scripts and modules against the Script Analyzer Rules' -Tag 'PsScriptAnalyzer' { Context "Checking files to test exist and Invoke-ScriptAnalyzer cmdLet is available" { It "Checking files exist to test." { $scriptsModules.count | Should Not Be 0 } It "Checking Invoke-ScriptAnalyzer exists." { { Get-Command Invoke-ScriptAnalyzer -ErrorAction Stop } | Should Not Throw } } #$scriptAnalyzerRules = Get-ScriptAnalyzerRule -Severity @("Error") | Where-Object {@('PSAvoidUsingComputerNameHardcoded','PSDSCUseIdenticalParametersForDSC') -notcontains $_.RuleName} $scriptAnalyzerRules = Get-ScriptAnalyzerRule -Severity @("Error", "Warning") | Where-Object { @() -notcontains $_.RuleName} forEach ($scriptModule in $scriptsModules) { switch -wildCard ($scriptModule) { '*.psm1' { $typeTesting = 'Module' } '*.ps1' { $typeTesting = 'Script' } '*.psd1' { $typeTesting = 'Manifest' } } Context "Checking $typeTesting - $scriptModule - conforms to Script Analyzer Rules" { forEach ($scriptAnalyzerRule in $scriptAnalyzerRules) { It "Script Analyzer Rule $scriptAnalyzerRule" { #(Invoke-ScriptAnalyzer -Path $scriptModule -IncludeRule $scriptAnalyzerRule).count | Should Be 0 $analysis = (Invoke-ScriptAnalyzer -Path $scriptModule -IncludeRule $scriptAnalyzerRule ) $issues = 0 ForEach ($r in $analysis) { switch ($r.Severity) { 'Information' { $prefix = "##vso[task.logissue type=warning;]" } 'Warning' { $issues++ $prefix = "##vso[task.logissue type=warning;]" } 'Error' { $issues++ $prefix = "##vso[task.logissue type=error;]" } } Write-Host ("{0}Script:{1} on the line {2} column {3}" -f $prefix, $r.ScriptName, $r.Line, $r.Column) Write-Host ("{0}broken rule {1}: {2}" -f $prefix, $r.RuleName, $r.Message) Write-Host ("{0}Actual part of the code [{1}]" -f $prefix, $r.Extent.Text) Write-Host ("{0}Suggested solution [{1}]" -f $prefix, $r.SuggestedCorrections.Text) } $issues| Should Be 0 } } } } } |