I have a parameter as follows:
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)]
[AllowEmptyString()]
[ValidateSet("1", "2", "3", "4", "5", "6", "Critical", "Important", "High", "Medium", "Low", "Lowest")]
public string Priority { get; set; }
When I run my command with -Priority "", it does not work
I know I can just skip the argument, but the real problem for me is when I execute my command using a pipe from import-csv
If my csv does not have any value, Import-Csv updates my parameter value to empty and so I get the following error:
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.
If I extend my validation set to include "", the the command if invoked individually runs successfully, however it still does not work if I pipe it to Import-Csv
I have also tried AllowNull attribute, but still the same error
UPDATE: After discussing with Garath, I appears that
AllowEmptyString does not work, instead use "" in ValidateSet
The question still remains unanswered - why doesnt [AllowEmptyString()] work?
CSV files must have trialing commas even if there are no values
Here it seems if trailing commas are not there then Import-Csv passes null to the command and that fails validation given by ValidateSet
When trailing commas are present, it seems empty is passed to the parameter which is acceptable as the set includes ""
I simulate your problem in simple ps1 script, and it is working (saved as fun2.ps1):
param(
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[string]
[ValidateSet("","1", "2", "3", "4", "5", "6")]
$a
)
Write-Host $a
The CSV look like below (doc.txt):
"ColName"
"2"
""
"3"
And Powershell command is:
Import-Csv .\doc.txt | %{.\fun2.ps1 $_.ColName}
The outuput for above commmand is:
PS C:\ps> Import-Csv .\doc.txt | %{.\fun2.ps1 $_.ColName}
2
3
So just remove [AllowEmptyString()] and change your validate set to:
[ValidateSet("", "1", "2", "3", "4", "5", "6", "Critical", "Important", "High", "Medium", "Low", "Lowest")]
AllowEmptyString is working. If it wasn't, you'd be getting an error message like
Cannot bind argument to parameter 'Priority' because it is an empty string.
It is the ValidateSet validation that is causing the problem because your set doesn't contain the empty string.
I don't think you need both validations. Remove the AllowEmptyString() validation and add "" as an element in you set.
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)]
[ValidateSet("", "1", "2", "3", "4", "5", "6", "Critical", "Important", "High", "Medium", "Low", "Lowest")]
[string] Priority
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With