ValidateScript ParameterAttribute in C# Binary Pow

2019-08-08 12:06发布

I have recently begun experimenting with Binary PowerShell Programming in C#, and I am having some trouble with ParameterValidationAttributes, the ValidateScript Attribute mostly. Basically, i want to create a Param named "ComputerName" and validate the computer is online at that time. It was easy in PowerShell:

    [Parameter(ValueFromPipeLine = $true)]
    [ValidateScript({ if (Test-Connection -ComputerName $_ -Quiet -Count 1) { $true } else { throw "Unable to connect to $_." }})]
    [String]
    $ComputerName = $env:COMPUTERNAME,

But i cannot figure out how to replicate that in C#. the ValidateScript attribute takes a ScriptBlock object http://msdn.microsoft.com/en-us/library/system.management.automation.scriptblock(v=vs.85).aspx im just not sure how to create that in C#, and i cannot really find any examples.

[Parameter(ValueFromPipeline = true)]
[ValidateScript(//Code Here//)]
public string ComputerName { get; set; }

C# is very new to me, so i appologize if this is a dumb question. here is a link the ValidateScript Attribute Class: http://msdn.microsoft.com/en-us/library/system.management.automation.validatescriptattribute(v=vs.85).aspx

1条回答
放荡不羁爱自由
2楼-- · 2019-08-08 12:36

It is not possible in C#, since .NET only allow compile time constants, typeof expressions and array creation expressions for attribute parameters and only constant available for reference types other then string is null. Instead you should derive from ValidateArgumentsAttribute and override Validate to perform validation:

class ValidateCustomAttribute:ValidateArgumentsAttribute {
    protected override void Validate(object arguments,EngineIntrinsics engineIntrinsics) {
        //Custom validation code
    }
}
查看更多
登录 后发表回答