我有一个用 C# 编写的 PowerShell 模块。最近我将其升级到.NET 8。 我的项目文件如下所示:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<AssemblyName>MyAssemblyName</AssemblyName>
<Nullable>enable</Nullable>
<Version>0.0.0</Version>
<AssemblyVersion>0.0.0</AssemblyVersion>
<SelfContained>true</SelfContained>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="PowerShellStandard.Library" Version="5.1.0-preview-06">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Path\To\Domain\Project.csproj" />
</ItemGroup>
</Project>
我是这样发布的:
dotnet publish $projectFile --self-contained --configuration Release --output C:\Some\Path
该模块在 PowerShell 7.4 中工作正常,但在 PowerShell 7.2 中不起作用。
Import-Module
总是失败并出现以下错误:
导入模块:无法加载文件或程序集“System.Console,版本=8.0.0.0,文化=中性,PublicKeyToken=b03f5f7f11d50a3a”。无法找到或加载特定文件。 (0x80131621)
这是预期的吗?当我作为独立发布时,我希望它无需升级 PowerShell 即可工作。是不是期望有误?
此问题是预料之中的,PowerShell 7.2(LTS 之前的版本)基于 .NET 6。 如果您希望您的模块与 pwsh 7 用户 (v7.2+) 完全兼容,您应该发布目标
net6.0
。请参阅PowerShell 终止支持日期以供参考。
PSADTree.csproj
,它为 Windows PowerShell 5.1 用户和 PowerShell 7+ 用户创建特定的程序集。在您的 .psd1
中,您可以使用不同的条件来确定应使用哪个 .dll
,例如 PSADTree.psd1#L12-L17
:
RootModule = if ($PSEdition -eq 'Core') {
'bin/net6.0/PSADTree.dll'
}
else {
'bin/net472/PSADTree.dll'
}
不幸的是,如果您希望分别针对 net6、7 和 8 进行多目标操作,
.psd1
将无法访问 $PSVersionTable
。在这种情况下,您可以在 .psm1
. 中定义此逻辑。