我最近开始在 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