首页 > 解决方案 > c#.Net PowerShell 类

问题描述

我正在尝试将 PowerShell 对象与远程运行空间一起使用。初始连接建立,测试返回正确的响应,一切看起来都很好。然后我为我的 powershell 对象分配一些命令来运行,它会弹出以下错误消息:

System.Management.Automation.PSObjectDisposedException:'无法执行操作,因为对象“PowerShell”已被释放。对象名称:“PowerShell”。

我实际上并没有处理任何东西(我宁愿在开发时保持开放,然后再优化它)。

RemoteShell(工作正常,没问题):

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(每次到达 *** 行时死掉):

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 + "';"); ****
        }

**** 行不断生成 PowerShell 处理的错误异常,阻止任何进一步的执行。相同的代码也用于本地 shell(从运行应用程序的机器上运行),并且工作正常。代码中的唯一区别是使用运行空间的 remoteShell...

作为参考,这是 localShell 代码:

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;
}

标签: c#powershellobjectdisposedexception

解决方案


推荐阅读