简体   繁体   中英

Powershell multiple AddParameter C#

I run a PowerShell from within a C# form application. I want to add multiple parameters to my PowerShell command.

But when I enter a second AddParameter call, it failed with the error:

System.Management.Automation.ParameterBindingException

Code:

PowerShell shell = PowerShell.Create().AddCommand("Get-NetAdapter");
shell.AddParameter("name", "Ethernet*");
shell.AddParameter("InterfaceIndex", "5");

foreach (PSObject result in shell.Invoke())
{
    Console.WriteLine("{0,-24}{1}", result.Members["Name"].Value,
                                    result.Members["InterfaceDescription"].Value);
} // End foreach.

It looks like it only accepts 1 parameter.

There is also a AddParameters , but I'm not able to get this working.

Anyone got any experience with this?

You can't actually use name and InterfaceIndex at the same time with the Get-NetAdapter cmdlet. This is because they belong to different Parameter Sets and as a result must be used separately.

To see details of the Parameter Sets for that cmdlet see here: https://technet.microsoft.com/en-us/library/jj130867(v=wps.630).aspx

Or use Get-Help Get-NetAdapter in PowerShell.

However if you are still having issues adding parameters when using ones that are permitted in the same parameter set, you could try adding both parameters as a single command, like this (using name and throttlelimit as an example, as they are permitted in the same Parameter Set: ByName for Get-NetAdapter ):

PowerShell shell = PowerShell.Create().AddCommand("Get-NetAdapter")
                                      .AddParameter("name", "Ethernet*")
                                      .AddParameter("ThrottleLimit", 5);

Or alternatively you can use a dictionary of parameter names and values:

IDictionary parameters = new Dictionary<String, String>();
parameters.Add("name", "Ethernet*");
parameters.Add("ThrottleLimit", 5);

PowerShell shell = PowerShell.Create().AddCommand("Get-NetAdapter")
   .AddParameters(parameters)

Source: https://msdn.microsoft.com/en-us/library/dn614674(v=vs.85).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM