2

In my C# app, I have to run some PowerShell scripts. I copied paste from this site code about how to run the scripts.

My question: suppose I want to use the code from the link, how can I extract the PowerShell output to some string or to some .txt file?

EDIT:

If you want to test this code for answering this post, you need:

  • add reference to System.Management.Automation dll
  • add requireAdministrator inside app.manifest
1
  • Redirect it.. just like any other shell. That's a pretty bad article as a side-note. Commented Jun 2, 2018 at 13:53

1 Answer 1

1

Based on this link, you can extract the output with Collection<PSObject> results = pipeline.Invoke();, here a code example, note this would extract the PowerShell output to StringBuiler and would hide the PowerShell window:

 string RunScript(string pathToYourScript){
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

            using (var runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
            {
                runspace.Open();
                runspace.SessionStateProxy.SetVariable("prog", this);

                using (Pipeline pipeline = runspace.CreatePipeline())
                {
                    if (!string.IsNullOrEmpty(path))
                        pipeline.Commands.AddScript(string.Format("$env:path = \"{0};\" + $env:path", pathToYourScript));

                    pipeline.Commands.AddScript(path);
                    pipeline.Commands.Add("Out-String");

                    Collection<PSObject> results = pipeline.Invoke();
                    StringBuilder stringBuilder = new StringBuilder();
                    foreach (PSObject obj in results)
                    {
                        stringBuilder.AppendLine(obj.ToString());

                    }

                    var outDefault = new Command("out-default");
                    outDefault.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                    pipeline.Commands.Add(outDefault);

                    return stringBuilder;
                    }

                }
            }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.