If you can reference the class that your cmdlet implements, you can “call” the cmdlet by creating an instance of the class, set any properties that represent the parameters, and call the method Cmdlet.Invoke<T>(). Here is an example:
using System.Linq;
using System.Management.Automation;
namespace MyModule.Commands
{
[Cmdlet(VerbsLifecycle.Invoke, "AnotherCmdlet")]
public class InvokeAnotherCmdlet : Cmdlet
{
[Parameter(Mandatory = true)]
public string Username { get; set; }
protected override void ProcessRecord()
{
GetADUserCommand anotherCmdlet = new GetADUserCommand() {
CommandRuntime = this.CommandRuntime,
Username = this.Username
};
anotherCmdlet.Invoke<object>().ToArray();
}
}
[Cmdlet(VerbsCommon.Get, "ADUser")]
public class GetADUserCommand : Cmdlet
{
[Parameter(Mandatory = true)]
public string Username { get; set; }
protected override void ProcessRecord()
{
WriteVerbose($"Getting AD User '{Username}'");
}
}
}
A few notes:
- You might want to pass the property value of the
Cmdlet.CommandRuntimecalling Cmdlet to the called Cmdlet. This ensures that if your called cmdlet writes to streams of objects (for example, by calling WriteObject), these objects will go to the host. An alternative is to call the calling cmdlet to list the result of the method call Invoke<T>()on the calling cmdlet. Invoke<T>() . IEnumberable<T>. .