In powershell some parameter have a dynamic auto complete behavior. For Example, Get-Process the parameter Name. I can iterate trough all my processes with TAB.
I want to use this behavior in my PSCmdlet.
But the problem is, I only know how to do this with static auto complete valuee. See the example:
public class TableDynamicParameters
{
[Parameter]
[ValidateSet("Table1", "Table2")]
public string[] Tables { get; set; }
}
Here an example how this is done with native powershell http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/21/use-dynamic-parameters-to-populate-list-of-printer-names.aspx
It works thx to @bouvierr
public string[] Tables { get; set; }
public object GetDynamicParameters()
{
if (!File.Exists(Path)) return null;
var tableNames = new List<string>();
if (TablesCache.ContainsKey(Path))
{
tableNames = TablesCache[Path];
}
else
{
try
{
tableNames = DbContext.GetTableNamesContent(Path);
tableNames.Add("All");
TablesCache.Add(Path, tableNames);
}
catch (Exception e){}
}
var runtimeDefinedParameterDictionary = new RuntimeDefinedParameterDictionary();
runtimeDefinedParameterDictionary.Add("Tables", new RuntimeDefinedParameter("Tables", typeof(String), new Collection<Attribute>() { new ParameterAttribute(), new ValidateSetAttribute(tableNames.ToArray()) }));
return runtimeDefinedParameterDictionary;
}
From MSDN: How to Declare Dynamic Parameters
Your Cmdlet
class must implement the IDynamicParameters
interface. This interface:
Provides a mechanism for a cmdlet to retrieve parameters that can be added dynamically by the Windows PowerShell runtime.
EDIT:
The IDynamicParameters.GetDynamicParameters()
method should:
return an object that has properties and fields with parameter related attributes similar to those define in a cmdlet class or a RuntimeDefinedParameterDictionary object.
If you look at this link, the author is doing this in PowerShell. He creates at runtime:
- a new instance of
ValidateSetAttribute
with a runtime array of possible values - He then creates a
RuntimeDefinedParameter
onto which he assigns theValidateSetAttribute
- He returns a
RuntimeDefinedParameterDictionary
containing this parameter
You can do the same in C#. Your GetDynamicParameters()
method should return this RuntimeDefinedParameterDictionary
containing the appropriate RuntimeDefinedParameter
.
来源:https://stackoverflow.com/questions/25823910/pscmdlet-dynamic-auto-complete-a-parameter-like-get-process