1

I have written a C# Tool where i can enter script parameters with an GUI which is generated based on the parmeter definitions of the script.

Now i want to have a dropdown list which offers me a dynamically generated set of values. The informations for this dropdown list should come from the parameter definition of the script.

(In my case i want to select an existing AD OU by Listing all Child-Objects of the Base OU.)

One way to get a list of valid parameters is to use "ValidateSet" for Parameter definition. There is abway to get te ValidateSet from the Script an build the dropdown list. But ValidateSet is a static deffinition and i have to update the script each time the list should be changed.

A good way for dynamic validation is "ValidateScript". The script command would be something like Test-Path. This would work for validation, but for my GUI i would not be able to generate a list of valid values.

Maby i can dynamically generate a custom enum type and use it as parameter type. A dropdown list for enum types is already implemented for GUI. But i think i's not a good idea and may not work to generate a enum type dynamically.

So, any other ideas for a list of valid values which is dynamically built?

4

3 回答 3

0

我曾经尝试使用枚举来执行此操作,但由于枚举值和 AD 名称之间的有效字符集不同,它出现了问题。

如果您希望将 GUI 与脚本分开,您可以研究使用 AST 从脚本中提取参数验证代码,然后在脚本之外运行它以构建您的列表。

于 2015-02-08T03:23:45.177 回答
0

您可以在 Powershell 脚本中使用动态参数。可以在此处找到从脚本块动态生成并添加到动态参数的 ValidateSet 参数属性的一个很好的示例:

http://blogs.technet.com/b/pstips/archive/2014/06/10/dynamic-validateset-in-a-dynamic-parameter.aspx

于 2015-02-09T16:58:29.777 回答
0

DynamicParam 适用于 PowerShell.exe。

但是我在使用 C# 程序读取 ValidateSet 时遇到问题。

这是我使用的代码:

InitialSessionState initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new string[] { @"C:\Users\kritzinger\OneDrive\Test-DynamicValidateSet.psm1" });
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();

PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.Commands.AddCommand("Get-Command").AddArgument("Test-DynamicValidateSet").AddParameter("ArgumentList", "Path");
Collection<PSObject> get_Command = ps.Invoke();
PSObject command = get_Command[0];
Dictionary<String, ParameterMetadata> parameters = command.Properties["parameters"].Value as Dictionary<String, ParameterMetadata>;

在最后一行我尝试访问值时收到以下异常:

System.Management.Automation.dll 中出现“System.Management.Automation.GetValueInvocationException”类型的未处理异常

附加信息:获取“参数”的异常:“无法检索 cmdlet 的动态参数。管道已停止。”

当我尝试访问 VisualStudio Watch 窗口中的值时,我得到了相同的异常。

使用静态 ValidateSet 定义,c# 代码运行良好。

于 2015-02-15T12:17:38.707 回答