我正在尝试从C#web应用程序向PowerShell传递参数,但一直收到错误:
原因= {“术语'参数($ ds)\ r \ n \ r \ n $ ds \ r \ n \ r \ n \ n \ r \ n'无法识别为cmdlet函数的名称,检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。“}
我的Powershell脚本如下:
Param($ds)
write-host $ds
我的C#是:
protected void drpCluster_SelectedIndexChanged(object sender, EventArgs e)
{
// Looping through all the rows in the GridView
foreach (GridViewRow row in GridVMApprove.Rows)
{
if (row.RowState == DataControlRowState.Edit)
{
// create dynamic dropDowns for datastores
DropDownList drpDatastore = (DropDownList)row.FindControl("drpDatastore");
DropDownList drpCluster = (DropDownList)row.FindControl("drpCluster");
var Datacenter = "'" + drpCluster.SelectedValue + "'";
strContent = this.ReadPowerShellScript("~/scripts/Get-DatastoresOnChange.ps1");
this.executePowershellCommand(strContent, Datacenter);
populateDropDownList(drpDatastore);
}
}
}
public string ReadPowerShellScript(string Script)
{
// Read script
StreamReader objReader = new StreamReader(Server.MapPath(Script));
string strContent = objReader.ReadToEnd();
objReader.Close();
return strContent;
}
private string executePowershellCommand(string scriptText, string scriptParameters)
{
RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
PSSnapInException snapInException = null;
PSSnapInInfo info = rsConfig.AddPSSnapIn("vmware.vimautomation.core", out snapInException);
Runspace RunSpace = RunspaceFactory.CreateRunspace(rsConfig);
RunSpace.Open();
Pipeline pipeLine = RunSpace.CreatePipeline();
Command scriptCommand = new Command(scriptText);
pipeLine.Commands.AddScript(scriptText);
if (!(scriptParameters == null))
{
CommandParameter Param = new CommandParameter(scriptParameters);
scriptCommand.Parameters.Add(Param);
pipeLine.Commands.Add(scriptCommand);
}
// Execute the script
Collection<PSObject> commandResults = pipeLine.Invoke();
// Close the runspace
RunSpace.Close();
// Convert the script result into a single string
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
foreach (PSObject obj in commandResults)
{
stringBuilder.AppendLine(obj.ToString());
}
OutPut = stringBuilder.ToString();
return OutPut;
}
我已经关注了其他一些线程,但无法执行脚本。如果我从PowerShell控制台运行它,只调用脚本和参数,我的PowerShell脚本就会执行。如果我从PowerShell脚本中删除Param($ds)
,则不会出错。
有人可以帮忙吗?
感谢。
答案 0 :(得分:3)
只有脚本块,ps1 / psm1文件和函数/过滤器才能有param块。您应该使用AddScript添加的脚本应采用以下格式:
& { param($ds); $ds }
&安培;是呼叫运营商。在您的示例中,您尝试将param作为命令执行。
<强>更新强>
您必须将参数传递给scriptblock,如下所示:
&安培; {param($ ds); $ ds} 42
这导致42被传递给scriptblock。使用AddScript粘贴脚本不会隐式创建ps1文件。它类似于你输入:
ps c:\> param($ds); $ds
...直接提示;这毫无意义。有意义吗?
-Oisin