Powershell to Exchange 2013 - Restricted language mode error

后端 未结 1 1930
小鲜肉
小鲜肉 2021-02-10 20:45

I\'m working on a C# web service that will be deployed on an Exchange 2013 server. This service will be responsible for running powershell commands to configure Exchange.

<
相关标签:
1条回答
  • 2021-02-10 20:57

    I ended up getting support from Microsoft and they provided the following solution which works. Instead of connection via a remote powershell session, it is possible to connect to the local powershell and then import the remote session. Doing this fixes the issue.

    Error handling not included in example below

    var runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    
    object psSessionConnection;
    
    // 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(_exchangeConnectionUri));
        command.AddParameter("Authentication", "Kerberos");
        powershell.Commands = command;
        powershell.Runspace = runspace;
    
        // TODO: Handle errors
        var result = powershell.Invoke();
        psSessionConnection = 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", psSessionConnection);
        powershell.Commands = command;
        powershell.Runspace = runspace;
    
        powershell.Invoke();
    }
    
    0 讨论(0)
提交回复
热议问题