passing parameters to powershell from c#

天大地大妈咪最大 提交于 2019-12-19 10:39:10

问题


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.


回答1:


Only scriptblocks, ps1/psm1 files and functions/filters can have a param block. The script you should be adding with AddScript should be of the form:

& { param($ds); $ds }

& is the call operator. In your example, you are trying to execute param as a command.

update

You must pass the arguments to the scriptblock like so:

& { param($ds); $ds } 42

This results in 42 being passesd to the scriptblock. Sticking script in with AddScript doesn't implicitly create a ps1 file. It's akin to you typing:

ps c:\> param($ds); $ds

...directly at the prompt; this is meaningless. Make sense?

-Oisin



来源:https://stackoverflow.com/questions/2594587/passing-parameters-to-powershell-from-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!