Public/Invoke-TunerPSModules.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
#requires -RunAsAdministrator

function Invoke-TunerPSModules {
    <#
    .SYNOPSIS
        Installs or Updates one or more PowerShell modules
    .DESCRIPTION
        Installs or Updates one or more PowerShell modules
    .PARAMETER Name
        Name of one or more PowerShell modules to install or update
    .EXAMPLE
        Invoke-TunerPSModules -Name @('dbatools','carbon')
    #>

    [CmdletBinding(SupportsShouldProcess=$True)]
    param(
        [parameter(Mandatory=$True, HelpMessage="Name of one or more modules")]
        [ValidateNotNullOrEmpty()]
        [string[]] $Name
    )
    try {
        Write-Host "updating or installing powershell modules..." -ForegroundColor Cyan
        $Name | ForEach-Object {
            if ($mdx = Get-Module $_ -ListAvailable) {
                $mdv = $mdx.Version -join '.'
                try {
                    if ($fdx = Find-Module $_) {
                        $fdv = $fdx.Version -join '.'
                        if ($mdv -ne $fdv) {
                            if ($CheckOnly) {
                                Write-Host "installed: $mdv / available: $fdv" -ForegroundColor Magenta
                            }
                            else {
                                Write-Host "updating $_ from $mdv to $fdv" -ForegroundColor Magenta
                                Uninstall-Module -Name $_ -AllVersions -Force
                                Install-Module -Name $_ -AllowClobber -Force
                            }
                        }
                        else {
                            Write-Host "$_ $mdv is latest" -ForegroundColor Green
                        }
                    }
                    else {
                        Write-Host "$_ is no longer on the gallery" -ForegroundColor Yellow
                    }
                }
                catch {
                    Write-Error $Error[0].Exception.Message
                }
            }
            else {
                if ($CheckOnly) {
                    Write-Host "$_ is not installed" -ForegroundColor Cyan
                }
                else {
                    Write-Host "installing $_" -ForegroundColor Magenta
                    Install-Module -Name $_ -AllowClobber -Force
                }
            }
        }
    }
    catch {}    
}

Export-ModuleMember -Function Invoke-TunerPSModules