![](/img/trans.png)
[英]Run Az PowerShell modules in C# .NET PowerShell environment fails to load Az modules
[英]Re-producing Microsoft PowerShell repo test project to install and Running AZ PowerShell SDK in C# .net6
我正在尝试在 C# 中运行安装和运行 Azure PowerShell 模块并调用脚本。
安装从 C# .net6.0 调用的 Azure PowerShell 模块是可行的。 这是来自 Microsoft PowerShell 团队: https://github.com/PowerShell/PowerShellGet/blob/master/test/perf/benchmarks/BenchmarksV3RemoteRepo.cs
所以我创建了一个简单的 C# 代码来重现它。
using System.Diagnostics;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell;
// Setting up the PowerShell runspace
var defaultSS = InitialSessionState.CreateDefault2();
defaultSS.ExecutionPolicy = ExecutionPolicy.Unrestricted;
var pwsh = PowerShell.Create(defaultSS);
// Import the PSGet version we want to test
pwsh.AddScript(@"
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
Import-Module PowerShellGet -RequiredVersion 3.0.14 -Force");
var result = pwsh.Invoke();
foreach (var outputItem in result) Debug.WriteLine(outputItem);
pwsh.Commands.Clear();
pwsh.AddScript("Install-PSResource -Name Az -Repository PSGallery -TrustRepository -Reinstall");
var results = pwsh.Invoke();
foreach (var outputItem in results) Debug.WriteLine(outputItem);
项目:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.PowerShell.Commands.Diagnostics" Version="7.2.7"/>
<PackageReference Include="Microsoft.PowerShell.Commands.Management" Version="7.2.7"/>
<PackageReference Include="Microsoft.PowerShell.Commands.Utility" Version="7.2.7"/>
<PackageReference Include="Microsoft.PowerShell.ConsoleHost" Version="7.2.7"/>
<PackageReference Include="Microsoft.PowerShell.CoreCLR.Eventing" Version="7.2.7"/>
<PackageReference Include="Microsoft.PowerShell.Native" Version="7.3.0"/>
<PackageReference Include="Microsoft.PowerShell.SDK" Version="7.2.7"/>
<PackageReference Include="Microsoft.PowerShell.Security" Version="7.2.7"/>
<PackageReference Include="System.Management.Automation" Version="7.2.7"/>
</ItemGroup>
</Project>
错误:
The specified module 'PowerShellGet' with version '3.0.14' was not loaded because no valid module file was found in any module directory.
The term 'Install-PSResource' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
要查看错误缓冲区,请检查powershell.ErrorBuffer.Result
值
我已经在我的环境中重现了,我遇到了如下类似的错误:
然后我使用了以下命令:
Install-Module -Name PowerShellGet -RequiredVersion 3.0.14-beta14 -AllowPrerelease -Force
通过使用上面的命令,我的错误得到了解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.