【问题标题】:How to pass arguments to the power shell script from c#?/ [duplicate]如何从 c# 将参数传递给 power shell 脚本?/ [重复]
【发布时间】:2018-09-05 17:19:59
【问题描述】:

我如何从 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 脚本。

【问题讨论】:

  • 对不起,这不一样..你能帮我解决这个问题吗?
  • 什么是“列表类型”参数?你能给我们举个例子吗?只要你坚持使用Process,你就会被限制在一个字符串中。
  • 列表 lsstr= 新列表(); if (IFS_startCb.Checked) { lsstr.Add("1");我想将此值作为参数发送。

标签: c# powershell visual-studio-2013


【解决方案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();

【讨论】:

  • 感谢 Jens :) -- 我可以将列表值发送到参数 2 ... ???你能帮忙吗?比如我应该在 parameter1、parameter2 和 value1 和 value2 中放置什么。
  • 我认为 PowerShell 不支持不包含一些 .NET 的通用列表,但也许它可以与 param([System.Collections.Generic.List[string]]$lsstrt) 一起使用
猜你喜欢
  • 2021-04-16
  • 2019-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-08
  • 1970-01-01
  • 1970-01-01
  • 2014-11-27
相关资源
最近更新 更多