繁体   English   中英

如何安装可以从 Powershell 加载的 nuget 包

[英]How to install a nuget package such as it can be loaded from Powershell

我有使用 nuget 包 Vanara.PInvoke.Shell32 的 ac# 源。 正如预期的那样,当我尝试在 Powershell 中使用 Add-Type 使用此源时,但它在“使用 Vanara.Pinvoke”语句中窒息

我尝试使用“Install-Package Vanara.PInvoke.Shell32”,但无法安装

如何使这个模块在 Powershell 核心中可用?

听起来您已经下载了Vanara.PInvoke.Shell32 NuGet 包,并且知道包含感兴趣的程序集的.dll文件的完整路径:

  • 此答案显示了如何下载 NuGet 包及其所有依赖项以在 PowerShell 中使用(请注意, Install-Package虽然原则上能够下载 NuGet 包,但不会自动打包目标包所依赖的包); 该技术也用于下面的演示代码。

使用PowerShell 代码中的Vanara.PInvoke.*.dll程序集- 通过使用Add-Type -LiteralPath将它们加载到会话中,然后进行诸如[Vanara.PInvoke.User32]::GetForegroundWindow()类的调用 -似乎无需额外的工作努力。

但是,您的用例需要使用临时编译的 C# 源代码中传递给Add-Type-TypeDefinition参数的程序集,并且正如您所发现的,这需要更多的努力,而不仅仅是将路径传递给Vanara.PInvoke.*.dll文件添加到-ReferencedAssemblies参数中,至少从 PowerShell 7.1 开始:

  • 令人费解的是,为了使以后的Add-Type -TypeDefinition调用成功,NuGet 包中的程序集必须首先通过其完整路径显式加载到具有Add-Type -LiteralPath的会话中 - 这闻起来像一个错误。

  • 如果程序集是.NET 标准DLL,就像手头的情况一样,您还必须在调用Add-Type -TypeDefinition -ReferencedAssembliesnetstandard程序集传递给 -ReferencedAssemblies。

  • 例如,对于在两个PowerShell 版本中运行的代码,帮助程序 .NET SDK 项目(参见下面的代码)应该以--framework netstandard2.0为目标。

  • 默认情况下,PowerShell 会话本身中默认可用的所有程序集(及其类型)也可以在传递给-TypeDefinition的 C# 源代码中引用:

    • Windows PowerShell中,传递给-ReferencedAssemblies的任何程序集都被添加到隐式可用类型。
    • 相比之下,在PowerShell (Core) 7+中,使用-ReferencedAssemblies排除通常隐式可用的程序集,因此必须显式传递所有必需的程序集(例如, System.Console以使用Console.WriteLine() )。

演示

以下是一个独立的、易于定制的示例,带有详细的注释,可在Windows PowerShellPowerShell (Core) 7+中使用,并执行以下操作:

  • 按需下载给定的 NuGet 包。
  • 创建一个辅助。 NET SDK 项目,该项目引用包并发布项目,以便相关程序集 ( *.dll ) 随时可用。
  • 首先直接从 PowerShell 使用包的程序集,然后通过临时编译的 C# 代码(传递给Add-Type -TypeDefinition )。

笔记:

  • 必须安装.NET SDK

  • 忽略损坏的语法突出显示。

$ErrorActionPreference = 'Stop'; Set-StrictMode -Off

# -- BEGIN: CUSTOMIZE THIS PART.
  # Name of the NuGet package to download.
  $pkgName = 'Vanara.PInvoke.Shell32'

  # If the package assemblies are .NET Standard assemblies, the 'netstandard'
  # assembly must also be referenced - comment out this statement if not needed.
  # Note: .NET Standards are versioned, but seemingly just specifying 'netstandard'
  #       is enough, in both PowerShell editions. If needed, specify the fully qualified,
  #       version-appropriate assembly name explicitly; e.g., for .NET Standard 2.0:
  #          'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'
  #       In *PowerShell (Core) 7+* only, a shortened version such as 'netstandard, Version=2.0' works too.
  $netStandardAssemblyName = 'netstandard'

  # The target .NET framework to compile the helper .NET SDK project for.
  # Targeting a .NET Standard makes the code work in both .NET Framework and .NET (Core).  
  # If you uncomment this statement, the SDK's default is used, which is 'net5.0' as of this writing.
  $targetFrameworkArgs = '--framework', 'netstandard2.0'

  # Test command that uses the package from PowerShell.
  $testCmdFromPs = { [Vanara.PInvoke.User32]::GetForegroundWindow().DangerousGetHandle() }

  # C# source that uses the package, to be compiled ad-hoc.
  # Note: Modify only the designated locations.
  $csharpSourceCode = @'
    using System;
    // == Specify your `using`'s here.
    using Vanara.PInvoke;
    namespace demo {
      public static class Foo {
        // == Modify only this method; make sure it returns something, ideally the same thing as
        //    PowerShell test command.
        public static IntPtr Bar() { 
          return User32.GetForegroundWindow().DangerousGetHandle();
        }
      }
    }
