Question

I trying to run my custom PowerShell cmdlets from another custom cmdlets. The strange thing is that I can run my custom cmdlets manually from the Windows Powershell and it works, but when I try to trigger the same custom cmdlets it fails.

Powershell

Run-Demo code:

It's basically like this the Run-Demo: I know it missing the parameter, but 'never the less' it should find the cmdlets in PowerShell.

                Command cmd = new Command("Run-ContentInventory");
                Runspace runSpace = RunspaceFactory.CreateRunspace();
                runSpace.Open();
                Pipeline pipeline = runSpace.CreatePipeline();
                pipeline.Commands.Add(cmd);
                Collection<PSObject> output;
                output = pipeline.Invoke();
                foreach (PSObject psObject in output)
                {
                    Console.WriteLine(psObject);
                }

Thanks for any help!

Was it helpful?

Solution

The core of your problem is that you're creating a new runspace, which won't have your cmdlets loaded. This is something you should avoid, because it eats up a lot of memory, and creates a lot of problems in trying to synchronize the two runspaces.

The trick is to use a Pipeline. Declare a private field of type Pipeline, then, in your BeginProcessing, add:

 pipeline = Runspace.DefaultRunspace.CreateNestedPipeline();

Please dispose of the nested pipeline in EndProcessing.

In processrecord, your code should remain almost the same.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top