So, I recently encountered a somewhat confusing PowerShell error with an error message similar to this one:
The variable cannot be validated because the value 4 is not a valid value for the Number variable.
This is, unfortunately, not only a non sensical but also pretty unhelpful error message. For one thing it’s not logical to say that a variable “cannot not be validated” and then declare that it is not valid. (Obviously, if you find a variable to be invalid you were able to validate it. So it should have been “did not pass validation” or something similar.) More importantly, however, 4
is a valid Number
value. So, what gives?
Thankfully, things, become a bit clearer, if we trace the error back to it’s root cause. Apparently errors of this kind are raised when variables are attributed with the [ValidateSet(<the-value-set>)]
attribute and then assigned a value that is not contained in the-value-set
. This may happen for example, when a cmdlet parameter has a ValidateSet
annotation and you invoke the cmdlet passing an invalid parameter value. The funny part, however, is that the parameter is not only validated when you pass it to the cmdlet, but even if you reassign the associated variable later on in your cmdlet.
Take a look at this reproducer.
host> docker run --rm -it ubuntu:24.04
ubuntu> apt-get update && apt-get upgrade --yes && apt-get install --yes curl
ubuntu> curl -LsS --fail -o "/tmp/packages-microsoft-prod.deb" \
"https://packages.microsoft.com/config/ubuntu/24.04/packages-microsoft-prod.deb"
ubuntu> dpkg --install "/tmp/packages-microsoft-prod.deb"
ubuntu> apt-get update && apt-get install --yes powershell=7.5.0-1.deb
ubuntu> pwsh
PS> Function Test {
[cmdletbinding()]
Param(
[ValidateSet(1,2,3)]
[int]$Number
)
$Number = 4
}
PS> Test 3
The variable cannot be validated because the value 4 is not a valid value for the Number variable.
Judging from the StackOverflow post below, this behavior has been there since at least 2017. It still occurs in the latest version of PowerShell (7.5.0) as you can see from the code above.
To not run into this problem, consider parameters attributed with ValidateSet
immutable and don’t reassign them.