Executing powershell scripts in c#

吃可爱长大的小学妹 提交于 2020-05-15 02:08:27

问题


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.


回答1:


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




回答2:


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");



回答3:


Your script does not give any output.You could use the command write-output on your script, to have an output.[As kpundir refer]

Write-Output $text


来源:https://stackoverflow.com/questions/43855697/executing-powershell-scripts-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!