簡體   English   中英

C# 二進制 PowerShell 模塊中的 ValidateScript ParameterAttribute

[英]ValidateScript ParameterAttribute in C# Binary PowerShell Module

我最近開始在 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 is null 相反,您應該從ValidateArgumentsAttribute派生並覆蓋Validate以執行驗證:

class ValidateCustomAttribute:ValidateArgumentsAttribute {
    protected override void Validate(object arguments,EngineIntrinsics engineIntrinsics) {
        //Custom validation code
    }
}

只是通過一個更完整的示例來擴展上面 user4003407 的答案。

從 ValidateArgumentsAttribute 派生一個新的驗證器並覆蓋 Validate 以執行驗證。 驗證是無效的,所以你真的只能在你選擇的情況下拋出異常。

Kevin Marquette 有一篇很棒的文章,但它是在 powershell 中的。 這是 ac# 示例:

[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();
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM