从 C# 运行 PowerShell 脚本

Rho*_* Yz 11 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""");
}
Run Code Online (Sandbox Code Playgroud)

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

名称进程未定义

pos*_*ote 6

在 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 $MyCode
$CalcInstance = New-Object -TypeName Calc
$CalcInstance.Add(20,30)
Run Code Online (Sandbox Code Playgroud)

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();
        }
Run Code Online (Sandbox Code Playgroud)

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

C# 中的 Powershell 命令