从C#运行PowerShell脚本

时间:2019-05-13 10:23:54

标签: c# powershell

我正在尝试使用Visual Studio构建图形平台。我不是开发人员,我想在单击按钮时运行PowerShell或批处理文件。问题是,即使我安装了PowerShell扩展,在尝试C#语法时也无法正常工作。

我尝试使用process.start在互联网上找到的一些代码,或者在所有情况下都试图创建命令,但命令名称未定义且无法使用。

private void Button1_Click(object sender, EventArgs e)
{
    Process.Start("path\to\Powershell.exe",@"""ScriptwithArguments.ps1"" ""arg1"" ""arg2""");
}

我想启动我的.ps1脚本,但是出现错误

  

名称过程未定义

1 个答案:

答案 0 :(得分:0)

Calling C# code in Powershell and vice versa

Powershell中的C#

$MyCode = @"
public class Calc
{
    public int Add(int a,int b)
    {
        return a+b;
    }

    public int Mul(int a,int b)
    {
        return a*b;
    }
    public static float Divide(int a,int b)
    {
        return a/b;
    }
}
"@

Add-Type -TypeDefinition $CalcInstance
$CalcInstance = New-Object -TypeName Calc
$CalcInstance.Add(20,30)

C#中的Powershell

  

所有与Powershell相关的功能都位于   System.Management.Automation命名空间,...在您的项目中引用

 static void Main(string[] args)
        {
            var script = "Get-Process | select -Property @{N='Name';E={$_.Name}},@{N='CPU';E={$_.CPU}}";

            var powerShell = PowerShell.Create().AddScript(script);

            foreach (dynamic item in powerShell.Invoke().ToList())
            {
                //check if the CPU usage is greater than 10
                if (item.CPU > 10)
                {
                    Console.WriteLine("The process greater than 10 CPU counts is : " + item.Name);
                }
            }

            Console.Read();
        }

因此,您的查询实际上也是stackoverflow上许多类似帖子的重复。

Powershell Command in C#

相关问题