Use already defined parameter inside the [vaildatescript] for another parameter

Hi Power Users,

Guide me through this

I have a function that will take 2 parameters as argument $computername and $action.
Now inside the validate script for $action parameter…Can I access the $computername argument passed to the function somehow ?

Can this be done?

Regards and Thanks

Nope. Each ValidatdeScript is basically its own scope, and the parameters themselves haven’t been “created” at that stage, so you can’t refer to them so far as I know. You really don’t want the ValidateScript doing anything “active,” like pinging a computer. It’s intended to do basic validation; if you need to do anything active, it goes inside the function.

It seems the argument can be used in validation, though.

Function TestMe {
Param (
[Parameter(Position=0)] $ComputerName,
[Parameter(Position=1)]
[ValidateScript({$_ -like "$($ComputerName)*"})] $Action
)
"ComputerName = $($ComputerName)"
"Action = $($Action)"
}

Above function uses the $ComputerName variable to validate the input for the $Action variable.

(0046) § {~} testme foo bar
TestMe : Cannot validate argument on parameter 'Action'. The "$_ -like "$($ComputerName)*"" validation script for the argument with value "bar" did n
ot return true. Determine why the validation script failed and then try the command again.
At line:1 char:12
+ testme foo bar
+Â Â Â Â Â Â Â Â Â Â Â  ~~~
+ CategoryInfo          : InvalidData: (:) [TestMe], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,TestMe

(0047) § {~} testme foo foobar
ComputerName = foo
Action = foobar

Thanks Gilbert,

I will try this, looks promising :slight_smile:

Regards,

Dex

I would warn against this, because I don’t believe you can guarantee the order in which the parameters will be assigned. Depending on the way you invoke the function, and the order in which you pass in parameters, you may get different results.

If you need to do validation involving multiple parameters, push the validation inside the body of the function. I like the idea of having all validation in the parameter block too, but it’s just not something that you can do reliably and since it wasn’t explicitly added as a design feature, you’ll likely end up with scenarios that generate unexpected results, causing you more grief in the long run.

Ohh Thanks Kirk and Don Sir,

So it’s not reliable…thanks for clearing this up for me.

Regards