【问题标题】:How to use a NuGet package within a PowerShell script?如何在 PowerShell 脚本中使用 NuGet 包?
【发布时间】:2016-05-18 07:41:04
【问题描述】:

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

(为了记录,我在问这个问题之前确实尝试过谷歌搜索,但所有出现的结果都是关于 PMC 和 Visual Studio 的结果,这与这个问题无关。)

【问题讨论】:

    标签: c# .net powershell nuget nuget-package


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      ~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 中。从this SO answer 得到这个想法。

      我不知道删除 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
          }
      }
      

      【讨论】:

      • Unregister-PackageSource -Source nuget.org
      • @JoshGust Name 似乎是别名,因为 Unregister-PackageSource -Name nuget.org -WhatIf 似乎可以工作,但 -Source 更正确,所以我编辑了答案。
      • 我发现 Register-PackageSource nugetV2 https://www.nuget.org/api/v2 -ProviderName NuGet 后跟 install-package packageName -Source nugetV2 让我到达那里,而无需取消注册任何东西。 @JamesKo 我确实必须手动执行add-type -path longPathName - 我不确定您希望有多少是自动的。 Get-Package 会告诉你它的安装位置(它会自动解包)。如果你想在没有管理员权限的情况下运行,请包括 -Scope CurrentUser
      【解决方案3】:

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

      对于有兴趣的人/其他有此问题的人,here 是我使用的代码。

      【讨论】:

      • “我放弃了”并不能真正作为答案,当然也不能作为公认的答案。充其量它属于评论,因此问题似乎仍未得到解答(可能知道该怎么做的人可以找到)。
      • @Tullo_x86:接受的分数完全取决于提问者,始终。这确实有资格作为答案,因为它试图提出解决方案。我们可以使用投票来表明我们认为它作为答案有多大帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-04
      • 1970-01-01
      • 2015-06-07
      • 2020-01-20
      • 1970-01-01
      • 2013-05-15
      相关资源
      最近更新 更多