Private/Check-NeededPSSnapins.ps1
<#
.SYNOPSIS Checks for required PowerShell snap-ins, loads them if registered but not loaded, and reports any missing snap-ins. .DESCRIPTION The Get-NeededPSSnapins function verifies if specified PowerShell snap-ins are loaded. If a snap-in is registered but not loaded, it attempts to load it. It reports any snap-ins that are not registered. .PARAMETER Snapins An array of snap-in names that need to be checked. .EXAMPLE PS> Get-NeededPSSnapins -Snapins "Citrix*", "VMware*" .OUTPUTS Boolean. Returns true if all snap-ins are loaded or successfully loaded, false if any are missing. .NOTES Author: Sundeep Eswarawaka Version: 1.0 #> Function Get-NeededPSSnapins { [CmdletBinding()] Param( [Parameter(Mandatory = $True)] [Alias("Snapin")] [string[]] $Snapins ) $missingSnapins = @() $loadedSnapins = Get-PSSnapin | ForEach-Object {$_.Name} $registeredSnapins = Get-PSSnapin -Registered | ForEach-Object {$_.Name} foreach ($snapin in $Snapins) { # Check if the snapin is loaded if ($loadedSnapins -notcontains $snapin) { # Check if the snapin is registered but not loaded if ($registeredSnapins -contains $snapin) { Write-Verbose "Loading PowerShell snap-in: $snapin" try { Add-PSSnapin -Name $snapin -ErrorAction Stop } catch { Write-Error "Error loading snap-in '$snapin': $_. Exception was thrown." return $false } } else { $missingSnapins += $snapin } } } if ($missingSnapins.Count -gt 0) { Write-Warning "Missing PowerShell snap-ins detected:" $missingSnapins | ForEach-Object { Write-Warning "`tMissing snap-in: $_" } return $false } else { Write-Verbose "All specified snap-ins are loaded." return $true } } |