1

I have a Powershell script being executed from a C# program. Both use a C# dll with static memory. When the Powershell script is executed, it has access to the same data that the C# program set. Additionally, anything the Powershell script writes to the dll is available the next time the script is called.

I want them to be completely separate so that the Powershell script runs in its own environment and memory space.

Here is my code:

using ( var _powerShell = PowerShell.Create() )
            {
                try
                {
                    _powerShell.Runspace = null;
                    _powerShell.RunspacePool = null;
                    _powerShell.AddScript($"{scriptFile} {args}");
                    _powerShell.Invoke();
                }
                catch ( Exception ex )
                {
                    Console.WriteLine(ex.ToString());
                }
                finally
                {
                    _powerShell.Dispose();
                }
            }

I am guessing I need to create a new Powershell session or something? I'm stuck.

5
  • 1
    Process.Start. Commented Apr 4, 2018 at 0:47
  • And finally block is redundant Commented Apr 4, 2018 at 1:56
  • _powerShell.Runspace = RunspaceFactory.CreateOutOfProcessRunspace(null); Commented Apr 4, 2018 at 10:21
  • @PetSerAl this throws an InvalidRunspaceStateException Commented Apr 4, 2018 at 19:33
  • @usr1 You need to open runspace before you can use it. Commented Apr 4, 2018 at 19:56

1 Answer 1

1

Got the answer thanks to PetSerAI:

using ( _powerShell = PowerShell.Create() )
{
    try
    {
        var run = RunspaceFactory.CreateOutOfProcessRunspace(null);
        run.Open();
        _powerShell.Runspace = run;
        _powerShell.AddScript($"{scriptFile} {args}");
        _powerShell.Invoke();
    }
    catch ( Exception ex )
    {
        //do stuff
    }
}

update: So there is a bug in the above code... the newly crated runspace is not released until the end of the program. I had this code being called multiple times, which resulted in a hundred background powershell instances. Here is the fix:

using ( var run = RunspaceFactory.CreateOutOfProcessRunspace(null) )
{
    run.Open();
    using ( _powerShell = PowerShell.Create() )
    {
        try
        {
            _powerShell.Runspace = run;
            _powerShell.AddScript($"{scriptFile} {args}");
            _powerShell.Invoke();
        }
        catch ( Exception ex )
        {
            //do stuff
        }
    }
}
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.