-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInstall-VcfPatchScannerModule.ps1
More file actions
350 lines (298 loc) · 16.1 KB
/
Copy pathInstall-VcfPatchScannerModule.ps1
File metadata and controls
350 lines (298 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# Copyright (c) 2026 Broadcom. All Rights Reserved.
# Broadcom Confidential. The term "Broadcom" refers to Broadcom Inc.
# and/or its subsidiaries.
#
# =============================================================================
#
# SOFTWARE LICENSE AGREEMENT
#
# Copyright (c) CA, Inc. All rights reserved.
#
# You are hereby granted a non-exclusive, worldwide, royalty-free license
# under CA, Inc.'s copyrights to use, copy, modify, and distribute this
# software in source code or binary form for use in connection with CA, Inc.
# products.
#
# This copyright notice shall be included in all copies or substantial
# portions of the software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
# =============================================================================
#Requires -Version 7.4
<#
.SYNOPSIS
Manually installs the VcfPatchScanner PowerShell module cross-platform.
.DESCRIPTION
Copies VcfPatchScanner.psd1, VcfPatchScanner.psm1, Private, Data, and Tools into the
first path in $env:PSModulePath for the current platform (Windows, Linux, or macOS).
Validates the installed manifest before completing. Python __pycache__ directories are
excluded from the copy.
The module source is expected at $SourcePath/VcfPatchScanner/ (i.e. the VcfPatchScanner/
subdirectory of this script's directory when running directly from a cloned repository).
If the module is currently loaded in the session it is removed before the files are
overwritten and reloaded afterward, so the in-memory version matches what was just
installed.
Once installed to $env:PSModulePath, PowerShell auto-imports the module the first time
any of its commands is used in a session. No $PROFILE changes are needed.
IMPORTANT: Do not add 'Import-Module VcfPatchScanner' to $PROFILE. The module contains
multiple private implementation files and takes a noticeable time to load. Use
PowerShell's built-in auto-import instead — the module loads once on first use per
session.
If $PROFILE contains 'Import-Module VcfPatchScanner' from an earlier install, the
installer detects and offers to clean it up automatically.
Use -SkipProfileUpdate to suppress all profile checks for unattended installs.
Prerequisites are checked at install time and reported with pass/fail status.
The module files are copied regardless; imports may fail until all prerequisites are met.
- PowerShell 7.4 or newer (enforced by #Requires and verified at startup).
- VCF PowerCLI 9.0 or newer (VCF.PowerCLI module).
- Python 3.13 or newer (required by the web UI server).
- pwsh in PATH (required by the Python server to launch scan subprocesses).
.PARAMETER SkipProfileUpdate
When specified, skips all $PROFILE inspection and cleanup. Use for unattended
installs where profile changes are unwanted.
.PARAMETER SourcePath
Path to the directory containing the VcfPatchScanner module subdirectory. Defaults to
the directory containing this script ($PSScriptRoot), which is correct when running
directly from a cloned repository.
.EXAMPLE
.\Install-VcfPatchScannerModule.ps1
Installs from the script's own directory. Checks $PROFILE for any VcfPatchScanner
import lines that would slow shell startup and offers to remove them.
.EXAMPLE
.\Install-VcfPatchScannerModule.ps1 -SourcePath "~/Downloads/VcfPatchScanner-1.0.0"
Installs from a custom source directory.
.EXAMPLE
.\Install-VcfPatchScannerModule.ps1 -SkipProfileUpdate
Installs without inspecting or modifying $PROFILE (suitable for CI or scripted installs).
.NOTES
After installation, open a new shell and run 'Initialize-VcfPatchScanner' to set up
your working directory. PowerShell auto-imports the module on first use — no profile
line needed.
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $false)] [Switch]$SkipProfileUpdate,
[Parameter(Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$SourcePath = $PSScriptRoot
)
function Invoke-ProfileCleanup {
<#
.SYNOPSIS
Shows the user what will be removed from $PROFILE and prompts for confirmation.
.NOTES
Always previews what will be deleted before writing. If the cleaned content is
identical to the original (no match), the function skips without prompting.
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)] [AllowEmptyString()] [ValidateNotNull()] [String]$CleanedContent,
[Parameter(Mandatory = $true)] [AllowEmptyString()] [ValidateNotNull()] [String]$OriginalContent,
[Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$ProfilePath
)
if ($OriginalContent -eq $CleanedContent) {
Write-Host " (Nothing matched for removal — skipping to prevent unintended edits.)" -ForegroundColor Gray
return
}
# Show exactly which non-blank lines will disappear so the user can verify before confirming.
$originalLines = $OriginalContent -split "`n"
$cleanedLines = $CleanedContent -split "`n"
$removedLines = $originalLines | Where-Object { $cleanedLines -notcontains $_ -and -not [String]::IsNullOrWhiteSpace($_) }
if ($removedLines) {
Write-Host " Lines that will be removed:" -ForegroundColor DarkGray
$removedLines | ForEach-Object { Write-Host " $_" -ForegroundColor DarkGray }
Write-Host ""
}
$response = Read-Host "Remove it now? (Y/N, Enter=no)"
if ($response -match '^Y(es)?$') {
Set-Content -LiteralPath $ProfilePath -Encoding UTF8 -NoNewline -Value $CleanedContent
Write-Host " Removed. Shell startup is now fast." -ForegroundColor Green
}
}
function Invoke-PrerequisiteCheck {
<#
.SYNOPSIS
Checks all prerequisites required by VcfPatchScanner and reports pass/fail to the console.
.NOTES
Write-Host is the primary output mechanism in this function; all Write-Host calls are
intentional interactive console output. Returns the number of failed checks so the caller
can emit a summary warning.
#>
[CmdletBinding()]
[OutputType([Int])]
Param ()
Write-Host "Checking prerequisites..."
$failCount = 0
$pathHint = if ($IsWindows) { ' ($env:PATH)' } else { '' }
# PowerShell version — already enforced by #Requires above; shown for transparency.
$minPsVersion = [Version]"7.4"
if ($PSVersionTable.PSVersion -ge $minPsVersion) {
Write-Host (" [PASS] {0,-20}: {1}" -f "PowerShell 7.4+", $PSVersionTable.PSVersion) -ForegroundColor Green
} else {
Write-Host (" [FAIL] {0,-20}: {1} — 7.4 or later required" -f "PowerShell 7.4+", $PSVersionTable.PSVersion) -ForegroundColor Red
$failCount++
}
# VCF PowerCLI 9.0+ — required by all scanner inventory and discovery functions.
$minPowerCliVersion = [Version]"9.0"
$vcfMod = Get-Module -ListAvailable -Name 'VCF.PowerCLI' -ErrorAction SilentlyContinue |
Sort-Object -Property Version -Descending | Select-Object -First 1
if ($null -eq $vcfMod) {
Write-Host (" [FAIL] {0,-20}: not installed — download from Broadcom Support Portal" -f "VCF PowerCLI 9.0+") -ForegroundColor Red
$failCount++
} elseif ($vcfMod.Version -lt $minPowerCliVersion) {
Write-Host (" [FAIL] {0,-20}: {1} — 9.0 or later required" -f "VCF PowerCLI 9.0+", $vcfMod.Version) -ForegroundColor Red
$failCount++
} else {
Write-Host (" [PASS] {0,-20}: {1}" -f "VCF PowerCLI 9.0+", $vcfMod.Version) -ForegroundColor Green
}
# Python 3.13+ — required by the web UI server (Start-VCFPatchScannerServer.py).
$minPythonMinor = 13
$pythonCmd = Get-Command -Name python3 -ErrorAction SilentlyContinue
if ($null -eq $pythonCmd) {
$pythonCmd = Get-Command -Name python -ErrorAction SilentlyContinue
}
if ($null -eq $pythonCmd) {
Write-Host (" [FAIL] {0,-20}: not found — install from python.org and add to PATH$pathHint" -f "Python 3.13+") -ForegroundColor Red
$failCount++
} else {
try {
$versionOutput = & $pythonCmd.Source --version 2>&1
if ($versionOutput -match '^Python (\d+)\.(\d+)') {
$pyMajor = [Int]$Matches[1]
$pyMinor = [Int]$Matches[2]
$pyDisplayVer = if ($versionOutput -match 'Python (\S+)') { $Matches[1] } else { [String]$versionOutput }
if ($pyMajor -lt 3 -or ($pyMajor -eq 3 -and $pyMinor -lt $minPythonMinor)) {
Write-Host (" [FAIL] {0,-20}: {1} — 3.{2} or later required" -f "Python 3.13+", $pyDisplayVer, $minPythonMinor) -ForegroundColor Red
$failCount++
} else {
Write-Host (" [PASS] {0,-20}: {1}" -f "Python 3.13+", $pyDisplayVer) -ForegroundColor Green
}
} else {
Write-Host (" [WARN] {0,-20}: could not determine version from '{1}' — {2}" -f "Python 3.13+", $pythonCmd.Source, $versionOutput) -ForegroundColor Yellow
$failCount++
}
} catch {
Write-Host (" [FAIL] {0,-20}: error reading version at '{1}': {2}" -f "Python 3.13+", $pythonCmd.Source, $_.Exception.Message) -ForegroundColor Red
$failCount++
}
}
# pwsh — required by the Python server to launch scan subprocesses.
$pwshCmd = Get-Command -Name pwsh -ErrorAction SilentlyContinue
if ($null -eq $pwshCmd) {
Write-Host (" [FAIL] {0,-20}: not found — install PowerShell 7 and add to PATH$pathHint" -f "pwsh in PATH") -ForegroundColor Red
$failCount++
} else {
Write-Host (" [PASS] {0,-20}: {1}" -f "pwsh in PATH", $pwshCmd.Source) -ForegroundColor Green
}
return $failCount
}
$moduleSourcePath = Join-Path -Path $SourcePath -ChildPath "VcfPatchScanner"
$itemsToCopy = @("VcfPatchScanner.psd1", "VcfPatchScanner.psm1", "Private", "Data", "Tools")
Write-Host ""
Write-Host "VcfPatchScanner Module Installer" -ForegroundColor Cyan
Write-Host "=================================" -ForegroundColor Cyan
Write-Host ""
$prereqFailCount = Invoke-PrerequisiteCheck
if ($prereqFailCount -gt 0) {
Write-Host ""
Write-Host " $prereqFailCount prerequisite(s) not met. The module files will still be installed but" -ForegroundColor Yellow
Write-Host " some functionality requires all prerequisites to be satisfied." -ForegroundColor Yellow
}
Write-Host ""
try {
if (-not (Test-Path -Path $moduleSourcePath -PathType Container)) {
throw "Module source not found: $moduleSourcePath"
}
$pathSeparator = [System.IO.Path]::PathSeparator
$basePath = ($env:PSModulePath -split $pathSeparator)[0]
$installPath = Join-Path -Path $basePath -ChildPath "VcfPatchScanner"
Write-Host "Source : $moduleSourcePath"
Write-Host "Destination : $installPath"
Write-Host ""
# Unload the module if it is currently in the session so the files can be
# overwritten and the reloaded copy is consistent with what was just installed.
$loadedModule = Get-Module -Name "VcfPatchScanner" -ErrorAction SilentlyContinue
if ($null -ne $loadedModule) {
Write-Host "Unloading currently loaded module (version $($loadedModule.Version))..." -ForegroundColor Gray
Remove-Module -Name "VcfPatchScanner" -Force -ErrorAction Stop
}
if (-not (Test-Path -Path $installPath)) {
Write-Host "Creating module directory..." -ForegroundColor Gray
New-Item -Path $installPath -ItemType Directory -Force | Out-Null
}
foreach ($item in $itemsToCopy) {
$itemSource = Join-Path -Path $moduleSourcePath -ChildPath $item
if (-not (Test-Path -Path $itemSource)) {
Write-Host " [SKIP] $item — not found at source." -ForegroundColor Yellow
continue
}
Write-Host " Copying $item..." -ForegroundColor Gray
# Exclude Python bytecode cache directories that may exist in a development checkout.
Copy-Item -Path $itemSource -Destination $installPath -Recurse -Force -Exclude "__pycache__"
# Copy-Item -Exclude does not recurse into subdirectories; remove any copied __pycache__ explicitly.
Get-ChildItem -Path (Join-Path -Path $installPath -ChildPath $item) -Filter "__pycache__" -Recurse -Directory -ErrorAction SilentlyContinue |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
}
# Unblock all copied files on Windows so execution policy does not block the module
# after installation when the source was downloaded from the internet (ZIP or clone).
# Unblock-File is a no-op on macOS/Linux where Zone.Identifier streams do not exist.
Write-Host "Unblocking installed module files (Windows execution policy)..." -ForegroundColor Gray
Get-ChildItem -Path $installPath -Recurse -File -ErrorAction SilentlyContinue |
ForEach-Object { Unblock-File -Path $_.FullName -ErrorAction SilentlyContinue }
Write-Host ""
Write-Host "Validating module manifest..." -ForegroundColor Gray
$manifestPath = Join-Path -Path $installPath -ChildPath "VcfPatchScanner.psd1"
$null = Test-ModuleManifest -Path $manifestPath -ErrorAction Stop
# Reload the module into the current session so the caller can use it immediately
# without opening a new shell. Import errors are non-fatal — the files are on disk
# and the user can reload manually if a dependency like VCF.PowerCLI is absent.
Write-Host "Importing module into current session..." -ForegroundColor Gray
try {
Import-Module -Name $manifestPath -Force -ErrorAction Stop
$reloadedVersion = (Get-Module -Name "VcfPatchScanner").Version
Write-Host " Module loaded (version $reloadedVersion)." -ForegroundColor Gray
} catch {
Write-Host " Import skipped: $($_.Exception.Message)" -ForegroundColor Yellow
Write-Host " Run 'Import-Module VcfPatchScanner' manually once all prerequisites are met." -ForegroundColor Yellow
}
# Check $PROFILE for any VcfPatchScanner entries that would slow shell startup.
# The installer never writes to $PROFILE — PowerShell auto-imports the module on first
# command use. Detect eager-load lines added by hand or earlier tooling.
$eagerProfileLine = "Import-Module VcfPatchScanner"
if (-not $SkipProfileUpdate) {
$profileContent = if (Test-Path -LiteralPath $PROFILE) {
Get-Content -LiteralPath $PROFILE -Raw -ErrorAction SilentlyContinue
} else {
""
}
$hasEagerLine = $profileContent -match "(?m)^\s*$([regex]::Escape($eagerProfileLine))\s*$"
if ($hasEagerLine) {
Write-Host ""
Write-Host "Profile warning" -ForegroundColor Yellow
Write-Host " $PROFILE contains 'Import-Module VcfPatchScanner'." -ForegroundColor Yellow
Write-Host " This adds startup latency to every new shell. PowerShell auto-imports the" -ForegroundColor Yellow
Write-Host " module on first use without any profile entry — the line is not needed." -ForegroundColor Yellow
Write-Host ""
$cleanedContent = ($profileContent -replace "(?m)^\s*# VcfPatchScanner[^\n]*\r?\n?", "") `
-replace "(?m)^\s*$([regex]::Escape($eagerProfileLine))\r?\n?", ""
Invoke-ProfileCleanup -ProfilePath $PROFILE -OriginalContent $profileContent -CleanedContent $cleanedContent
} else {
Write-Host ""
Write-Host " No profile changes needed — Initialize-VcfPatchScanner auto-loads on first use." -ForegroundColor Green
}
}
Write-Host ""
Write-Host "Installation complete." -ForegroundColor Green
Write-Host " Initialize-VcfPatchScanner" -ForegroundColor Green
Write-Host ""
}
catch {
Write-Host ""
Write-Host "Installation failed: $($_.Exception.Message)" -ForegroundColor Red
throw
}