从 Asp.Net Web API 执行 powershell SCVMM cmdlet

Excute powershell SCVMM cmdlets from Asp.Net Web API

我正在 Asp.Net 开发 Web Api。我需要网络 API 使用 .Net Framework 与 SCVMM 通信。 我们都知道 SCVMM 不提供类似于从 c# 代码执行函数的 API o 接口,但我们可以选择从 PowerShell 执行 运行 命令。

情况如下:

  1. 在 PowrShell 提示符下,我可以毫无问题地与 SCVMM 通信
  2. 从使用 Cake.Pworsehl Nuget 包的 c# 代码我可以使用 SCVMM 命令执行 cmdlet 并与 SCVNMM 毫无问题地沟通。
  3. 使用我之前编写的函数,我创建了一个包含所有 我需要的功能,我还为该 dll 添加了一个 TestProject 并且所有工作 很好。
  4. 问题是当我使用 WebApi 项目调用相同的函数时 VS 2022 中的调试模式出现以下错误:

System.Management.Automation.CmdletInvocationException: 'You do not have access to the management server VMM NO_PARAM. (Error Id: 1604)

奇怪的是,正如我之前所说,我可以 运行 PowerShell 提示符下的所有函数,并执行 TestProjects 甚至控制台应用程序中的所有代码,但是如果我调用相同的函数形式web api,我收到那个错误。

我认为这个问题必须通过 de Identity 或类似的东西来解决,但我找不到任何方法来为 运行 powershell cmdlet 形式的 c# 代码指定凭据。

这是给我错误的函数:

public List<Vm> GetVMsBase()
{

    InitialSessionState initialSessionState = InitialSessionState.CreateDefault();
    initialSessionState.ExecutionPolicy = ExecutionPolicy.Unrestricted;
    initialSessionState.ImportPSModule(new string[] { "virtualmachinemanager" });            

    using (var myRunSpace = RunspaceFactory.CreateRunspace(initialSessionState))
    {
          myRunSpace.Open();
          using (var pipeLine = myRunSpace.CreatePipeline())
          {
                Command cmd = new Command("Get-SCVirtualMachine");
                cmd.Parameters.Add("VMMServer", "vmmserver.domain.com");
                pipeLine.Commands.Add(cmd);

                return pipeLine.Invoke().Select(vm =>
                new Vm
                {
                    Name = vm.Properties["name"].Value.ToString(),
                    Owner = ((string[])vm.Properties["CustomProperties"].Value)[1],
                    ExpirationDate = DateTime.TryParse(
                                ((string[])vm.Properties["CustomProperties"].Value)[0], new CultureInfo("es-ES"), DateTimeStyles.None, out DateTime dt) ?
                                dt : new DateTime(1800, 1, 1),
                    CreationDate = DateTime.TryParse(
                                vm.Properties["CreationTime"].Value.ToString(), new CultureInfo("es-ES"), DateTimeStyles.None, out DateTime dt2) ?
                                dt2 : new DateTime(1800, 1, 1),
                    Hlnumber = ((string[])vm.Properties["CustomProperties"].Value)[2],
                    State = Enum.TryParse(vm.Properties["VirtualMachineState"].Value.ToString(), out VirtualMachineState vmState) ? vmState : VirtualMachineState.Unknow
                }).ToList();

                if (pipeLine.Error != null && pipeLine.Error.Count > 0)
                {
                    //check error
                }
            }
        }

有什么方法可以从网络 api 调用或 运行 此代码吗?

感谢您的关注。

我终于解决了这个问题,运行 powershell cmdlet 的代码没有任何问题,问题出在 IIS expres 的配置(在 visual studio 中)和部署时api 在 IIS 10 中。

在这两种情况下,我都必须以禁用匿名登录的方式设置取消配置,并且使用的唯一身份验证方法是“Windows”,仅此而已。

在 IIS Express 中,您必须编辑位于解决方案 .vs 目录中的 .config 文件,而在 IIS 10 中,您必须在身份验证选项中编辑站点设置。