Can’t figure out how to return to reloop through the try catch throw when a incorrect value is entered. Currently upon entering an incorrect value the validation test displays an error message. A correct works with no issues.
function FOO
{
[CmdletBinding()]
param(
[Parameter(Mandatory,HelpMessage="Enter a Datacenter Name")]
[ValidateScript({
try{
Get-DataCenter -Name $_ -ErrorAction Stop
}
catch{
throw "Datacenter $_ not found. Please enter a valid Datacenter Name."
}
})]
[String[]]
$DCChoice
)
$DCChoice
}
Hello Kiran,
Thank you for your reply. As usual not making myself clear if I enter the following:
10:31AM D:\PowerShell_Test\powercli> FOO -DCChoice xxxx wvhq
FOO : Cannot validate argument on parameter ‘DCChoice’. Datacenter 12/23/2019 10:32:04 AM Get-Datacenter Datacenter with name ‘xxxx’ was not found using the specified
filter(s). not found. Please enter a valid Datacenter Name.
At line:1 char:16
Would like to have the validation test restart giving the user another opportunity to enter a correct value without having to restart the function. Hope this makes some sense. Maybe what I’m asking for is not possible
If you want a re-prompt, that is normally done outside the function like so:
$svcs = Get-Service | Select-Object -ExpandProperty Name
do {
$prompt = (Read-Host -Prompt 'Enter the name of the service').Trim()
if (-not ($svcs -contains $prompt)) {
'{0} is not a valid service' -f $prompt
}
}
while (-not ($svcs -contains $prompt))
Get-Service -Name $prompt
Normally I don’t do the retry within the function, I ask the function to return a status message as a hashtable and performs the retry in the script.
Based on your scenario, probably I would try something like this.
[PRE]
function FOO
{
[CmdletBinding()]
param(
[Parameter(Mandatory,HelpMessage="Enter a Datacenter Name")]
[String]$DCChoice
)
$exitFlag = $False
Do
{
Try
{
$DC = Get-DataCenter -Name $DCChoice -ErrorAction Stop
$exitFlag = $true
}
Catch
{
$DC = $null
$title = "wrong DC Name"
$prompt = "$DCChoice was wrong, Would you like to [A]bort or [R]etry?"
$choices = @('&Abort','&Retry')
$choice = $host.ui.PromptForChoice($title,$prompt,$choices,0)
If($choice -eq 0){$exitFlag = $true}
}
}Until($exitFlag)
If([String]::IsNullOrEmpty($DC))
{
Return 'NotProcessed'
}
Instead of using the validate script you can use dynamic validate set, get all the valid values and use them in the validate set, please refer to the link below…
What you have is what I’m except the RETRY doesn’t work when I press retry nothing happens the abort option works perfectly. DO you have sometime to help me with the retry option,is there a way to return to start over again allowing the user to retry entering the correct datacenter?