PowerShell + C#: Accessing the Current Runspace And Adding a Snap-In

NOTE: This post – drafted, composed, written, and published by me – originally appeared on https://blogs.technet.microsoft.com/johnbai and is potentially (c) Microsoft.

I’ve been coding an assembly for import into the Exchange Management Shell (EMS) in C# for some time. One of the problems that I ran into was how to load the Support assembly, since it’s not imported into the RunSpace by default. After a while of testing/trying/failing and repeat ad nauseam, I found the answer in the form of what I consider to be a cheat.

You see, when the module is loaded, I’m depending on the current runspace as it exists to execute commands. There’s no proper way to access the runspace that you’re currently executing to modify it’s configuration by adding the snap-in.

So, we arrive at the “cheat”:

// We use the current runspace to cast our calls into.
// This grants us access to the current runspace, instead of instantiating a new one.
// More information on the PowerShell.Create method can be found here: https://msdn.microsoft.com/en-us/library/system.management.automation.powershell.create(v=vs.85).aspx
// More information on the RunspaceMode.CurrentRunspace enumeration value can be found here: https://msdn.microsoft.com/en-us/library/system.management.automation.runspacemode(v=vs.85).aspx
PowerShell initialPowerShell = PowerShell.Create(RunspaceMode.CurrentRunspace);

// More information on the PowerShell.AddScript method can be found here: https://msdn.microsoft.com/en-us/library/dd182436(v=vs.85).aspx
initialPowerShell.Commands.AddScript("Add-PSSnapin Microsoft.Exchange.Management.Powershell.Support");

// More information on the PowerShell.Invoke method can be found here: https://msdn.microsoft.com/en-us/library/dd182449(v=vs.85).aspx

If you’re wondering about the code comments: One of the ways that people learn is by searching for examples or questions related to the problem they’re trying to solve. This is something that I – admittedly – used to do. Once they find what they think might be the answer, they look at the methods/class in the documentation (at least, that’s what I used to do). So, I figured why not shorten the effort down for those who want to learn? 🙂

One thought on “PowerShell + C#: Accessing the Current Runspace And Adding a Snap-In

  1. YAY! I’ve been trying to figure out how to do this for hours. I was trying to set PowerShell.Runspace property to Runscape.DefaultRunscpace and kept getting the pipeline error below.

    “The pipeline was not run because a pipeline is already running. Pipelines cannot be run concurrently.”

Comments are closed.