在C#中执行Powershell脚本

在C#中执行Powershell脚本

本文介绍了在C#中执行Powershell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我用来尝试执行Powershell脚本的脚本,但是每当我运行它时,我都会得到一个空白的命令窗口。

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.

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脚本



Powershell Script

 $text = "test test test"

我要做的就是将测试输出到命令窗口。

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

推荐答案

您可以使用Write-Output代替Write-主办。从winform应用程序调用时,它对我有用。

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

这篇关于在C#中执行Powershell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 16:30