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.
<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();
}