Skip to content

Instantly share code, notes, and snippets.

@gettek
Last active February 18, 2024 11:55
Show Gist options
  • Save gettek/ed6d120693aedae06b1920f4353d747e to your computer and use it in GitHub Desktop.
Save gettek/ed6d120693aedae06b1920f4353d747e to your computer and use it in GitHub Desktop.
Install and Update PowerShell Modules in Bulk
<#
.SYNOPSIS
Update your PowerShell modules in bulk by specifiying an explicit list to install & keep up to date
Requires 'PowerShellGet'
.DESCRIPTION
Add this module to your $profile to run when required:
Import-Module "path/to/module/updateMods"
.NOTES
Author: Sadik Tekin
.PARAMETER clean
Removes old versions keeping only the latest
.EXAMPLE
updateMods -clean
#>
function updateMods {
[CmdletBinding()]
Param( [switch][Parameter(Mandatory = $false)] $clean )
if ($PSVersionTable.PSVersion.Major -lt 7) { throw "Please use PowerShell >= 7.0" }
Import-Module PowerShellGet
# Add/Remove required modules from this list
@(
'Az'
'Az.*'
'AzureAD'
'Microsoft.Graph'
'AzAPICall'
'SQLServer'
'GuestConfiguration'
'PSDscResources'
'PSDesiredStateConfiguration'
'AuditPolicyDsc'
'SecurityPolicyDsc'
'xWebAdministration'
'nx'
).ForEach({
try {
Find-Module -Name $_ -Verbose | ForEach-Object {
$installedVersion = (Get-InstalledModule -Name $_.Name -ErrorAction SilentlyContinue).Version
if (!($installedVersion)) {
Write-Host '🟢 Installing New Module' $_.Name $_.Version -ForegroundColor Green
}
elseif ($installedVersion -lt $_.Version) {
Write-Host '🔷 Updating' $_.Name $installedVersion '->' $_.Version -ForegroundColor Blue
}
$command = @{
Name = $_.Name
RequiredVersion = $_.Version
Scope = 'AllUsers'
Force = $true
AcceptLicense = $true
Confirm = $false
Verbose = $true
}
Install-Module @command
if ($clean) {
$modpath = "$(($env:PSModulePath).Split(';')[0])/$($_.Name)"
$latest = (Get-ChildItem -Path $modpath | Sort-Object LastWriteTime | Select-Object -Last 1)
Get-ChildItem -Path $modpath -Exclude $latest.BaseName | ForEach-Object {
Write-Host "🔴 Removing Older Version $($_.FullName)..." -ForegroundColor DarkRed
Remove-Item $_.FullName -Recurse -Force
}
}
}
}
catch { Write-Host "🥵 Could not install module: $_" -ForegroundColor Red }
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment