I would like to use an “If” statement within a ValidateScript parameter validation attribute for an advanced function I am writing instead of having to use the $PSBoundParameters variable to check if more than one parameter is being used.
I would like to be able to use Method 1 rather than Method 2 if possible, but not sure if there is a way of doing this, because I keep getting the following error when using Method 1 below:
[blockquote]Check-Parameters : Cannot validate argument on parameter
‘Param2’. The “If ($Param1){ Write-Warning -Message “The Param1
parameter and the Param2 parameter cannot be used together!” }”
validation script for the argument with value “10” did not return a result of
True. Determine why the validation script failed, and then try the command
again.[/blockquote]
Method 1
Function Check-Parameters
{
[cmdletbinding[]]
Param
(
$ComputerName = $env:COMPUTERNAME,
[Switch]$Param1,
[ValidateScript[({If ($Param1){Write-Warning -Message "The Param1 parameter and the Param2 parameter cannot be used together!" }}]]
[Int]$Param2
)
Check-Parameters -Param1 -Param2 "10"
}
Method 2
Function Check-Parameters
{
[cmdletbinding[]]
Param
(
$ComputerName = $env:COMPUTERNAME,
[Switch]$Param1,
[Int]$Param2
)
$ParamString = @(
$Params = @(
Foreach ($Param in 'Param1', 'Param2')
{
If ($PSBoundParameters[$Param])
{
$Param
}
}
)
Write-Output $Params)
If (($ParamString -eq "Param1") -and ($ParamString -eq "Param2"))
{
Write-Warning -Message "The Param1 parameter and the Param2 parameter cannot be used
together!"
}
ElseIf (($ParamString -eq "Param1") -and ($ParamString -ne "Param2"))
{
"Param1 is being used!"
}
ElseIf (($ParamString -ne "Param1") -and ($ParamString -eq "Param2"))
{
"Param2 is being used!"
}
ElseIf (!($ParamString))
{
"No parameter is being used!"
}
}
OR
Should I use Parameter Sets?
Thanks