5

I've been using

Add-Type -Path "Path to dll"

for loading .NET assemblies into Powershell (v3) scripts. What I've found is this causes the dll file to become locked until the powershell console is terminated.

Is there some way to prevent this from happening? Can I somehow close or remove my references to release lock on this file at end of my script?

killercowuk
  • 1,313
  • 1
  • 11
  • 23

1 Answers1

7

Yes, you can read the dll into memory and load the assembly using reflection:

$bytes = [System.IO.File]::ReadAllBytes($storageAssemblyPath)
[System.Reflection.Assembly]::Load($bytes)

I added this solution as an answer to How to load assemblies in PowerShell?

Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
  • 1
    Unfortunately this approach appears to output content to Write-Host (info about GAC, Version and Location) which I need to keep clean. Any suggestions to prevent this? – killercowuk Mar 14 '18 at 14:35
  • 2
    pipe the result to `Out-null`. So change the second line to: `[System.Reflection.Assembly]::Load($bytes) | Out-null` – Martin Brandl Mar 14 '18 at 14:38
  • 1
    What happens if this dll loads other dlls in the same folder. Will this solve that as well? I assume not – Mark May 15 '19 at 20:33
  • @Mark Good question. I would also assume not. Can you verify that? – Martin Brandl May 20 '19 at 12:29
  • @Mark, for me it wasn't in the same folder, but confirmed. I got a 'could not load file or assembly' error. – pwilcox Jan 29 '20 at 23:13
  • @MartinBrandl, confirmed in the negative, see my comment to mark. – pwilcox Jan 29 '20 at 23:14