简体   繁体   中英

Executing powershell scripts in c#

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 test"

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

You can use Write-Output instead of Write-Host. It works for me while invoking from winform application.

You code seems to be correct, however your script does not give any output. So that is why you do not see the output of the script. Add:

Write-Host $text

This will give you output that is printed at the line:

Console.WriteLine(outputItem.BaseObject.ToString() + "\n");

你的脚本没有给出任何输出。你可以在脚本上使用命令write-output来获得输出。[as kpundir refer]

Write-Output $text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM