Selasa, 02 Februari 2016

PowerShell v2 Test if an Assembly is Loaded

As part of a function I was writing I came up with this test to see if an assembly needed to be loaded:
if(([appdomain]::currentdomain.getassemblies() | Where{$_ -match "System.Drawing"}) -eq $null)
{
     Write-Verbose "Loading System.Drawing assembly.";
     [Void] [System.Reflection.Assembly]::LoadFromPartialName("System.Drawing");
}
 Richard Siddaways post
Assemblies loaded in PowerShell
got me thinking in this direction. All I did was add the wrapper to test for a specific item. This could easily be modularized into a function:
function Load-Assembly
{
     [CmdletBinding()]
     param(
          [Parameter(
              Mandatory = $true,
              ValueFromPipeline = $true
          )]
          [ValidateNotNullOrEmpty()]
          [String]
          $AssemblyName,
         
          [Switch]
          $Report = $false
     )

     if(([appdomain]::currentdomain.getassemblies() | Where {$_ -match $AssemblyName}) -eq $null)
     {
          if($Report) {
              Write-Output "Loading $AssemblyName assembly.";
          }
          [Void] [System.Reflection.Assembly]::LoadFromPartialName($AssemblyName);
          return 1
     }
     else
     {
          if($Report) {     
              Write-Output "$AssemblyName is already loaded.";
          }
          return -1
     }
}

Load-Assembly -AssemblyName System.Drawing

lamsim

About lamsim

Author Description here.. Nulla sagittis convallis. Curabitur consequat. Quisque metus enim, venenatis fermentum, mollis in, porta et, nibh. Duis vulputate elit in elit. Mauris dictum libero id justo.

Subscribe to this Blog via Email :