Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a PowerShell script from C#

Tags:

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.

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""");
}

I want to launch my .ps1 script but I get an error

name process is not defined

like image 260
Rhon Yz Avatar asked May 13 '19 10:05

Rhon Yz


1 Answers

Calling C# code in Powershell and vice versa

C# in Powershell

$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#

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();
        }

So, your query is also really a duplicate of many similar posts on stackoverflow.

Powershell Command in C#

like image 186
postanote Avatar answered Oct 25 '22 06:10

postanote