5

I want to know the difference between executing PowerShell script in C# using the Pipeline class versus the PowerShell class.

Using Pipeline :

Pipeline pipe = runspace.CreatePipeline();

Using PowerShell class:

PowerShell ps = PowerShell.Create();

We can use both of them to execute PowerShell script in C#, but what is the difference between them?

0

2 Answers 2

6

Note: The PowerShell SDK documentation is terse, so the following is speculative.

  • An instance of the PowerShell class is a wrapper for a runspace, the container in which a PowerShell session runs; its .Runspace property returns the enclosed runspace.

  • You need a runspace (Runspace instance) in order to create and execute a pipeline for executing arbitrary PowerShell statements.

  • To create a pipeline, you have two options:

    • If you have a PowerShell instance, you can use its convenience methods such as .AddScript() to implicitly create a pipeline.

    • Alternatively, use a runspace's .CreatePipeline() method to create and manage a pipeline explicitly.

Simply put: The convenience methods of the PowerShell class allow simpler creation and execution of pipelines.

Note that both approaches support executing multiple statements, including any mix of commands (e.g., cmdlet invocations such as Get-Date) and expressions (e.g.,1 + 2).

The following snippet compares the two approaches (using PowerShell itself), which are functionally equivalent, from what I can tell:

# Create a PowerShell instance and use .AddScript() to implicitly create
# a pipeline that executes arbitrary statements.
[powershell]::Create().AddScript('Get-Date -DisplayHint Date').Invoke()

# The more verbose equivalent using the PowerShell instance's .RunSpace
# property and the RunSpace.CreatePipeline() method.
[powershell]::Create().RunSpace.CreatePipeline('Get-Date -DisplayHint Date').Invoke()

There may be subtleties that I'm missing; do tell us, if so.

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

Comments

3

You should read the documentation. A pipeline is a feature of a runspace. The PowerShell.Create() method will create a PowerShell object, a kind of wrapper for everything contained. Both of these methods belong to the same PowerShell SDK.

The Pipeline is intended to run commands and is underneath the runspace object.

More

Pipeline Class (msdn)

PowerShell Class (msdn)

1 Comment

@mklement0 I've updated my answer, but my understanding of the paradigm is the PowerShell type is a kind of wrapper and handles the runspace/pipeline setup/teardown while those other methods (using runspacefactory and Runspace.CreatePipeline are lower-level details you can manipulate.

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.