microsoft/hve-core

Public

mirrored fromhttps://github.com/microsoft/hve-coreAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
hve-core-v2.3.6

Branches

Tags

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

Clone

HTTPS

Download ZIP

scripts/linting/Invoke-PSScriptAnalyzer.ps1

201lines Ā· modecode

1#!/usr/bin/env pwsh
2# Copyright (c) Microsoft Corporation.
3# SPDX-License-Identifier: MIT
4#
5# Invoke-PSScriptAnalyzer.ps1
6#
7# Purpose: Wrapper for PSScriptAnalyzer with GitHub Actions integration
8# Author: HVE Core Team
9
10#Requires -Version 7.0
11
12[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
27$ErrorActionPreference = 'Stop'
28
29# Import shared helpers
30Import-Module (Join-Path $PSScriptRoot "Modules/LintingHelpers.psm1") -Force
31Import-Module (Join-Path $PSScriptRoot "../lib/Modules/CIHelpers.psm1") -Force
32
33#region Functions
34
35function Invoke-PSScriptAnalyzerCore {
36 [CmdletBinding()]
37 [OutputType([void])]
38 param(
39 [Parameter(Mandatory = $false)]
40 [switch]$ChangedFilesOnly,
41
42 [Parameter(Mandatory = $false)]
43 [string]$BaseBranch = "origin/main",
44
45 [Parameter(Mandatory = $false)]
46 [string]$ConfigPath = (Join-Path $PSScriptRoot "PSScriptAnalyzer.psd1"),
47
48 [Parameter(Mandatory = $false)]
49 [string]$OutputPath = "logs/psscriptanalyzer-results.json"
50 )
51
52 Write-Host "šŸ” Running PSScriptAnalyzer..." -ForegroundColor Cyan
53
54 # Ensure PSScriptAnalyzer is available
55 if (-not (Get-Module -ListAvailable -Name PSScriptAnalyzer)) {
56 Write-Host "Installing PSScriptAnalyzer module..." -ForegroundColor Yellow
57 Install-Module -Name PSScriptAnalyzer -Force -Scope CurrentUser -Repository PSGallery
58 }
59
60 Import-Module PSScriptAnalyzer
61
62 # Get files to analyze
63 $filesToAnalyze = @()
64
65 if ($ChangedFilesOnly) {
66 Write-Host "Detecting changed PowerShell files..." -ForegroundColor Cyan
67 $filesToAnalyze = @(Get-ChangedFilesFromGit -BaseBranch $BaseBranch -FileExtensions @('*.ps1', '*.psm1', '*.psd1'))
68 }
69 else {
70 Write-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
75 if (@($filesToAnalyze).Count -eq 0) {
76 Write-Host "āœ… No PowerShell files to analyze" -ForegroundColor Green
77 Set-CIOutput -Name "count" -Value "0"
78 Set-CIOutput -Name "issues" -Value "0"
79 return
80 }
81
82 Write-Host "Analyzing $($filesToAnalyze.Count) PowerShell files..." -ForegroundColor Cyan
83 Set-CIOutput -Name "count" -Value $filesToAnalyze.Count
84
85 # Run PSScriptAnalyzer
86 $allResults = @()
87 $hasErrors = $false
88
89 foreach ($file in $filesToAnalyze) {
90 $filePath = if ($file -is [System.IO.FileInfo]) { $file.FullName } else { $file }
91 Write-Host "`nšŸ“„ Analyzing: $filePath" -ForegroundColor Cyan
92
93 $results = Invoke-ScriptAnalyzer -Path $filePath -Settings $ConfigPath
94
95 if ($results) {
96 $allResults += $results
97
98 foreach ($result in $results) {
99 $annotationLevel = switch ($result.Severity) {
100 'Error' { 'Error' }
101 'Warning' { 'Warning' }
102 'Information' { 'Notice' }
103 default { 'Notice' }
104 }
105
106 Write-CIAnnotation `
107 -Message "$($result.RuleName): $($result.Message)" `
108 -Level $annotationLevel `
109 -File $filePath `
110 -Line $result.Line `
111 -Column $result.Column
112
113 $icon = switch ($result.Severity) {
114 'Error' { 'āŒ'; $hasErrors = $true }
115 'Warning' { 'āš ļø' }
116 default { 'ā„¹ļø' }
117 }
118
119 Write-Host " $icon [$($result.Severity)] $($result.RuleName): $($result.Message) (Line $($result.Line))" -ForegroundColor $(
120 if ($result.Severity -eq 'Error') { 'Red' }
121 elseif ($result.Severity -eq 'Warning') { 'Yellow' }
122 else { 'Cyan' }
123 )
124 }
125 }
126 else {
127 Write-Host " āœ… No issues found" -ForegroundColor Green
128 }
129 }
130
131 # Export results
132 $summary = @{
133 TotalFiles = @($filesToAnalyze).Count
134 TotalIssues = @($allResults).Count
135 Errors = @($allResults | Where-Object Severity -eq 'Error').Count
136 Warnings = @($allResults | Where-Object Severity -eq 'Warning').Count
137 Information = @($allResults | Where-Object Severity -eq 'Information').Count
138 HasErrors = $hasErrors
139 }
140
141 # Ensure logs directory exists
142 $logsDir = Split-Path $OutputPath -Parent
143 if (-not (Test-Path $logsDir)) {
144 New-Item -ItemType Directory -Force -Path $logsDir | Out-Null
145 }
146
147 $allResults | ConvertTo-Json -Depth 5 | Out-File $OutputPath
148 $summary | ConvertTo-Json | Out-File (Join-Path $logsDir "psscriptanalyzer-summary.json")
149
150 # Set outputs
151 Set-CIOutput -Name "issues" -Value $summary.TotalIssues
152 Set-CIOutput -Name "errors" -Value $summary.Errors
153 Set-CIOutput -Name "warnings" -Value $summary.Warnings
154
155 if ($hasErrors) {
156 Set-CIEnv -Name "PSSCRIPTANALYZER_FAILED" -Value "true"
157 }
158
159 # Write summary
160 Write-CIStepSummary -Content "## PSScriptAnalyzer Results`n"
161
162 if ($summary.TotalIssues -eq 0) {
163 Write-CIStepSummary -Content "āœ… **Status**: Passed`n`nAll $($summary.TotalFiles) PowerShell files passed linting checks."
164 Write-Host "`nāœ… All PowerShell files passed PSScriptAnalyzer checks!" -ForegroundColor Green
165 return
166 }
167 else {
168 Write-CIStepSummary -Content @"
169āŒ **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
180 Write-Host "`nāŒ PSScriptAnalyzer found $($summary.TotalIssues) issue(s)" -ForegroundColor Red
181 throw "PSScriptAnalyzer found $($summary.TotalIssues) issue(s)"
182 }
183}
184
185#endregion Functions
186
187#region Main Execution
188
189if ($MyInvocation.InvocationName -ne '.') {
190 try {
191 Invoke-PSScriptAnalyzerCore -ChangedFilesOnly:$ChangedFilesOnly -BaseBranch $BaseBranch -ConfigPath $ConfigPath -OutputPath $OutputPath
192 exit 0
193 }
194 catch {
195 Write-Error -ErrorAction Continue "PSScriptAnalyzer failed: $($_.Exception.Message)"
196 Write-CIAnnotation -Message $_.Exception.Message -Level Error
197 exit 1
198 }
199}
200
201#endregion Main Execution