Invoking C# powershell cmdlets from another powers

2019-08-29 04:06发布

Here is my scenario : I have add-data and add-bulkdata cmdlets, both are written in C# deriving from pscmdlet, add-bulkdata takes a csv file and each line is fed to add-data cmdlet. Add-data cmdlet might throw terminating exceptions, if it does I dont know how to receive it in the add-bulkdata cmdlet, in bulkdata cmdlet I get a commandinvocationexception but it does not have the ErrorRecord that the underlying add-data had set. Also if I query pipeline.errors it gives me no information.

What is the best way to handle such scenario?

My Add-Bulkdata ProcessRecord() function looks something like this :

InitialSessionState initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new[] { @"C:\mybinary.dll" });
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.Add(cmd); //cmd is add-data cmdlet
pipeline.Commands.Add("out-string"); // I have tried with and without this

Collection<PSObject> results = pipeline.Invoke();
Collection<object> errors = pipeline.Error.ReadToEnd();

0条回答
登录 后发表回答