获取异常"当前PowerShell实例的状态对此操作无效。"在尝试处理Powershell会话时?

时间:2015-03-18 07:19:23

标签: powershell visual-c++ exchange-server powershell-v2.0 powershell-remoting

我编写了VC ++代码,远程连接到Powershell并执行一些命令行开关。一旦执行了所有的命令行开关,我就必须处理会话。为此,我执行' Remove-PSSession'然后删除Powershell和runspace对象。但是在执行Remove-PSSession时,我得到以下异常。 "当前PowerShell实例的状态对此操作无效。"。这是我处理会话的代码。我不确定在执行Remove-PSSession或其他地方时是否抛出了异常,但我确定它在这个块中被抛出。

PSCommand^ rmcommand = gcnew PSCommand();
    rmcommand->AddScript("Remove-PSSession $session");
    ps->Commands = rmcommand;
    ps->Invoke();           
    if(runSpace != nullptr)
    {
        delete runSpace;
    }
    if(ps!=nullptr)
    {
        delete ps;
    }

这里runSpace是运行空间对象,ps是Powershell对象。由于我得到了这个例外,我无法处理会话。请赐教。

1 个答案:

答案 0 :(得分:0)

Is it possible that you're reusing the PowerShell/Runspace instances for multiple command invocations without first disposing of them? I've seen this error when attempting to do so. Try creating a new instance of PowerShell and the Runspace for your removal command.
相关问题