When is an Explicit Add-Type Call Required for a System DLL in PowerShell?

Viewed 457

While writing a PowerShell script that uses items in System.DirectoryServices.AccountManagement, I noticed a discrepancy between when my script runs on PowerShell Desktop vs PowerShell Core.

This command works on PowerShell Core without explicit assembly loads:

$context = [System.DirectoryServices.AccountManagement.PrincipalContext]::new(
    [System.DirectoryServices.AccountManagement.ContextType]::Domain, 
    $Domain)

However, the exact same command fails on PowerShell Classic with:

Unable to find type [System.DirectoryServices.AccountManagement.PrincipalContext].

However, if I manually load the type (via Add-Type -AssemblyName System.DirectoryServices.AccountManagement), it works fine on PowerShell Classic.

What's striking me as odd is my script uses plenty of other .NET Assemblies, all of which load fine without an explicit Add-Type call, in both Classic and Core.

Is there a clear set of rules for which assemblies must be imported via Add-Type vs which can be implicitly loaded?

1 Answers

Per this issue in the PowerShell docs repo: https://github.com/MicrosoftDocs/PowerShell-Docs/issues/6422#issuecomment-668293431

  • In Windows PowerShell (i.e. 5.1 and below), you need to use Add-Type for anything that isn't already loaded. This is chiefly for scenarios involving GAC assemblies, which you can specify by name, rather than by path.
  • In PS 6+, there is no GAC. But PowerShell now ships its own assemblies in $PSHome. These assemblies are automatically loaded on request, so there's no need to Add-Type them, but doing so is still permitted (it allows you to write scripts that are implicitly compatible with Windows PowerShell, like the example you give above).
  • Since there's no GAC, there's no actual need in PS 6+ to use Add-Type
  • Loading assemblies from arbitrary paths still requires Add-Type, since those assemblies will not be discovered otherwise

It looks like the PowerShell documentation will be updated with the new information.

Related