2

My application hosts PowerShell and adds COM object references via RunSpace.SessionStateProxy.SetVariable(). After adding the variables and calling Invoke on some PowerShell code, the COM objects don't get released properly. How can I force all COM references (including those for temporary references returned by calling the COM object model) to be released by PowerShell and the .NET runtime? I tried calling

    object o = rs.SessionStateProxy.GetVariable(name);
    if (o != null)
    {
        rs.SessionStateProxy.SetVariable(name, null);
        Marshal.ReleaseComObject(o);
    }

on all the variables, as well PipeLine.Dispose(), Runspace.Close(), and GC.Collect(), but it didn't help.

3
  • 1
    You might try Marshal.FinalReleaseComObject although I wonder if there is some other script/command that is holding onto a reference besides the variable you null out. Commented Feb 10, 2011 at 16:53
  • That didn't help either. I'm not sure what other script/command could be involved -- the behavior occurs even if the PowerShell code doesn't call these objects (i.e., the variables are set but never used). Commented Feb 10, 2011 at 17:08
  • I figured it out -- when storing the variables, temporary references were getting created: rs.SessionStateProxy.SetVariable("name", obj.subobj). If I instead store the return value of obj.subobj in a variable and release after calling SetVariable, everything works as expected. Thanks. Commented Feb 10, 2011 at 17:17

1 Answer 1

2

Based on Keith's tip, I tracked this down. When storing the variables, temporary references were getting created:

RunSpace.SessionStateProxy.SetVariable("name", obj.subobj)

If I instead store the return value of obj.subobj in a variable and ReleaseComObject on the local variable after calling SetVariable, everything works as expected.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.