首页 > 解决方案 > 从 C# 运行 PowerShell 脚本

问题描述

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

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

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

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

名称进程未定义

标签: c#powershell

解决方案


在 Powershell 中调用 C# 代码,反之亦然

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 上许多类似帖子的副本。

C# 中的 Powershell 命令


推荐阅读