Running powershell from C#

本文关键字:from powershell Running | 更新日期: 2023-09-27 18:17:24

大家好,我是c#新手。我知道powershell。我想弄清楚如何从c#程序运行一个powershell脚本。我有以下工作作为自己的测试程序。然而,当我试图把更复杂的脚本,可以包括GUI窗口,应该弹出似乎没有运行。我的思路对吗?我还注意到,每行之后的分号需要在c#中正确运行脚本。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            using (PowerShell PS = PowerShell.Create())
            {
                PS.AddScript("$file = '"C:''test''csharp.txt'";"+
                "Set-Content -path $file -value '"testc'";");
                PS.Invoke();
            }

        }//end of main
 }//end of class
}//end of namespace

Running powershell from C#

只有UI线程可以做UI操作。从我所看到的,你的PS.Invoke()创建了自己的线程,我没有找到任何可以让你把它提升到UI线程的东西。