Prevent assembly locking in PowerShell

Working with an automated process I recently ran into an issue where PowerShell was locking one of my files and holding up the rest of the process.

I needed to load the compiled DLL file to perform a couple actions. After the load was complete I had not need for the DLL file, however, PowerShell.exe wouldn't let it be moved or deleted until the completion of the script.

The solution

The below two lines allows the code to be read into memory, then loads the assembly from memory instead of disk. No file locks to disk!

$DLLBytes = [System.IO.File]::ReadAllBytes(“MyClassLibrary.dll”)[System.Reflection.Assembly]::Load($DLLBytes)

Other perks

While it wasn't my initial goal, I found another upside. As the file isn't locked and can be replaced/updated at anytime this works well for a shared libraries folder that multiple scripts can use. As long as your DLL updates are forward compatible they can be upgraded at anytime.

Previous
Previous

Autumn: Conference Season

Next
Next

Deleting ServiceNow Records via List Filter