Hi,
I'm trying to pass a parameter to powershell from c# web app, but keep getting an error
Reason = {"The term 'Param($ds)\r\n\r\n$ds\r\n\r\n\r\n' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."}
my powershell script is as follows:
Param($ds)
write-host $ds
my c# is:
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;
}
i've followed some other threads but can't script to execute. My Powershell scripts executes if i run it from powershell console just calling the script and a parameter. if i remove Param($ds) from the powershell script it doesn't error.
can anyone help?
thanks.