繁体   English   中英

在 .NET 中导入 Az Powershell 模块

[英]Importing Az Powershell module in .NET

我正在尝试使用 C# 中的 PowerShell。 我想导入 Az.Compute 模块以使用 cmdlet,但它不起作用。

        InitialSessionState iss = InitialSessionState.CreateDefault();

        iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Bypass;
        Console.WriteLine(iss.ExecutionPolicy);
        //iss.ImportPSModule(new string[] { "Az.Compute" });
        iss.ImportPSModulesFromPath(@"C:\Program Files\WindowsPowerShell\Modules\Az.Compute");

        Runspace runspace = RunspaceFactory.CreateRunspace(iss);
        runspace.Open();

        PowerShell ps = PowerShell.Create();
        ps.Runspace = runspace;

        Collection<PSObject> servers = ps
            .AddCommand("Get-AzVM")
            .Invoke();

首先,我需要绕过执行策略才能导入模块。 我正在使用 InitialSessionSate 类中的 ImportPSModule 方法。 当我运行此代码时,我在 Get-AzVM 处遇到异常: System.Management.Automation.CommandNotFoundException: 'The 'Get-AzVM' command was found in the module 'Az.Compute', but the module could not be loaded. For more information, run 'Import-Module Az.Compute'.' System.Management.Automation.CommandNotFoundException: 'The 'Get-AzVM' command was found in the module 'Az.Compute', but the module could not be loaded. For more information, run 'Import-Module Az.Compute'.'

如果我在开发人员 powershell 中运行 Get-InstalledModule 模块就在那里。 我尝试通过从路径导入模块,但在尝试使用模块中的 cmdlet 时仍然出现异常。

上述错误是由于Az.Compute模块未正确加载造成的。 您可以尝试以下解决方法,让Get-AzVM cmdlet 正常工作,并让模块正确加载:

  • Install-Module -Name Az -AllowClobber -Scope CurrentUser运行此 cmdlet 后,重新启动 Powershell,然后再次运行此import-module az.compute cmd。

  • 您还可以从事件查看器检查 PowerShellCore/Operational 的日志,如果发现任何错误,则将包更新到最新版本

暂无
暂无

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

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