-2

How can i call the below PowerShell script from c# .. by passing arguments to Powershell script from c# (my arguments are string and list types)

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"powershell.exe";
//provide powershell script full path
**startInfo.Arguments = @"& 'C:\powershell-scripts\call-from-c-sharp.ps1'";** 
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
// execute script call start process
process.Start();
// get output information
string output = process.StandardOutput.ReadToEnd();

// catch error information
string errors = process.StandardError.ReadToEnd();

------------------------------------------------------------------------------

Function Server($x,[string]$lsstr)
{
  Remove-Item -Path D:\vamc\Powershell_scripts\di.txt

  $server=$x
  #Invoke-WmiMethod -ComputerName $server

  foreach($act in $lsstr)
  {        
      If( $act -eq 1 )
      {
          Remove-Item -Path D:\vamc\Powershell_scripts\di1.txt
      }
      ElseIf($act -eq 2)
      { 
         Remove-Item -Path D:\vamc\Powershell_scripts\di2.txt
      }
      ElseIf($act -eq 3)
      {
        Remove-Item -Path D:\vamc\Powershell_scripts\di3.txt
      }
      ElseIf($act -eq 4)
      {
         Remove-Item -Path D:\vamc\Powershell_scripts\di4.txt
      }
      Else
      {
         Write-Host "Invalid selection"
      }
  }
}

Server 

Can you please give me the detail code explanation.

I want to call the below PowerShell script from c# by using the same code.

Vincent K
  • 1,326
  • 12
  • 19

1 Answers1

-1
PowerShell powerShell = PowerShell.Create();

// Add and invoke your PS script

powerShell.AddCommand("Import-Module").AddParameter("Name",  "path\yourPSScript.ps1");
powerShell.Invoke();

powerShell.Commands.Clear();

//Add your function
powerShell.AddCommand("Server");

//Add attributes
powerShell.AddParameter("parameter1", value);
powerShell.AddParameter("parameter2", value);

//invoke
powerShell.Invoke();
  • Thanks Jens:) -- can i send list values to parameter 2 ... ??? can you help on this ? like what should i place in parameter1, parameter2 and value1 and value2. – Vamsi Krishna Mar 27 '18 at 13:03
  • I don't think PowerShell supports generic lists without including some .NET, but perhaps it could work with `param([System.Collections.Generic.List[string]]$lsstrt)` – Jens Tore Fremmegaard Mar 27 '18 at 13:19