[英]Run a PowerShell script from C#
I'm trying to build a graphic platform using Visual Studio. 我正在尝试使用Visual Studio构建图形平台。 And I'm not a developer, I want to run PowerShell or batch files when I click a button.
我不是开发人员,我想在单击按钮时运行PowerShell或批处理文件。 Thing is when I'm trying C# syntax it does not work even if I installed PowerShell extension.
问题是,即使我安装了PowerShell扩展,在尝试C#语法时也无法正常工作。
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. 我尝试使用
process.start
在互联网上找到的一些代码,或者在所有情况下都试图创建命令,但命令名称未定义且无法使用。
private void Button1_Click(object sender, EventArgs e)
{
Process.Start("path\to\Powershell.exe",@"""ScriptwithArguments.ps1"" ""arg1"" ""arg2""");
}
I want to launch my .ps1
script but I get an error 我想启动我的
.ps1
脚本,但出现错误
name process is not defined
名称过程未定义
Calling C# code in Powershell and vice versa 在Powershell中调用C#代码,反之亦然
C# in Powershell 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)
Powershell in C# C#中的Powershell
All the Powershell related functions are sitting in System.Management.Automation namespace, ... reference that in your project
所有与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();
}
So, your query is also really a duplicate of many similar posts on stackoverflow. 因此,您的查询实际上也是stackoverflow上许多类似帖子的重复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.