2013-05-21 35 views
0

我有一个参数如下:PowerShell的 - [AllowEmptyString()不工作

[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] 
[AllowEmptyString()] 
[ValidateSet("1", "2", "3", "4", "5", "6", "Critical", "Important", "High", "Medium", "Low", "Lowest")] 
public string Priority { get; set; } 

当我运行-Priority ""我的命令,这是行不通的

我知道我可以只跳过参数,但对我来说真正的问题是,当我使用import-csv执行我的命令时,Import-Csv将我的参数值更新为空,因此我得到以下错误:import-csv

如果我的csv没有任何值,

Cannot validate argument on parameter 'Priority'. The argument "" does not belong to the set "1,2,3,4,5,6,Critical,Important,High,Med 
ium,Low,Lowest" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again. 

如果我延长我的验证集包括“”,如果单独调用命令运行成功,但它仍然无法正常工作,如果我管它Import-Csv

我也曾尝试AllowNull属性,但还是同样的错误

UPDATE: 与Garath的讨论之后,我似乎是

  1. AllowEmptyString不起作用,而是在ValidateSet中使用“”

    问题仍然没有解答 - 为什么[AllowEmptyString()]没有工作?

  2. CSV文件必须试运行逗号,即使没有值

    这似乎如果尾随逗号是不是有那么Import-Csv传递空的命令和失败时ValidateSet

    给拖影验证似乎空是传递给参数,这是可接受的,因为该集合包括“”

回答

1

我在简单的ps1脚本中模拟你的问题,它是wor王(保存为fun2.ps1):

param(
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)] 
[string] 
[ValidateSet("","1", "2", "3", "4", "5", "6")] 
$a 
) 

Write-Host $a 

的CSV类似于下面(doc.txt):

"ColName" 
"2" 
"" 
"3" 

和PowerShell命令是:

Import-Csv .\doc.txt | %{.\fun2.ps1 $_.ColName} 

的outuput以上命令是:

PS C:\ps> Import-Csv .\doc.txt | %{.\fun2.ps1 $_.ColName} 
2 

3 

所以刚才雷莫已经[AllowEmptyString()]和改变你的验证设置为:

[ValidateSet("", "1", "2", "3", "4", "5", "6", "Critical", "Important", "High", "Medium", "Low", "Lowest")] 
+0

你试过用import-csv吗? –

+0

我更新了我的答案详细信息 –

+0

谢谢,但正如我在我的问题中所说的,扩展验证集以包含“”适用于单个命令,它不适用于import-Csv |命令 –

0

AllowEmptyString工作。如果不是,你会得到一个错误消息像

Cannot bind argument to parameter 'Priority' because it is an empty string.

这是ValidateSet验证,是造成问题,因为你的集不包含空字符串

我不认为你需要两个验证。删除AllowEmptyString()验证并添加""作为您设置的元素。

[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] 
[ValidateSet("", "1", "2", "3", "4", "5", "6", "Critical", "Important", "High", "Medium", "Low", "Lowest")] 
[string] Priority