如何从c#传递参数到power shell脚本?/

时间:2018-03-27 10:29:30

标签: c# powershell visual-studio-2013

如何通过从c#传递参数到Powershell脚本来调用c#中的以下PowerShell脚本(我的参数是字符串和列表类型)

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 

请你详细解释一下。

我想通过使用相同的代码从c#调用以下PowerShell脚本。

1 个答案:

答案 0 :(得分:-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();