[英]Powershell: How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?
[英]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
文件的完整路径:
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
-ReferencedAssemblies
将netstandard
程序集传递给 -ReferencedAssemblies。
例如,对于在两个PowerShell 版本中运行的代码,帮助程序 .NET SDK 项目(参见下面的代码)应该以--framework netstandard2.0
为目标。
默认情况下,PowerShell 会话本身中默认可用的所有程序集(及其类型)也可以在传递给-TypeDefinition
的 C# 源代码中引用:
-ReferencedAssemblies
的任何程序集都被添加到隐式可用类型。-ReferencedAssemblies
会排除通常隐式可用的程序集,因此必须显式传递所有必需的程序集(例如, System.Console
以使用Console.WriteLine()
)。演示:
以下是一个独立的、易于定制的示例,带有详细的注释,可在Windows PowerShell和PowerShell (Core) 7+中使用,并执行以下操作:
*.dll
) 随时可用。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.