Public/Install-ModuleIfNeeded.ps1
function Install-ModuleIfNeeded { <# .SYNOPSIS Ensures a PowerShell module is installed from the PowerShell Gallery and imports it. .DESCRIPTION Checks if a given module is installed. If not, installs the latest version from the PowerShell Gallery. If already installed, can optionally update it. Finally, imports the module into the current session. .PARAMETER Name The name of the module to ensure is installed and imported. .PARAMETER Update If specified, updates the module to the latest version if already installed. #> param( [Parameter(Mandatory)] [string]$Name, [switch]$Update ) # Ensure PSGallery is trusted if ((Get-PSRepository -Name "PSGallery").InstallationPolicy -ne "Trusted") { Write-Host "Setting PSGallery repository to Trusted..." Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted } # Check if installed $installed = Get-InstalledModule -Name $Name -ErrorAction SilentlyContinue if ($null -eq $installed) { Write-Host "Module '$Name' not installed. Installing..." Install-Module -Name $Name -Scope CurrentUser -Force Write-Host "Module '$Name' installed successfully." } else { Write-Host "Module '$Name' is already installed (version $($installed.Version))." if ($Update) { Write-Host "Updating module to latest version..." Update-Module -Name $Name -Force Write-Host "Module '$Name' updated." } } # Import module into session try { Import-Module $Name -Force -ErrorAction Stop Write-Host "Module '$Name' imported successfully." } catch { Write-Error "Failed to import module '$Name': $_" } } |