| | 1 | | <# |
| | 2 | | .SYNOPSIS |
| | 3 | | Ensures that a .NET assembly is loaded only once. |
| | 4 | |
|
| | 5 | | .DESCRIPTION |
| | 6 | | Checks the currently loaded assemblies for the specified path. If the |
| | 7 | | assembly has not been loaded yet, it is added to the current AppDomain. |
| | 8 | | .PARAMETER AssemblyPath |
| | 9 | | Path to the assembly file to load. |
| | 10 | | #> |
| | 11 | | function Assert-KrAssemblyLoaded { |
| | 12 | | [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '')] |
| | 13 | | [CmdletBinding()] |
| | 14 | | [OutputType([bool])] |
| | 15 | | param ( |
| | 16 | | [Parameter(Mandatory = $true)] |
| | 17 | | [string]$AssemblyPath |
| | 18 | | ) |
| 2 | 19 | | if (-not (Test-Path -Path $AssemblyPath -PathType Leaf)) { |
| 0 | 20 | | throw "Assembly not found at path: $AssemblyPath" |
| | 21 | | } |
| 1 | 22 | | $assemblyName = [System.Reflection.AssemblyName]::GetAssemblyName($AssemblyPath).Name |
| 3 | 23 | | $loaded = [AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq $assemblyName } |
| 1 | 24 | | if (-not $loaded) { |
| 0 | 25 | | if ($Verbose) { |
| 0 | 26 | | Write-Verbose "Loading assembly: $AssemblyPath" |
| | 27 | | } |
| | 28 | | try { |
| 0 | 29 | | Add-Type -LiteralPath $AssemblyPath |
| | 30 | | } catch { |
| 0 | 31 | | Write-Error "Failed to load assembly: $AssemblyPath" |
| 0 | 32 | | return $false |
| | 33 | | } |
| | 34 | | } else { |
| 1 | 35 | | if ($Verbose) { |
| 0 | 36 | | Write-Verbose "Assembly already loaded: $AssemblyPath" |
| | 37 | | } |
| | 38 | | } |
| 1 | 39 | | return $true |
| | 40 | | } |
| | 41 | |
|