functions/Assert-Module.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
82
83
84
85
86
87
88
89
90
91
92
93
94
# <copyright file="Assert-Module.ps1" company="Endjin Limited">
# Copyright (c) Endjin Limited. All rights reserved.
# </copyright>

<#
.SYNOPSIS
Ensures that the specfied module is available.

.DESCRIPTION
Checks the presence of the specfied module version, installing it if necessary.

.PARAMETER Name
The module name.

.PARAMETER Version
The module version.

.PARAMETER AdditionalArgs
Any additional 'Install-Module' arguments required by the module (e.g. -AcceptLicense)

.PARAMETER DoNotInstall
Suppresses the auto-install behaviour

.PARAMETER Scope
Sets the installation scope of the module.

.PARAMETER PSRepository
Sets the PowerShell repository used as the source (e.g. PSGallery)

.OUTPUTS
Returns the 'PSModuleInfo' object for the asserted module - this can be used by the caller to easily import the module.

#>

function Assert-Module
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$True)]
        [string] $Name,

        [Parameter()]
        [string] $Version = "Latest",

        [Parameter()]
        [hashtable] $AdditionalArgs,

        [Parameter()]
        [switch] $DoNotInstall,

        [Parameter()]
        [string] $Scope = "CurrentUser",

        [Parameter()]
        [string] $PSRepository = "PSGallery"
    )

    $existingLoaded = Get-Module $Name
    $existingInstalled = Get-Module -ListAvailable $Name

    # TODO: a version unconstrained check

    if ($null -ne $existingLoaded -and $existingLoaded.Version -eq $Version) {
        return $existingLoaded
    }
    elseif ($existingLoaded) {
        Write-Verbose ("Unloading incorrect version of module {0} - (actual={1}, required={2})" -f $Name, $existingLoaded.Version, $Version)
        $existingLoaded | Remove-Module -Verbose:$false
    }

    if ($DoNotInstall) {
        throw "The required module {0} v{1} is not available and was not installed due to DoNotInstall=true"
    }

    if ($null -eq $existingInstalled -or ($Version -notin $existingInstalled.Version)) {
        Write-Verbose ("Installing required module: {0} v{1}" -f $Name, $Version)
        $installArgs= @{
            Name = $Name
            Scope = $Scope
            Force = $true
            RequiredVersion = $Version
            Repository = $PSRepository
        }
        if ($AdditionalArgs) {
            $installArgs += $AdditionalArgs
        }
        Install-Module @installArgs
    }

    $assertedModule = Get-Module -ListAvailable $Name | Where-Object { $_.Version -eq $Version }
    if (!$assertedModule) {
        throw "The module {0} v{1} was unexpectedly not available"
    }
    return $assertedModule
}