从 C# 运行 PowerShell 脚本 [英] Run a PowerShell script from C#
问题描述
我正在尝试使用 Visual Studio 构建图形平台.而且我不是开发人员,我想在单击按钮时运行 PowerShell 或批处理文件.问题是当我尝试 C# 语法时,即使我安装了 PowerShell 扩展,它也不起作用.
I'm trying to build a graphic platform using Visual Studio. And I'm not a developer, I want to run PowerShell or batch files when I click a button. Thing is when I'm trying C# syntax it does not work even if I installed PowerShell extension.
我尝试了一些在 Internet 上找到的代码,使用 process.start
或尝试在所有情况下创建命令,但命令的名称未定义且不起作用.>
I tried some code that I found on the internet, using process.start
or trying to create a command in all cases the name of the command is not defined and it does not work.
private void Button1_Click(object sender, EventArgs e)
{
Process.Start("path\to\Powershell.exe",@"""ScriptwithArguments.ps1"" ""arg1"" ""arg2""");
}
我想启动我的 .ps1
脚本,但出现错误
I want to launch my .ps1
script but I get an error
未定义名称进程
推荐答案
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 命名空间,...在您的项目中引用该名称
All the Powershell related functions are sitting in System.Management.Automation namespace, ... reference that in your project
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 上许多类似帖子的重复.
So, your query is also really a duplicate of many similar posts on stackoverflow.
这篇关于从 C# 运行 PowerShell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!