gpt4 book ai didi

c# - 在从 C# 调用的 PowerShell Core 中安装 Az

转载 作者:行者123 更新时间:2023-12-02 23:54:36 32 4
gpt4 key购买 nike

我尝试调用一个 PowerShell 脚本来安装并使用 C# .NET 6 中的 Az 库,但出现以下错误:

Failed to run test  because 
New-AzResourceGroup:
Line |
8 | New-AzResourceGroup -Name 'TestRg123' -Location 'eastus2euap'
| ~~~~~~~~~~~~~~~~~~~
| The term 'New-AzResourceGroup' 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.

仔细查看 ps.ErrorBuffer 显示 PowerShellCore 在安装 Azure 模块时遇到问题。显然this is not a new problem

程序.cs

using System.Diagnostics;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

var initialState = InitialSessionState.CreateDefault2();
initialState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;

using var ps = PowerShell.Create(initialState);
var results = ps.AddScript(@"
Install-PackageProvider -Name Nuget -Scope CurrentUser –Force

Install-Module –Name PowerShellGet -Scope CurrentUser –Force

Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force

# Import Azure module
Import-Module 'Az'
Import-Module 'Az.Accounts'
Import-Module 'Az.RecoveryServices'

try {
New-AzResourceGroup -Name 'TestRg123' -Location 'eastus2euap'
}
catch
{
$string_err = $_ | Out-String
Write-Output ""Failed to run test $testname because $string_err""
}
").Invoke();

foreach (var outputItem in results)
{
Debug.WriteLine(outputItem);
}

ConsoleApp.csproj

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Platforms>x64</Platforms>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.PowerShell.SDK" Version="7.2.6" />
<PackageReference Include="PowerShellStandard.Library" Version="5.1.1" />
<PackageReference Include="System.Management.Automation" Version="7.2.6" />
</ItemGroup>

</Project>

错误:

Unhandled Exception - Message:'The type initializer for 'Microsoft.PackageManagement.Internal.Utility.Plugin.DynamicType' threw an exception.' Name:'TypeInitializationException' Stack Trace:'   at Microsoft.PackageManagement.Internal.Utility.Plugin.DynamicType.Create(Type tInterface, OrderedDictionary`2 instanceMethods, List`2 delegateMethods, List`1 stubMethods, List`2 usedInstances)
at Microsoft.PackageManagement.Internal.Utility.Plugin.DynamicInterface.CreateProxy(Type tInterface, Object[] instances)
at Microsoft.PackageManagement.Internal.Utility.Plugin.DynamicInterface.DynamicCast(Type tInterface, Object[] instances)
at Microsoft.PackageManagement.Internal.Utility.Plugin.DynamicInterface.DynamicCast[TInterface](Object[] instances)
at Microsoft.PackageManagement.Internal.Utility.Plugin.DynamicInterfaceExtensions.As[TInterface](Object instance)
at Microsoft.PowerShell.PackageManagement.Cmdlets.CmdletBase.get_PackageManagementHost()
at Microsoft.PowerShell.PackageManagement.Cmdlets.CmdletBase.SelectProviders(String[] names)
at Microsoft.PowerShell.PackageManagement.Cmdlets.CmdletWithProvider.get_SelectedProviders()
at Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackageProvider.get_SelectedProviders()
at Microsoft.PowerShell.PackageManagement.Cmdlets.CmdletWithProvider.<get_CachedSelectedProviders>b__23_0()
at Microsoft.PackageManagement.Internal.Utility.Extensions.DictionaryExtensions.GetOrAdd[TKey,TValue](IDictionary`2 dictionary, TKey key, Func`1 valueFunction)
at Microsoft.PackageManagement.Internal.Utility.Extensions.Singleton`1.GetOrAdd(Func`1 newInstance, Object primaryKey, Object[] keys)
at Microsoft.PackageManagement.Internal.Utility.Extensions.SingletonExtensions.GetOrAdd[TResult](Object primaryKey, Func`1 newInstance, Object[] keys)
at Microsoft.PowerShell.PackageManagement.Cmdlets.CmdletWithProvider.get_CachedSelectedProviders()
at Microsoft.PowerShell.PackageManagement.Cmdlets.CmdletWithProvider.GenerateDynamicParameters()
at Microsoft.PowerShell.PackageManagement.Cmdlets.AsyncCmdlet.<>c__DisplayClass83_0.<AsyncRun>b__0()'

屏幕截图:

enter image description here

最佳答案

虽然最初需要更长的时间,但我建议使用内置的 C# 工具来调用 powershell。请注意,您必须在运行代码的每台计算机上安装 powershell 模块。这可能会导致问题。但是,您可以使用类似的东西:

    public Collection<PSObject> runAzureCommands(Command _command, string _commandName)
{
InitialSessionState initialSession = InitialSessionState.CreateDefault();
initialSession.ImportPSModule(new[] { "MSOnline" });
PSCredential credential = new PSCredential(this.emailLogin, this.emailPass);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("https://outlook.office365.com/PowerShell-LiveID"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyerrors) => true;
System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)(0x30 | 0xc0 | 0x300 | 0xc00);
connectionInfo.MaximumConnectionRedirectionCount = 10;
Command connectCommand = new Command("Connect-AzureAD");
connectCommand.Parameters.Add(new CommandParameter("Credential", credential));

try
{
using (Runspace runspace = RunspaceFactory.CreateRunspace(initialSession))
{
runspace.Open();
Pipeline pipe = runspace.CreatePipeline();
pipe.Commands.Add(connectCommand);
var results = pipe.Invoke();
var error = pipe.Error.ReadToEnd();
if (error.Count > 0)
{
foreach (PSObject err in error)
{
//Log the error as needed.
}
}
pipe = runspace.CreatePipeline();
pipe.Commands.Add(_command);
var results2 = pipe.Invoke();
var error2 = pipe.Error.ReadToEnd();
if (error2.Count > 0)
{
foreach (PSObject er in error2)
{
//log the error as needed.
}
}
return results2;
}
}
catch (Exception e)
{
//Log the exception as needed.
}
}

这可以让您更好地记录错误,并更好地记录异常。如果您需要使用创建的项目/输出,它还允许您返回 PS 对象。

使用函数:

    public void addAzureGroupMember(object _group, object _user)
{
Command command = new Command("Add-AzureADGroupMember");
command.Parameters.Add("ObjectId", _group);
command.Parameters.Add("RefObjectId", _user);
Collection<PSObject> results = runAzureCommands(command, "addAxureGroupMember");
}

构建主函数后,您可以快速创建额外的函数。此外,当/如果它中断时,您只需更改一个主要函数,而不是修复使用模板创建的每个 powershell 脚本。

我们使用它来连接到 powershell AD 和其他 powershell 项目(包括 ExchangeOnline 和 MsolService)的模板。

关于c# - 在从 C# 调用的 PowerShell Core 中安装 Az,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74007416/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com