You can invoke a cmdlet from managed code in more than one way. This article explains how to use the Pipeline class to invoke a cmdlet.
First, create a new instance of the Pipeline class by using the runspace that you created. The following example shows how to create a new instance of the Pipeline class.
RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
PSSnapInException snapInException = null;
PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException);
Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);
myRunSpace.Open(rsConfig);
Pipeline pipeLine = myRunSpace.CreatePipeline();
Dim rsConfig as RunspaceConfiguration
rsConfig = RunspaceConfiguration.Create()
Dim snapInException as PSSnapInException
Dim info as PSSnapInInfo
info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException)
Dim myRunSpace as Runspace
myRunSpace = RunspaceFactory.CreateRunspace(rsConfig)
myRunSpace.Open()
Dim pipeLine as Pipeline
pipeLine = myRunSpace.CreatePipeline()
Next, create an instance of the Command class by using the name of the cmdlet that you want to run. The following code creates an instance of the Command class that will run the Get-Command cmdlet.
Command myCommand = new Command("Get-Command");
Dim myCommand as New Command("Get-Command")
Next, add the command to the Commands collection of the pipeline.
pipeLine.Commands.Add(myCommand);
pipeLine.Commands.Add(myCommand)
Now, call the Pipeline.Invoke method to run the command.
Collection<PSObject> commandResults = pipeLine.Invoke();
Dim commandResults As Collection(Of PSObject)
commandResults = pipeLine.Invoke()
This code invokes the cmdlet(s) in the Commands collection of the pipeline and returns a collection of objects that are derived from the PSObject class. The following code puts together all of the previous code examples.
RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
PSSnapInException snapInException = null;
PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException);
Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);
myRunSpace.Open();
Pipeline pipeLine = myRunSpace.CreatePipeline();
Command myCommand = new Command("Get-Command");
pipeLine.Commands.Add(myCommand);
Collection<PSObject> commandResults = pipeLine.Invoke();
Dim rsConfig as RunspaceConfiguration
rsConfig = RunspaceConfiguration.Create()
Dim snapInException As PSSnapInException
info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException)
Dim myRunSpace As Runspace
myRunSpace = RunspaceFactory.CreateRunspace(rsConfig)
myRunSpace.Open()
Dim pipeLine As Pipeline
pipeLine = myRunSpace.CreatePipeline()
Dim myCommand As New Command("Get-Command")
pipeLine.Commands.Add(myCommand)
Dim commandResults As Collection(Of PSObject)
commandResults = pipeLine.Invoke()