Last active
November 8, 2020 13:25
-
-
Save gsscoder/779b4624de261fd694e89387d5c1b204 to your computer and use it in GitHub Desktop.
PowerShell Install helper function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Install { | |
[OutputType([void])] | |
param ( | |
[Parameter(Mandatory, ValueFromPipeline)] [string] $Module, | |
[Parameter(Mandatory)] [ValidatePattern("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,9}$")] [string] $Version | |
) | |
"Testing module '$Module' presence." | Write-Verbose | |
$moduleInfo = Get-InstalledModule $Module -ErrorAction SilentlyContinue -Verbose:$false | |
if (-not $moduleInfo) { | |
"Module '$Module' not present. Attempting installation." | Write-Verbose | |
try { | |
"Install-Module $Module -AllowClobber -Force -Scope CurrentUser -Verbose:`$false -RequiredVersion $Version" ` | |
| Invoke-Expression | |
$moduleInfo = Get-InstalledModule $Module -Verbose:$false | |
"Module '$Module' installed in version $($moduleInfo.Version)." | Write-Verbose | |
return | |
} catch { | |
"Unable to install module '$Module'.`n$_" | Write-Error | |
exit 1 | |
} | |
} | |
$info = $moduleInfo.Version | |
$actual = "$($info.Major).$($info.Minor).$($info.Build)" | |
if ($actual -eq $Version) { | |
"Module '$Module' present in version $($moduleInfo.Version)." | Write-Verbose | |
} else { | |
"Module '$Module' present in version '$actual'. Pinned version '$Version'." | Write-Warning | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment