10

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

D.J.
  • 3,644
  • 2
  • 15
  • 22
Rhon Yz
  • 145
  • 1
  • 1
  • 8
  • use 'System.Diagnostics.Process.Start(...)' or you add 'using System.Diagnostics;' to the top of your cs-file – D.J. May 13 '19 at 11:15
  • 1
    Is "name process is not defined" a compilation or run-time error? – harper May 13 '19 at 12:09
  • System.Diagnostics.Process.Start("path\to\Powershell.exe"); works, but when I define the path to my script it won't run it. – Rhon Yz May 13 '19 at 12:12
  • for example : System.Diagnostics.Process.Start("powershell.exe", "U:\\folder1\\folder2\\Test.ps1"); does not work – Rhon Yz May 13 '19 at 12:13
  • Does `File.Exists("U:\\folder1\\folder2\\Test.ps1")` ? – xdtTransform May 13 '19 at 12:14
  • Sure, the file exists – Rhon Yz May 13 '19 at 12:20
  • You could use PowerShell directly from C# code by using [PowerShell class](https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.powershell?view=pscore-6.2.0) from System.Management.Automation. Here is a link to [msdn blog](https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/) showing just that. – MadKarel May 13 '19 at 12:26
  • Possible duplicate of [Powershell Command in C#](https://stackoverflow.com/questions/1933126/powershell-command-in-c-sharp) – Nick.Mc May 14 '19 at 06:29
  • 1
    I think this https://stackoverflow.com/questions/527513/execute-powershell-script-from-c-sharp-with-commandline-arguments[link] could be helpful – techguy1029 Jun 03 '19 at 23:54

3 Answers3

6

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#

AHaleIII
  • 173
  • 1
  • 7
postanote
  • 15,138
  • 2
  • 14
  • 25
2
string path = @"C:\1.ps1";

Process.Start(new ProcessStartInfo("Powershell.exe",path) { UseShellExecute = true })
haseakash
  • 31
  • 1
  • 6
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/31276759) – MD. RAKIB HASAN Mar 16 '22 at 07:41
1

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.

J.Tribbiani
  • 454
  • 3
  • 9