如何使用C#在PowerShell的单个脚本块中运行多个命令?

如何使用C#在PowerShell的单个脚本块中运行多个命令?,c#,powershell,powershell-3.0,C#,Powershell,Powershell 3.0,我试图在一个脚本中执行多个PS命令,但它引发了一个异常。我尝试了不同的选择,但没有成功 using (powershell = PowerShell.Create()) { command = new PSCommand(); command.AddCommand("Invoke-Command"); command.AddParameter("ScriptBlock", System.Management.Automation.ScriptBlo

我试图在一个脚本中执行多个PS命令,但它引发了一个异常。我尝试了不同的选择,但没有成功

 using (powershell = PowerShell.Create())
 {
    command = new PSCommand();
    command.AddCommand("Invoke-Command");
    command.AddParameter("ScriptBlock",
          System.Management.Automation.ScriptBlock.Create(
           "New-MailContact -Name '" + txtEmail.Text + "' -ExternalEmailAddress '" + txtEmail.Text + "';" ));
     command.AddParameter("ScriptBlock",
           System.Management.Automation.ScriptBlock.Create(
           "Set-MailContact -Identity '" + txtEmail.Text + "'-HiddenFromAddressListsEnabled $true"));


    command.AddParameter("Session", session);
    powershell.Commands = command;
    powershell.Runspace = runspace;
    result = powershell.Invoke();
    if (powershell.Streams.Error.Count > 0 || result.Count != 1)
    {
         if (powershell.Streams.Error[0].ToString().ToLowerInvariant().Contains("already exists"))
         {
               return;
          }
          else
          {
               throw new Exception("Fail to establish the connection");
           }
       }
      }
无法绑定参数,因为多次指定了参数“ScriptBlock”。要为可以接受多个值的参数提供多个值,请使用数组语法。例如,“-参数值1、值2、值3”

我也试过了

command.AddParameter("ScriptBlock",
   System.Management.Automation.ScriptBlock.Create(
   "New-MailContact -Name '" + txtEmail.Text + "' -ExternalEmailAddress '" + txtEmail.Text + "';" +  " Set-MailContact -Identity '" + txtEmail.Text + "'-HiddenFromAddressListsEnabled $true"));


我认为您可以简化代码—您不需要使用
Invoke命令
ScriptBlock
元素来分别调用单个命令—您可以直接调用cmdlet

如果使用参数构建命令,还可以同时解决@madreflection引起的脚本注入问题

下面是PowerShell中的一个版本(对我来说,测试比旋转一个示例C#项目更容易:-),您可以将其转换为C#:

$p=[System.Management.Automation.PowerShell]::Create()
$c=新对象系统.管理.自动化.运行空间.命令(“新邮件联系人”);
$c.Parameters.Add(“Name”,$Name)
$c.Parameters.Add(“ExternalEmailAddress”,$address)
$null=$p.Commands.AddCommand($c)
$c=新对象系统.管理.自动化.运行空间.命令(“设置邮件联系人”);
$c.Parameters.Add(“Identity”、$Identity)
$c.Parameters.Add(“HiddenFromAddressListsEnabled”,$hidden)
$null=$p.Commands.AddCommand($c)
$p.Invoke()
更新-啊,刚才注意到您正在使用
调用命令
上的
会话
参数-如果您使用远程处理执行它,那么您可能毕竟需要
调用命令
。也许这个答案会有帮助


只需添加另一个:
var anotherCommand=powershell.Commands.AddCommand()我不得不指出,您有命令注入漏洞。您需要通过将撇号加倍(类似于SQL)来转义撇号,以便输入中的撇号不会关闭字符串并允许用户输入的命令跟随。这样的输入可能非常危险:
;删除项目\-递归-强制#
command.AddParameter("ScriptBlock",
   System.Management.Automation.ScriptBlock.Create(
   "(New-MailContact -Name '" + txtEmail.Text + "' -ExternalEmailAddress '" + txtEmail.Text + "')" +  " Set-MailContact -Identity '" + txtEmail.Text + "'-HiddenFromAddressListsEnabled $true"));