如何在 PowerShell 脚本中使用 NuGet 包?

How to use a NuGet package within a PowerShell script?

我正在编写一个使用 Mono.Cecil 库的 PowerShell 脚本。我将如何安装该软件包以便我可以在脚本中使用它?谢谢!

(郑重声明,我在问这个问题之前确实尝试过谷歌搜索,但得到的结果都是关于 PMC 和 Visual Studio 的结果,这与这个问题无关。)

找不到好的解决方案,我最终只能通过 NuGet API 手动下载并解压缩包。

对于 interested/others 遇到此问题的人,here 是我使用的代码。

~5.x 版本的 PowerShell 默认包含一个 nuget 包源,但它不起作用:

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/

如果您 Unregister-PackageSource -Source nuget.orgRegister-PackageSource -Location https://www.nuget.org/api/v2 -name nuget.org -Trusted 我已经能够通过 PowerShell Install-Package 安装 nuget papckages,而不是 visual studio。从 .

得到灵感

我不知道删除 v3 版本的 nuget.org 源代码还有哪些其他可能的负面影响,但我已经 运行 这种方式已经有一段时间了,看起来还不错,你的里程可能会有所不同。

作为替代方案,这里有一个示例,它通过下拉 nuget.exe 来完成工作,即使这样做是一种糟糕的方式:

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
    }
}

我能够通过指定源在 PowerShell 6 (Core) 中安装包:

PS > install-package gudusoft.gsqlparser -source https://www.nuget.org/api/v2