【发布时间】:2020-02-25 23:53:57
【问题描述】:
我正在尝试在单个脚本中执行多个 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”。要为可以接受多个值的参数提供多个值,请使用数组语法。比如“-参数value1,value2,value3”。
我也试过了
command.AddParameter("ScriptBlock",
System.Management.Automation.ScriptBlock.Create(
"New-MailContact -Name '" + txtEmail.Text + "' -ExternalEmailAddress '" + txtEmail.Text + "';" + " Set-MailContact -Identity '" + txtEmail.Text + "'-HiddenFromAddressListsEnabled $true"));
和
command.AddParameter("ScriptBlock",
System.Management.Automation.ScriptBlock.Create(
"(New-MailContact -Name '" + txtEmail.Text + "' -ExternalEmailAddress '" + txtEmail.Text + "')" + " Set-MailContact -Identity '" + txtEmail.Text + "'-HiddenFromAddressListsEnabled $true"));
【问题讨论】:
-
再添加一个:
var anotherCommand = powershell.Commands.AddCommand(); -
我不得不指出你有命令注入漏洞。您需要通过将撇号加倍(类似于 SQL)来转义撇号,以便输入中的撇号不会关闭字符串并允许用户输入的命令跟随。这样的输入可能非常危险:
'; Remove-Item \ -Recurse -Force #
标签: c# powershell powershell-3.0