Rhon Yz
Rhon Yz

Reputation: 155

Run a PowerShell script from C#

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

Upvotes: 11

Views: 21253

Answers (3)

postanote
postanote

Reputation: 16076

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

Upvotes: 6

haseakash
haseakash

Reputation: 79

string path = @"C:\1.ps1";

Process.Start(new ProcessStartInfo("Powershell.exe",path) { UseShellExecute = true })

Upvotes: 2

J.Tribbiani
J.Tribbiani

Reputation: 530

Here's what it worked for me, including cases when the arguments contains spaces:

using (PowerShell PowerShellInst = PowerShell.Create())
        {

            PowerShell ps = PowerShell.Create();
            
            string param1= "my param";
            string param2= "another param";
            string scriptPath = <path to script>;

            ps.AddScript(File.ReadAllText(scriptPath));

            ps.AddArgument(param1);
            ps.AddArgument(param2);

            ps.Invoke();
         
        }

The .ps1 file would be something as this (make sure you declare the parameters in the .ps1 script):

Param($param1, $param2)

$message = $param1 + " & " + $param2"
[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
[System.Windows.Forms.MessageBox]::Show($message)

I find this approach very easy to understand and very clear.

Upvotes: 2

Related Questions