簡體   English   中英

從C#運行PowerShell腳本

[英]Run a PowerShell script from C#

我正在嘗試使用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腳本,但出現錯誤

名稱過程未定義

在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命令

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM