Using the code below, a powershell process is spawned and the runspace opens properly. From here I can submit the powershell commands to create and import a remote powershell session. The issue is this new session loads and caches all of the imported modules into the host process and not the process spawned by the CreateOutOfProcessRunspace(...).Open() with no way of garbage collecting the cached modules.
PowerShellProcessInstance instance = new PowerShellProcessInstance(new Version(5, 1), null, null, true);
var runspace = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0]), instance);
runspace.Open();
Using an initialization script for the powershell instance gets stuck on the runspace.Open()
. As far as I can tell, it never even times out. I have let it run for a good 5 minutes (when it shouldn't take longer than 20 seconds to pull the remote modules) and the state of the runspace is still Opening
.
string script = string.Join("\r\n", new string[] {
"$Username = \"mailbox\"",
"$SecurePass = ConvertTo-SecureString -AsPlainText password -Force",
"$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$SecurePass",
"$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "url" -Credential $Credential -Authentication Basic -AllowRedirection",
"Import-PSSession $session"
});
PowerShellProcessInstance instance = new PowerShellProcessInstance(new Version(5, 1), null, ScriptBlock.Create(script), true);
var runspace = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0]), instance);
runspace.Open();
Does anyone know of a way to isolate the remote powershell session into its own process and invoke it from a c# application?
For a work around, I am planning to isolate the powershell session into its own process by creating a separate executible that accepts Powershell commands and returns results. That way I can close that process and free memory when powershell is not in use.