locked
Executing powershell scripts in c# RRS feed

  • Question

  • Below is the script I am using to try and execute my powershell script but whenever i run it i just get a blank command window.

    C# Code

    static void Main(string[] args)
            {
                string text = System.IO.File.ReadAllText(@"C:\Program Files (x86)\Backup Reporter\Required\edit_website.ps1");
    
                using (PowerShell PowerShellInstance = PowerShell.Create())
                {
                    // use "AddScript" to add the contents of a script file to the end of the execution pipeline.
                    // use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
                    PowerShellInstance.AddScript(text);
    
                    Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
                    foreach (PSObject outputItem in PSOutput)
                    {
                        // if null object was dumped to the pipeline during the script then a null
                        // object may be present here. check for null to prevent potential NRE.
                        if (outputItem != null)
                        {
                            Console.WriteLine(outputItem.BaseObject.ToString() + "\n");
                        }
                    }
                    if (PowerShellInstance.Streams.Error.Count > 0)
                    {
                        Console.Write("Error");
                    }
                    Console.ReadKey();
                }
            }


    Powershell Script

    $text = "test test tes"

    All I want to do is output test to the command window. 

    Monday, May 8, 2017 7:29 PM

Answers

  • Jack,

    You're PowerShell script does not write anything to the output stream. Try this:

    $Text = "test test test"

    $Text


    Tim Curwick
    MadWithPowerShell.com

    • Proposed as answer by Just Karl Tuesday, May 9, 2017 3:21 PM
    • Marked as answer by xjacksssss Tuesday, May 9, 2017 6:21 PM
    Monday, May 8, 2017 10:18 PM