pen*_*owe 8 c# powershell cmdlet
在Powershell cmdlet中公开一组相关函数时,是否可以共享属性名称和摘要帮助以在程序集中跨cmdlet规范化这些函数?
我知道这可以通过派生类来完成,但是当有多个具有不同属性的cmdlet要共享时,此解决方案最多是尴尬的.
这是一个非常简单的例子.我想分享属性'Name'和所有相关的注释,以便它们在我们生成的N个cmdlet中是相同的,但我想不出在c#中执行此操作的好方法.理想情况下,任何共享都允许指定参数属性,例如Mandatory或Position.
namespace FrozCmdlets
{
using System.Management.Automation;
/// <summary>
/// Adds a new froz to the system.
/// </summary>
[Cmdlet( VerbsCommon.Add, "Froz" )]
public class AddFroz : Cmdlet
{
/// <summary>
/// The name of the froz.
/// For more information on the froz, see froz help manual.
/// </summary>
[Parameter]
public string Name { get; set; }
protected override void ProcessRecord()
{
base.ProcessRecord();
// Add the froz here
}
}
/// <summary>
/// Removes a froz from the system.
/// </summary>
[Cmdlet( VerbsCommon.Remove, "Froz" )]
public class RemoveFroz : Cmdlet
{
/// <summary>
/// The name of the froz.
/// For more information on the froz, see froz help manual.
/// </summary>
[Parameter]
public string Name { get; set; }
protected override void ProcessRecord()
{
base.ProcessRecord();
// Remove the froz here
}
}
}
Run Code Online (Sandbox Code Playgroud)
是的,有一种方法可以做到这一点,而无需从参数的公共基类继承。它没有很好的记录,只是在IDynamicParameters.GetDynamicParameters方法的注释中暗示。这是对该主题的更详细处理。
首先,使用 [Parameter] 属性将常用参数声明为属性,创建一个类:
internal class MyCommonParmeters
{
[Parameter]
public string Foo { get; set; }
[Parameter]
public int Bar { get; set; }
...
}
Run Code Online (Sandbox Code Playgroud)
然后每个想要使用这些通用参数的 Cmdlet 都应该实现 IDynamicParameters 接口以返回 MyCommonParameters 类的成员实例:
[Cmdlet(VerbsCommon.Add, "Froz")]
public class AddFroz : PSCmdlet, IDynamicParameters
{
private MyCommonParmeters MyCommonParameters
= new MyCommonParmeters();
object IDynamicParameters.GetDynamicParameters()
{
return this.MyCommonParameters;
}
...
Run Code Online (Sandbox Code Playgroud)
通过这种方法,PowerShell 命令参数绑定器将查找并填充 MyCommonParameters 实例上的参数,就像它们是 Cmdlet 类的成员一样。
| 归档时间: |
|
| 查看次数: |
579 次 |
| 最近记录: |