'@

# -- END of customized part.

# Make sure the .NET SDK is installed.
$null = Get-command dotnet

# Helper function for invoking external programs.
function iu { $exe, $exeArgs = $args; & $exe $exeArgs; if ($LASTEXITCODE) { Throw "'$args' failed with exit code $LASTEXIDCODE." } }


# Create a 'NuGetFromPowerShellDemo' subdirectory in the TEMP directory and change to it.
Push-Location ($tmpDir = New-Item -Force -Type Directory ([IO.Path]::GetTempPath() + "/NuGetFromPowerShellDemo"))

try {
  
  # Create an aux. class-lib project that downloads the NuGet package of interest.
  if (Test-Path "bin\release\*\publish\$pkgName.dll") {
    Write-Verbose -vb "Reusing previously created aux. .NET SDK project for package '$pkgName'"
  }
  else {
    Write-Verbose -vb "Creating aux. .NET SDK project to download and unpack NuGet package '$pkgName'..."
    iu dotnet new classlib --force @targetFrameworkArgs >$null
    iu dotnet add package $pkgName >$null
    iu dotnet publish -c release >$null
  }

  # Determine the full paths of all the assemblies that were published (excluding the helper-project assembly).
  [array] $pkgAssemblyPaths = (Get-ChildItem bin\release\*\publish\*.dll -Exclude "$(Split-Path -Leaf $PWD).dll").FullName

  # Load the package assemblies into the session.
  # !! THIS IS NECESSARY EVEN IF YOU ONLY WANT TO REFERENCE THE PACKAGE
  # !! ALL YOU WANT DO TO IS TO USE THE PACKAGE TO AD HOC-COMPILE C# SOURCE CODE.
  # Write-Verbose -vb "Loading assembly file paths, from $($pkgAssemblyPaths[0] | Split-Path):`n$(($pkgAssemblyPaths | Split-Path -Leaf) -join "`n")"
  Add-Type -LiteralPath $pkgAssemblyPaths

  # Write-Verbose -vb 'Performing a test call FROM POWERSHELL...'
  & $testCmdFromPs

  # Determine the assemblies to pass to Add-Type -ReferencedAssemblies.
  # The NuGet package's assemblies.
  $requiredAssemblies = $pkgAssemblyPaths
  # Additionally, the approriate .NET Standard assembly may need to be referenced.
  if ($netStandardAssemblyName) { $requiredAssemblies += $netStandardAssemblyName }
  # Note: In *PowerShell (Core) 7+*, using -ReferencedAssemblies implicitly
  #       excludes the assemblies that are otherwise available by default, so you
  #       may have to specify additional assemblies, such as 'System.Console'.
  #       Caveat: In .NET (Core), types are often forwarded to other assemblies,
  #               in which case you must use the forwarded-to assembly; e.g.
  #               'System.Drawing.Primitives' rather than just 'System.Drawing' in
  #               order to use type System.Drawing.Point.
  #               What mitigates the problem is that failing to do so results in a 
  #               an error message that mentions the required, forwarded-to assembly.
  # E.g.:
  #  if ($IsCoreCLR) { $requiredAssemblies += 'System.Console' }

  Write-Verbose -vb 'Ad-hoc compiling C# CODE that uses the package assemblies...'
  Add-Type -ReferencedAssemblies $requiredAssemblies -TypeDefinition $csharpSourceCode
  
  Write-Verbose -vb 'Performing a test call FROM AD HOC-COMPILED C# CODE...'
  [demo.Foo]::Bar()

} 
finally {
  Pop-Location
  Write-Verbose -vb "To clean up the temp. dir, exit this session and run the following in a new session:`n`n  Remove-Item -LiteralPath '$tmpDir' -Recurse -Force"
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM