Tuesday, February 2, 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

Related Post:

0 comments:

Post a Comment

 
Copyright 2009 Information Blog
Powered By Blogger