Is it possible to share properties and comments between Powershell cmdlets in C #?

When exposing a set of related functions in Powershell cmdlets, can you share property names and summary help to normalize them in cmdlets in the assembly?

I know that this can be done with derived classes, but this solution is inconvenient in the best case, when there are several cmdlets with different properties that need to be separated.

Here is a very simple example. I would like to share the Name property and all related comments so that they are the same for all N cmdlets that we produce, but I can't think of a good way to do this in C #. Ideally, any sharing would allow the specification of parameter attributes, such as Required or Position.

namespace FrozCmdlets { using System.Management.Automation; /// <summary> /// Adds a new froz to the system. /// </summary> [Cmdlet( VerbsCommon.Add, "Froz" )] public class AddFroz : Cmdlet { /// <summary> /// The name of the froz. /// For more information on the froz, see froz help manual. /// </summary> [Parameter] public string Name { get; set; } protected override void ProcessRecord() { base.ProcessRecord(); // Add the froz here } } /// <summary> /// Removes a froz from the system. /// </summary> [Cmdlet( VerbsCommon.Remove, "Froz" )] public class RemoveFroz : Cmdlet { /// <summary> /// The name of the froz. /// For more information on the froz, see froz help manual. /// </summary> [Parameter] public string Name { get; set; } protected override void ProcessRecord() { base.ProcessRecord(); // Remove the froz here } } } 
+7
source share
1 answer

Yes, there is a way to do this without inheriting from a common base class for parameters. This is not well documented, only hinted at in the note of the IDynamicParameters.GetDynamicParameters method. Here is a more detailed discussion of the topic.

First create a class with your common parameters declared as properties with [Parameter] attributes:

 internal class MyCommonParmeters { [Parameter] public string Foo { get; set; } [Parameter] public int Bar { get; set; } ... } 

Then, each Cmdlet that wants to use these common parameters must implement the IDynamicParameters interface in order to return a member instance of the MyCommonParameters class:

 [Cmdlet(VerbsCommon.Add, "Froz")] public class AddFroz : PSCmdlet, IDynamicParameters { private MyCommonParmeters MyCommonParameters = new MyCommonParmeters(); object IDynamicParameters.GetDynamicParameters() { return this.MyCommonParameters; } ... 

With this approach, the PowerShell parameter binder parameter will find and populate the parameters in the MyCommonParameters instance just as if they were members of the Cmdlet classes.

+3
source

All Articles