0

I am calling a PowerShell script from c# within an ASP page. The script executes just fine but the output (write-host) of my PowerShell does not get captured. I would like to be able to capture any output back into the ASP page.

The following is is my current code.

    protected void ExecuteInputClick(object sender, EventArgs e)
        {
            Result.Text = string.Empty;

            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
            runspace.Open();

            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

            Pipeline pipeline = runspace.CreatePipeline();

            string scriptfile = "C:\\PRJ_Templates\\CreateProject.ps1";

            Command myCommand = new Command(scriptfile);
            CommandParameter DestDirParam = new CommandParameter("DestinationDirectory", DropDownList1.SelectedValue);
            CommandParameter ProjNamParam = new CommandParameter("ProjectName", Input.Text);
            myCommand.Parameters.Add(DestDirParam);
            myCommand.Parameters.Add(ProjNamParam);

            pipeline.Commands.Add(myCommand);

            try
            {
                System.Collections.ObjectModel.Collection<PSObject> results = pipeline.Invoke();
                runspace.Close();
                StringBuilder stringBuilder = new StringBuilder();
                foreach (PSObject obj in results)
                {
                    stringBuilder.AppendLine(obj.ToString());
                }
                Result.Text = Server.HtmlEncode(stringBuilder.ToString());
            }
            catch (ActionPreferenceStopException Error) { Result.Text = Error.Message; }
            catch (RuntimeException Error) { Result.Text = Error.Message; }
        }

Any thought why the write-host is not getting put into Results?

Ali
  • 2,702
  • 3
  • 32
  • 54
Jo Re
  • 1
  • 1
  • 1
    `.Invoke()` only captures what goes to the _success output stream_ (via `Write-Output` or, more typically, via _implicit_ output). By contrast, any other streams have to be accessed via the `.Streams` property, including the information stream that `Write-Host` writes to. – mklement0 Feb 14 '20 at 03:35
  • More broadly: [`Write-Host` is typically the wrong tool to use](http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/), unless the intent is to write _to the display only_, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, redirect it to a file. To output a value, use it _by itself_; e.g., `$value` instead of `Write-Host $value` (or use `Write-Output $value`, though that is rarely needed). See also: the bottom section of https://stackoverflow.com/a/50416448/45375 – mklement0 Feb 14 '20 at 03:37

0 Answers0