Hi All
I'm putting together a script and I would like it to perform some input validation. It basically needs to compare the name of the clusters in a vcenter and compare it to what the user enters, if the cluster exists it should continue with the name if it doesn't it should print "Invalid cluster name" and ask for input again.
The full script allows the user to connect to one of multiple vcenters and it already works vCenters with only one cluster. However as soon as there is more than one cluster it does not validate any of the names correctly. So basically doesn't deal with the multiple variables in the array correctly.
Below are the snippets from this part of the script. Some help would be greatly appreciated.
[CmdletBinding()]
param (
[ValidateScript({
if ($_ -eq $clusters) {
$true
} else {
throw "$_ is an invalid cluster name "
}
})]
$clustername
)
}
Connect-VIServer -Server $vcentername -Credential $vcenterpw | Out-Null
# Choose a cluster
Write-Output " "
Write-Host "The following clusters are available in the vCenter" -ForegroundColor Green
Write-Output " "
$cluster = Get-Cluster
$clusters = $cluster.Name
$clusters
Write-Output " "
$clustername = Read-Host -Prompt 'Which cluster contains the resource pool you would like to upgrade?'
Try {
$a = 'no error'
$Error.clear()
$null = Test-Cluster -clustername $clustername
}
Catch {
Write-Host $Error -ForegroundColor Red
$a = 'error'
}
}
While ($a -eq 'error')
Seems to work for me though.
Did you change the order of the operands on the line?
if ($clusters -contains $_) {
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Use the -contains operator instead of -eq
if ($clusters -contains $_) {
$true
} else {
throw "$_ is an invalid cluster name "
}
})]
$clustername
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Hi LucD
Thanks for the quick reply :-).
I changed it to -contains but it unfortunately didn't make a difference.
Seems to work for me though.
Did you change the order of the operands on the line?
if ($clusters -contains $_) {
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Else, show the run of the code (output)
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Ah ha, -in works like a charm.
Thanks!
Which is the same as -contains, but with the operands in the reverse order.
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference