Sometimes in my PowerShell scripts, I need access to a specific DLL, using Add-Type -AssemblyName
. However, the DLLs I need aren't always on the machine or in the GAC. For instance, I might want a quick script that uses Dapper to query a database. In these cases, I have been literally copying the DLLs along with the ps1
file. I was wondering if this was common/a good idea and whether there was an existing extension that would load up NuGet packages, store then in a global or local folder and call Add-Type -AssemblyName
automatically.
It'd be a lot like using npm
or pip
in Node.js or Python, respectively.
Update
I did some research and there's nothing built-in to older versions of PowerShell. I made some progress trying to write one from scratch using the nuget.exe
&"$(Get-Location)/nuget.exe" install $packageName -Version $version -OutputDirectory "$(Get-Location)/packages" -NoCache -NoInteractive
This will download a given package/version under a "packages" folder in the current folder, along with any of its dependencies. However, it looks like it downloads every framework version, with no obvious way to tell which one to use for your given environment.
Otherwise, you could just loop through the results and call Add-Type:
Get-ChildItem .\packages\ -Recurse -Filter "*.dll" | % { try { Add-Type -Path $_.FullName } catch [System.Exception] { }}
I tried using the restore
command using a project.json
file to see if I could control the framework version with no luck. This is just too hacky for me.
I'll check out @crownedjitter's suggestion of using PowerShell 5.
Update
Using @crownedjitter's suggestion, I was able to eventually register the PackageManagement module with NuGet (see comments below). With the following command, I was able to reproduce what the Nuget.exe
command above was doing:
Install-Package Dapper -Destination packages
Obviously, this is a lot shorter. Problem is it has the same limitation; it brings down every framework version of a package. If this includes .NET core, it brings down a good deal of the .NET core framework with it! There doesn't appear to be a way to specify a target framework (a.k.a, .NET 4.5.1 or below).
I am wondering if there is a way to determine which NuGet package folder(s) to load the DLLs from based on PowerShell's current $PSVersionTable.CLRVersion
field.