-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGet-AzModules.ps1
81 lines (73 loc) · 2.59 KB
/
Get-AzModules.ps1
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
[OutputType([array])]
[CmdletBinding()]
param (
[Parameter(Mandatory, HelpMessage = 'Path to a Powershell file (.ps1 or .psm1) using Az cmdlets')]
[ValidateScript( { Test-Path $_ })]
[string]
$Path,
[Parameter(HelpMessage = 'Prefix for the module used. Must match the prefix used in commandlets for the module. Defaults to "Az".')]
[string]
$Prefix = 'Az',
[Parameter(HelpMessage = 'Check installed versions of used modules compared to latest')]
[Switch]
$CheckVersions
)
## Input validation
$file = Get-Item $Path
if ($file.Extension -notin '.ps1', '.psm1') {
Write-Error "$($file.Name) is not a powershell file"
return $null
}
Write-Host "Looking for $Prefix modules needed for $($file.Name)..."
## Identify all cmdlets used
$content = Get-Content -Path $Path -Raw
$allMatches = $content | Select-String -Pattern "\w+-$Prefix\w+" -AllMatches
$uniqueCmdlets = $allMatches.Matches.Value | Select-Object -Unique
$modules = @()
if ($uniqueCmdlets.Count -eq 0) {
Write-Host "No $Prefix cmdlets found"
return $null
}
else {
Write-Host "Number of unique $Prefix cmdlets found: $($uniqueCmdlets.Count)"
}
## Find all modules used
foreach ($cmdlet in $uniqueCmdlets) {
$found = Get-Command $cmdlet -ErrorAction:SilentlyContinue
if (!$found) {
$remoteCmdlet = Find-Command $cmdlet
if ($remoteCmdlet) {
Write-Warning "$cmdlet was not found. Available in module $($remoteCmdlet.ModuleName) [$($remoteCmdlet.Version)] from $($remoteCmdlet.Repository)"
$module = $remoteCmdlet.ModuleName
}
else {
Write-Warning "$cmdlet was not found in an installed module"
}
}
else {
$module = (Get-Command $cmdlet).Source
}
Write-Verbose "$cmdlet uses $module"
if ($module -notin $modules) {
$modules += $module
}
}
Write-Host "Number of $Prefix modules used: $($modules.Count)"
$modulesWithVersion = @()
## Optional: Check versions of installed modules
if ($CheckVersions) {
foreach ($module in $modules) {
$installedVer = (Get-Module $module -ListAvailable).Version
$latestVer = (Find-Module $module).Version
if ($installedVer -and ($latestVer -gt $installedVer)) {
Write-Warning "$($module): latest version [$latestVer] newer than installed version [$installedVer]"
}
$modulesWithVersion += [PSCustomObject]@{
Name = $module
InstalledVersion = $installedVer
LatestVersion = $latestVer
}
}
return $modulesWithVersion | Sort-Object -Property Name
}
return $modules | Sort-Object