Ошибка экземпляра пространства выполнения Powershell: System.Management.Automation не найден - PullRequest
0 голосов
/ 17 июня 2019

Я пытаюсь сделать несколько удаленных запросов к Exchange из API ядра .NET, но у меня возникли некоторые проблемы, и я не могу найти решение.

Я создал шаблон синглтона, поэтому могу иметь толькоодин сеанс PowerShell для каждого пользователя, и всякий раз, когда мне нужно позвонить для обмена, я снова получаю этот сеанс.Проблема заключается в том, что при попытке создать пространство выполнения возникает ошибка System.IO.FileNotFoundException 'en System.Management.Automation.dll, и я не могу выполнить какую-либо команду.

Я размещаю свой API в локальномIIS в Windows 10 и я использую .NET Core 2.2.Если я делаю запрос непосредственно в IIS Express, при запуске моего кода в Visual Studio я не получаю ошибки, но получаю исключение, когда делаю запрос к сайту IIS.

Любая помощь будет принята с благодарностью!!!

Спасибо !!!

Я попытался создать пространство выполнения локально и подключиться к Exchange, но я также попытался подключиться remotelly и сохранить эту конфигурацию, поэтому мне нужно было только импортироватьсеанс.

Мы также пытались обновить ядро ​​.net до версии 3, но нам не повезло.

// this is how I retrive the sessíon from the singleton --
public Powershell GetSession(string usuario, string password)
{
    PSCredential credenciales = Powershell.CrearCredenciales(usuario, password);
    Powershell powershell;
    if (diccionarioSesionesPowershell.ContainsKey(credenciales))
    {
        powershell = diccionarioSesionesPowershell[credenciales];
        bool sesionValida = powershell.EsValida();
        if (!sesionValida)
        {
            powershell.InicializarRunspace();
        }
    }
    else
    {
        powershell = new Powershell(credenciales, Logger);
        powershell.CrearRunspace();
        diccionarioSesionesPowershell.Add(credenciales, powershell);
    }
    return powershell;
}





// this is the singleton config in startup
services.AddSingleton<PilaPowershell>();




// this is how I save my remote session so I can import it later
private Runspace Runspace{get; set;}

public bool InicializarRunspace()
{
    bool resultado = false;
    try
    {
        Runspace = RunspaceFactory.CreateRunspace();-->this is where I get the error
        Runspace.Open();

        // Create a powershell session for remote exchange server
        using (var powershell = PowerShell.Create())
        {
            var command = new PSCommand();
            command.AddCommand("New-PSSession");
            command.AddParameter("ConfigurationName", "Microsoft.Exchange");
            command.AddParameter("ConnectionUri", new Uri("https://outlook.office365.com/powershell-liveid/"));
            command.AddParameter("Authentication", "Basic");
            command.AddParameter("Credential", Credenciales);
            powershell.Commands = command;
            powershell.Runspace = Runspace;

            var result = powershell.Invoke();
            SesionesPS = result[0];
        }

        // Set ExecutionPolicy on the process to unrestricted
        using (var powershell = PowerShell.Create())
        {
            var command = new PSCommand();
            command.AddCommand("Set-ExecutionPolicy");
            command.AddParameter("Scope", "Process");
            command.AddParameter("ExecutionPolicy", "Unrestricted");
            powershell.Commands = command;
            powershell.Runspace = Runspace;

            powershell.Invoke();
        }

        // Import remote exchange session into runspace
        using (var powershell = PowerShell.Create())
        {
            var command = new PSCommand();
            command.AddCommand("Import-PSSession");
            command.AddParameter("Session", SesionesPS);
            powershell.Commands = command;
            powershell.Runspace = Runspace;

            powershell.Invoke();
        }
        resultado = true;
    }
    catch (Exception ex)
    {
        Logger.LogError(ex, "Powershell error when creating runspace: ");
        resultado = false;
    }
    return resultado;
}





//this is how I try to create the runspace and connect remotelly - I do open and close the runspace when I run my commands
public void CrearRunspace()
{
    WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(LiveId), SchemaUri, Credenciales);
    connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
    Runspace =  RunspaceFactory.CreateRunspace(connectionInfo);-->this is where I get the error
}

1 Ответ

0 голосов
/ 18 июня 2019

Я нашел решение для моей проблемы. Когда я создал API, я скачал PowerSDK SDK с помощью Nuget, но когда я опубликовал его с этим SDK, IIS не смог получить доступ к необходимым зависимостям. Поэтому я удалил SDK и вместо этого установил PowerShell 6 на свой ПК и связал зависимости в сборке, и это сработало !!

...