Saturday, August 5, 2023

How to call PowerShell command -let or PowerShell script from C#


We can call poweshell command-let from C#


```sh 

Install Powershell SDK package then  Add reference of System.Management.Automation
  #Install-Package Microsoft.PowerShell.SDK#
  #dotnet add package Microsoft.PowerShell.SDK
```

Following is the code to invoke powershell command-let

```sh
#usings -
  using System.Management.Automation;
  using System.Management.Automation.Runspaces;


  using (PowerShell ps = PowerShell.Create()){
      ps.AddCommand("Get-Process");
      ps.AddParameter("Name", "excel");

      foreach (PSObject result in ps.Invoke()){
         Console.WriteLine(result);
      }
}

```

We can call powershell script file  from C#

```sh
Following is the code to invoke powershell  script

#usings
 using System.Management.Automation;
 using System.Management.Automation.Runspaces;

 var ps1File = @"C:\Users\\install-scheme.ps1";
 var startInfo = new ProcessStartInfo(){
                FileName = "powershell.exe",
                Arguments = $"-NoProfile -ExecutionPolicy ByPass -File \"{ps1File}\"",
                UseShellExecute = false
            };
 Process.Start(startInfo);
```

We can invoke powershell command-let \cli from C# using CliWrap 

```sh 
#Install Package 
dotnet add package CliWrap -Version 3.6.4 # Install-Package CliWrap -Version 3.6.4

# using 
  using CliWrap;
  using CliWrap.Buffered;
  using System;
  using System.Threading;
  using System.Threading.Tasks;
   


var result= await cli.Wrap("powershell")
                     .WithArguments(new[]{"Get-Process"," -Name",\"devenv"})
                     .ExecuteBufferedASync();
Console.WriteLine(result.StandardOutput);
Console.WriteLine(result.StandardError);

```




```

No comments:

Post a Comment