在c#中执行powershell脚本

问题描述 投票:3回答:3

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

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"

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

c# powershell c#-4.0
3个回答
1
投票

您可以使用Write-Output而不是Write-Host。从winform应用程序调用时,它适用于我。


0
投票

您的代码似乎是正确的,但是您的脚本不提供任何输出。这就是为什么你没有看到脚本输出的原因。加:

Write-Host $text

这将为您提供在该行打印的输出:

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

0
投票

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

Write-Output $text
© www.soinside.com 2019 - 2024. All rights reserved.