Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a NuGet package within a PowerShell script?

I'm writing a PowerShell script that makes use of the Mono.Cecil library. How would I install the package so I can use it from within the script? Thanks!

(For the record, I did try Googling before asking this, but all that came up was results about PMC and Visual Studio, which aren't relevant to this question.)

like image 388
James Ko Avatar asked Feb 08 '16 15:02

James Ko


2 Answers

I was able to install a package in PowerShell 6 (Core) by specifying the source:

PS > install-package gudusoft.gsqlparser -source https://www.nuget.org/api/v2
like image 93
craig Avatar answered Nov 10 '22 09:11

craig


~5.x versions of PowerShell have a nuget package source included by default but it doesn't work:

PS > Get-PackageSource 
Name                             ProviderName     IsTrusted  Location
----                             ------------     ---------  --------
nuget.org                        NuGet            False      https://api.nuget.org/v3/index.json
PSGallery                        PowerShellGet    False      https://www.powershellgallery.com/api/v2/

If you Unregister-PackageSource -Source nuget.org and Register-PackageSource -Location https://www.nuget.org/api/v2 -name nuget.org -Trusted I have been able to install nuget papckages with just Install-Package from PowerShell, not within visual studio. Got the idea from this SO answer.

I don't know what other possible negative impacts there are to removing the v3 version of the nuget.org source but I have been running this way for a while and things appear ok, your mileage may vary.

As an alternative here is an example that gets the job done by pulling down the nuget.exe even if it is a crummy way to have to do this:

function Install-InvokeOracleSQL {
    $ModulePath = (Get-Module -ListAvailable InvokeSQL).ModuleBase
    Set-Location -Path $ModulePath

    if ($PSVersionTable.Platform -ne "Unix") {
        $SourceNugetExe = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
        $TargetNugetExe = ".\nuget.exe"
        Invoke-WebRequest $sourceNugetExe -OutFile $targetNugetExe
        .\nuget.exe install Oracle.ManagedDataAccess
        Remove-Item -Path $TargetNugetExe
    } elseif ($PSVersionTable.Platform -eq "Unix") {
        nuget install Oracle.ManagedDataAccess.Core -Version 2.12.0-beta2
    }
}
like image 10
Chris Magnuson Avatar answered Nov 10 '22 11:11

Chris Magnuson