I'm trying to use a PowerShell object with a remote runspace. The initial connection is established, the test returns back with the correct responses, all appears good. I then assign my powershell object some commands to run, and it pops up with the following error message:
System.Management.Automation.PSObjectDisposedException: 'Cannot perform operation because object "PowerShell" has already been disposed. Object name: 'PowerShell'.'
I've not actually disposed of anything (I'd rather keep things open while I'm developing, and optimise it later).
RemoteShell (works fine, no problems):
Private PowerShell RemoteShell (string Hostname, PSCredential psCred)
{
PowerShell psCon = PowerShell.Create();
WSManConnectionInfo connectionInfo = new WSManconnectionInfo
{
Port = 5985,
AuthenticationMechanism = AuthenticationMechanism.Kerberos,
ComputerName = Hostname,
Credential= psCred,
ShellUri = "http://schemas.microsoft.com/powershell/microsoft.powershell",
IdleTimeout = 99999999
}
using (Runspace remoterunspace = RunspaceFactory.CreateRunespace(connectionInfo))
{
try {
remoteRunspace.Open();
using (psCon) {
psCon.Runspace = remoteRunspace;
psCon.AddCommand("whoami");
psCon.AddStatement().AddScript("[System.Net.Dns]::GetHostByName(($env:computerName))";
Collection<PSObject> results= psCon.Invoke();
string resultsstr = "Shell created under: " + results[0].ToString() + System.Environment.NewLine + "Shell created on: " + results[1].ToString();
AddToOutput(--- not really relevant ---);
} catch (Exception e) {
AddToOutput (--- not really relevant ---);
}
}
return psCon;
}
JobAsync (dies every time it hits the *** line):
Private Boolean jobAsync (string type, List<ScriptModule>JobList, PSCredential psCred)
{
PowerShell psCon;
<type switch kind of irrelevant>
psCon = RemoteShell(targetFQDN, psCred);
foreach(ScriptModule curMod in JobList)
{
psCon.Commands.Clear();
List<String[]> ResultsArr = new List<string[]>();
int TestNum = 0;
foreach(ScriptObject curScr in curMod.moduleScripts)
{
<< some more irrelevant stuff assembling strings >>
**** psCon.AddStatement().AddScript("$param" + pC + " = '" + paramVal + "';"); ****
}
The **** line constantly generates a PowerShell disposed error exception preventing any further execution. This same code is also used on a local shell (running from the machine the application is running on) and this works fine. The only difference in the code is the remoteShell utilising a runspace...
For reference, here's the localShell code:
private PowerShell LocalShell()
{
PowerShell psCon = PowerShell.Create();
try {
psCon.AddCommand("whoami");
psCon.AddStatement().AddScript("[System.Net.Dns]::GetHostByName(($env:computerName))");
Collection<PSObject> results = psCon.Invoke();
<< more irrelevant string stuff >>
} catch (Exception e) {
<< more irrelevant string stuff >>
}
return psCon;
}