C# 二进制 PowerShell 模块中的 ValidateScript ParameterAttribute
本文关键字:ValidateScript ParameterAttribute 模块 二进制 PowerShell | 更新日期: 2023-09-27 18:37:11
我最近开始尝试用C#进行二进制PowerShell编程,我在使用ParameterValidationAttributes(主要是ValidateScript属性)时遇到了一些麻烦。 基本上,我想创建一个名为"ComputerName"的参数,并验证当时计算机是否在线。 在PowerShell中很容易:
[Parameter(ValueFromPipeLine = $true)]
[ValidateScript({ if (Test-Connection -ComputerName $_ -Quiet -Count 1) { $true } else { throw "Unable to connect to $_." }})]
[String]
$ComputerName = $env:COMPUTERNAME,
但是我不知道如何在 C# 中复制它。 ValidateScript 属性采用 ScriptBlock 对象 http://msdn.microsoft.com/en-us/library/system.management.automation.scriptblock(v=vs.85).aspx 我只是不确定如何在 C# 中创建它,我真的找不到任何示例。
[Parameter(ValueFromPipeline = true)]
[ValidateScript(//Code Here//)]
public string ComputerName { get; set; }
C#对我来说很新,所以如果这是一个愚蠢的问题,我深表歉意。 这是 ValidateScript 属性类的链接:http://msdn.microsoft.com/en-us/library/system.management.automation.validatescriptattribute(v=vs.85).aspx
C# 中是不可能的,因为 .NET 只允许编译时常量、typeof
表达式和属性参数的数组创建表达式,并且只允许对引用类型string
null
。相反,您应该从ValidateArgumentsAttribute
派生并覆盖Validate
以执行验证:
class ValidateCustomAttribute:ValidateArgumentsAttribute {
protected override void Validate(object arguments,EngineIntrinsics engineIntrinsics) {
//Custom validation code
}
}
只是为了用一个更完整的示例来扩展 user4003407 上面的答案。
从 ValidateArgumentsAttribute 派生一个新的验证程序,并覆盖 Validate 以执行验证。 验证是无效的,所以你真的只能在你选择的情况下抛出异常。
凯文·马凯特(Kevin Marquette)有一篇很棒的文章,但它在Powershell中。下面是一个 c# 示例:
[Cmdlet(VerbsCommon.Get, "ExampleCommand")]
public class GetSolarLunarName : PSCmdlet
{
[Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)]
[ValidateDateTime()]
public DateTime UtcDateTime { get; set; }
protected override void ProcessRecord()
{
var ExampleOutput = //Your code
this.WriteObject(ExampleOutput);
base.EndProcessing();
}
}
class ValidateDateTime:ValidateArgumentsAttribute {
protected override void Validate(object arguments,EngineIntrinsics engineIntrinsics) {
var date = (DateTime)arguments;
if( date.Year < 1700 || date.Year > 2082){
throw new ArgumentOutOfRangeException();
}
}