Search code examples
c#powershell

PSCommand vs PowerShell in System.Management.Automation


From the definition of PSCommand Class:

Defines a PowerShell command / script object which can be used with PowerShell object.

the definition of PowerShell class:

Represents a PowerShell command or script to execute against a Runspace(Pool) if provided, otherwise execute using a default Runspace. Provides access to different result buffers like output, error, debug, verbose, progress, warning, and information.

Apart from the buffers, what is the difference between the two. It seems redundant that both exist, so I wonder why I would use one over the other.


Solution

  • It seems redundant that both exist, so I wonder why I would use one over the other.

    There is no redundancy, PowerShell depends on PSCommand. PSCommand isn't a class you will be manually instantiating, or I can't think of a place where you would want to manually instantiate it. This class is instantiated in the .Commands property of a PowerShell instance and represents the collection of commands or scripts your instance will invoke when you call its *Invoke() methods.

    In addition, .Commands isn't usually a property you'll be interacting with directly as the PowerShell class has APIs wrapping its PSCommand member, see PowerShell.cs#L975-L1496. All Add*() methods will direct the call to _psCommand.Commands except for .Clear().