2017-02-19 36 views
-1
function foo 
{ 
    param(
     [parameter(Mandatory=$true)] 
     [ValidateSet('Test1','Test2','Test3')] 
     [String]$ChooseOne= 'Test1', 
    ) 

do xxxxxxxxxxxxxxxx 
{ 

foo -ChooseOne Test9 

我正在使用一組必需參數的powershell函數。該驗證組的偉大工程,然而由於驗證是集..如果輸入的選項不是列出的選項之一。我會得到一個錯誤象下面這樣:失敗的PowerShell ValidateSet - 錯誤操作將變量設置爲默認值?

foo: Cannot validate argument on parameter 'ChooseOne'. The argument "Test9" does not belong to the set "Test1,Test2,Test3" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the 
command again. 
At line:1 char:1 
+ foo 
+ ~~~~~~~~~~~~~ 
    + CategoryInfo   : InvalidData: (:) [foo], ParameterBindingValidationException 
    + FullyQualifiedErrorId : ParameterArgumentValidationError,foo 

有沒有一種辦法有一個錯誤的行動來設置委託變量爲它以前定義的默認值?因此,在這種情況下

它會默認$ChooseOne爲「Test1

+1

有大量的高級函數示例使用參數及其各種選項。示例:http://stackoverflow.com/questions/39154887/set-a-default-value-for-variable-in-powershell和[引用TechNet](https://social.technet.microsoft.com/wiki/內容/文章/ 15994.powershell-advanced-function-parameter-attributes.aspx) – user4317867

回答

-2

如果我做的值不是強制性的,它會如想設置爲默認。

[parameter(Mandatory=$false)] 
+0

那麼這個問題又有什麼意義呢? – 4c74356b41

0

在你問題你明確地傳遞一個無效參數的驗證集受限-ChooseOne參數,然後問:

有沒有辦法有一個錯誤動作將受控變量設置爲之前定義的默認值?

答案是:沒有,和一個很好的理由:如果您定義的參數爲只接受來自定義的一組可接受值的參數,您明確要防止傳遞一個不可接受值,所以你想要 PowerShell報告錯誤。

如果你想接受無效值,只是靜靜地忽略他們 - 這似乎是一個壞主意 - 不使用驗證屬性的參數,而是處理驗證 - 和安靜回覆到默認值 - 在您的功能機身

作爲題外話:在這裏,定義爲被標記爲強制性的參數的默認值沒有意義的。


在自己answer改變你的問題的前提不經過任何價值-ChooseOne參數。

製作參數強制性的,即可選 - 這是默認,順便說一下,不需要明確的[parameter(Mandatory=$false)] - 實際上使得申報,如果沒有參數傳遞其生效的任何默認值 - 這是默認值的一點。