How to call PowerShell cmdlet from binary (C #) module?

I am writing a custom binary (C #) Cmdlet, and from within this CmdLet I would like to call another Cmdlet PowerShell build (like Get-ADUser) and return the results to my Cmdlet. What is the best way to do this? Note. It seems that creating another PowerShell instance (as described here ) inside my custom Cmdlet is not the most efficient way to accomplish this.

I reviewed this question. However, he does not answer my question.

+4
source share
1 answer

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() {
                // Pass CommandRuntime of calling cmdlet to the called cmdlet (note 1)
                CommandRuntime = this.CommandRuntime, 

                // Set parameters
                Username = this.Username
            };

            // Cmdlet code isn't ran until the resulting IEnumerable is enumerated (note 2)
            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>. .
+2

Source: https://habr.com/ru/post/1606496/


All Articles