microsoft/hve-core

Public

mirrored from https://github.com/microsoft/hve-coreAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
hve-core-v2.3.7

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

scripts/linting/Invoke-PSScriptAnalyzer.ps1

201lines · modeblame

66be1367Bill Berry7 months ago1#!/usr/bin/env pwsh
d19c9b3alittleKitchen5 months ago2# Copyright (c) Microsoft Corporation.
3# SPDX-License-Identifier: MIT
66be1367Bill Berry7 months ago4#
5# Invoke-PSScriptAnalyzer.ps1
6#
7# Purpose: Wrapper for PSScriptAnalyzer with GitHub Actions integration
8# Author: HVE Core Team
9
6e262826little Kitchen5 months ago10#Requires -Version 7.0
11
66be1367Bill Berry7 months ago12[CmdletBinding()]
13param(
14[Parameter(Mandatory = $false)]
15[switch]$ChangedFilesOnly,
16
17[Parameter(Mandatory = $false)]
18[string]$BaseBranch = "origin/main",
19
20[Parameter(Mandatory = $false)]
21[string]$ConfigPath = (Join-Path $PSScriptRoot "PSScriptAnalyzer.psd1"),
22
23[Parameter(Mandatory = $false)]
24[string]$OutputPath = "logs/psscriptanalyzer-results.json"
25)
26
6e262826little Kitchen5 months ago27$ErrorActionPreference = 'Stop'
28
66be1367Bill Berry7 months ago29# Import shared helpers
30Import-Module (Join-Path $PSScriptRoot "Modules/LintingHelpers.psm1") -Force
fdd75ed7Bill Berry5 months ago31Import-Module (Join-Path $PSScriptRoot "../lib/Modules/CIHelpers.psm1") -Force
66be1367Bill Berry7 months ago32
6b84a8e4Bill Berry4 months ago33#region Functions
66be1367Bill Berry7 months ago34
6b84a8e4Bill Berry4 months ago35function Invoke-PSScriptAnalyzerCore {
36[CmdletBinding()]
37[OutputType([void])]
38param(
39[Parameter(Mandatory = $false)]
40[switch]$ChangedFilesOnly,
66be1367Bill Berry7 months ago41
6b84a8e4Bill Berry4 months ago42[Parameter(Mandatory = $false)]
43[string]$BaseBranch = "origin/main",
66be1367Bill Berry7 months ago44
6b84a8e4Bill Berry4 months ago45[Parameter(Mandatory = $false)]
46[string]$ConfigPath = (Join-Path $PSScriptRoot "PSScriptAnalyzer.psd1"),
66be1367Bill Berry7 months ago47
6b84a8e4Bill Berry4 months ago48[Parameter(Mandatory = $false)]
49[string]$OutputPath = "logs/psscriptanalyzer-results.json"
50)
66be1367Bill Berry7 months ago51
6b84a8e4Bill Berry4 months ago52Write-Host "🔍 Running PSScriptAnalyzer..." -ForegroundColor Cyan
66be1367Bill Berry7 months ago53
6b84a8e4Bill Berry4 months ago54# Ensure PSScriptAnalyzer is available
55if (-not (Get-Module -ListAvailable -Name PSScriptAnalyzer)) {
56Write-Host "Installing PSScriptAnalyzer module..." -ForegroundColor Yellow
57Install-Module -Name PSScriptAnalyzer -Force -Scope CurrentUser -Repository PSGallery
58}
59
60Import-Module PSScriptAnalyzer
61
62# Get files to analyze
63$filesToAnalyze = @()
64
65if ($ChangedFilesOnly) {
66Write-Host "Detecting changed PowerShell files..." -ForegroundColor Cyan
67$filesToAnalyze = @(Get-ChangedFilesFromGit -BaseBranch $BaseBranch -FileExtensions @('*.ps1', '*.psm1', '*.psd1'))
68}
69else {
70Write-Host "Analyzing all PowerShell files..." -ForegroundColor Cyan
71$gitignorePath = Join-Path (git rev-parse --show-toplevel 2>$null) ".gitignore"
72$filesToAnalyze = @(Get-FilesRecursive -Path "." -Include @('*.ps1', '*.psm1', '*.psd1') -GitIgnorePath $gitignorePath)
73}
74
75if (@($filesToAnalyze).Count -eq 0) {
76Write-Host "✅ No PowerShell files to analyze" -ForegroundColor Green
77Set-CIOutput -Name "count" -Value "0"
78Set-CIOutput -Name "issues" -Value "0"
79return
80}
81
82Write-Host "Analyzing $($filesToAnalyze.Count) PowerShell files..." -ForegroundColor Cyan
83Set-CIOutput -Name "count" -Value $filesToAnalyze.Count
66be1367Bill Berry7 months ago84
35c44178o75 months ago85# Run PSScriptAnalyzer
86$allResults = @()
87$hasErrors = $false
88
89foreach ($file in $filesToAnalyze) {
90$filePath = if ($file -is [System.IO.FileInfo]) { $file.FullName } else { $file }
91Write-Host "`n📄 Analyzing: $filePath" -ForegroundColor Cyan
66be1367Bill Berry7 months ago92
35c44178o75 months ago93$results = Invoke-ScriptAnalyzer -Path $filePath -Settings $ConfigPath
94
95if ($results) {
96$allResults += $results
66be1367Bill Berry7 months ago97
35c44178o75 months ago98foreach ($result in $results) {
3587e6abBill Berry5 months ago99$annotationLevel = switch ($result.Severity) {
100'Error' { 'Error' }
101'Warning' { 'Warning' }
102'Information' { 'Notice' }
103default { 'Notice' }
104}
105
106Write-CIAnnotation `
35c44178o75 months ago107-Message "$($result.RuleName): $($result.Message)" `
3587e6abBill Berry5 months ago108-Level $annotationLevel `
35c44178o75 months ago109-File $filePath `
110-Line $result.Line `
111-Column $result.Column
112
113$icon = switch ($result.Severity) {
114'Error' { '❌'; $hasErrors = $true }
115'Warning' { '⚠️' }
116default { 'ℹ️' }
117}
118
119Write-Host " $icon [$($result.Severity)] $($result.RuleName): $($result.Message) (Line $($result.Line))" -ForegroundColor $(
120if ($result.Severity -eq 'Error') { 'Red' }
121elseif ($result.Severity -eq 'Warning') { 'Yellow' }
122else { 'Cyan' }
123)
66be1367Bill Berry7 months ago124}
35c44178o75 months ago125}
126else {
127Write-Host " ✅ No issues found" -ForegroundColor Green
66be1367Bill Berry7 months ago128}
129}
130
35c44178o75 months ago131# Export results
132$summary = @{
de43e73eKatrien De Graeve5 months ago133TotalFiles = @($filesToAnalyze).Count
134TotalIssues = @($allResults).Count
135Errors = @($allResults | Where-Object Severity -eq 'Error').Count
136Warnings = @($allResults | Where-Object Severity -eq 'Warning').Count
137Information = @($allResults | Where-Object Severity -eq 'Information').Count
35c44178o75 months ago138HasErrors = $hasErrors
139}
66be1367Bill Berry7 months ago140
67585f5aAndrew Vineyard4 months ago141# Ensure logs directory exists
142$logsDir = Split-Path $OutputPath -Parent
143if (-not (Test-Path $logsDir)) {
144New-Item -ItemType Directory -Force -Path $logsDir | Out-Null
145}
146
35c44178o75 months ago147$allResults | ConvertTo-Json -Depth 5 | Out-File $OutputPath
67585f5aAndrew Vineyard4 months ago148$summary | ConvertTo-Json | Out-File (Join-Path $logsDir "psscriptanalyzer-summary.json")
66be1367Bill Berry7 months ago149
35c44178o75 months ago150# Set outputs
3587e6abBill Berry5 months ago151Set-CIOutput -Name "issues" -Value $summary.TotalIssues
152Set-CIOutput -Name "errors" -Value $summary.Errors
153Set-CIOutput -Name "warnings" -Value $summary.Warnings
66be1367Bill Berry7 months ago154
35c44178o75 months ago155if ($hasErrors) {
3587e6abBill Berry5 months ago156Set-CIEnv -Name "PSSCRIPTANALYZER_FAILED" -Value "true"
35c44178o75 months ago157}
66be1367Bill Berry7 months ago158
35c44178o75 months ago159# Write summary
3587e6abBill Berry5 months ago160Write-CIStepSummary -Content "## PSScriptAnalyzer Results`n"
66be1367Bill Berry7 months ago161
35c44178o75 months ago162if ($summary.TotalIssues -eq 0) {
3587e6abBill Berry5 months ago163Write-CIStepSummary -Content "✅ **Status**: Passed`n`nAll $($summary.TotalFiles) PowerShell files passed linting checks."
35c44178o75 months ago164Write-Host "`n✅ All PowerShell files passed PSScriptAnalyzer checks!" -ForegroundColor Green
6b84a8e4Bill Berry4 months ago165return
35c44178o75 months ago166}
167else {
3587e6abBill Berry5 months ago168Write-CIStepSummary -Content @"
66be1367Bill Berry7 months ago169❌ **Status**: Failed
170
171| Metric | Count |
172|--------|-------|
173| Files Analyzed | $($summary.TotalFiles) |
174| Total Issues | $($summary.TotalIssues) |
175| Errors | $($summary.Errors) |
176| Warnings | $($summary.Warnings) |
177| Information | $($summary.Information) |
178"@
179
35c44178o75 months ago180Write-Host "`n❌ PSScriptAnalyzer found $($summary.TotalIssues) issue(s)" -ForegroundColor Red
6b84a8e4Bill Berry4 months ago181throw "PSScriptAnalyzer found $($summary.TotalIssues) issue(s)"
35c44178o75 months ago182}
183}
6b84a8e4Bill Berry4 months ago184
185#endregion Functions
186
187#region Main Execution
188
189if ($MyInvocation.InvocationName -ne '.') {
190try {
191Invoke-PSScriptAnalyzerCore -ChangedFilesOnly:$ChangedFilesOnly -BaseBranch $BaseBranch -ConfigPath $ConfigPath -OutputPath $OutputPath
192exit 0
193}
194catch {
195Write-Error -ErrorAction Continue "PSScriptAnalyzer failed: $($_.Exception.Message)"
196Write-CIAnnotation -Message $_.Exception.Message -Level Error
197exit 1
198}
66be1367Bill Berry7 months ago199}
6b84a8e4Bill Berry4 months ago200
201#endregion Main Execution