2015-01-12 22 views
1

我最近開始嘗試在C#中使用Binary PowerShell編程,而且我主要在使用ParameterValidationAttributes和ValidateScript Attribute時遇到了一些麻煩。基本上,我想創建一個名爲「ComputerName」的Param,並驗證當時的計算機處於在線狀態。在PowerShell中很容易:C#中的ValidateScript ParameterAttribute Binary 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

回答

3

它不是在C#可能的,因爲.NET只允許編譯時間常數,typeof表達式和數組創建表達式屬性參數和僅常數可用於其他然後string是引用類型null。相反,你應該從ValidateArgumentsAttribute派生並重寫Validate進行驗證:

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

感謝您的信息,這也許有點出我的C#概念。所以,我創建該類後,我可以在ValidateScript()中調用它? [ValidateScript({ValidateCustomAttribute.Validate(arg0,arg1)})] – dotps1

+0

@ dotps1您應用自定義屬性而不是'ValidateScriptAttribute'。 – PetSerAl

+0

謝謝,我想我明白了,所以我可以拋出一個異常,如果電腦無法聯繫? – dotps1