In my script i have a date parameter that need to be in a certain format, that I've solved with validatescript and regex. This works nicely but I want a custom error if a. your date don't validate as DateTime b. your date doesn't validate the regex
Param (
[parameter(mandatory=$false)]
[ValidateScript({
If ($_ -match "^([0-9]{4}[-]?((0[13-9]|1[012])[-]?(0[1-9]|[12][0-9]|30)|(0[13578]|1[02])[-]?31|02[-]?(0[1-9]|1[0-9]|2[0-8]))|([0-9]{2}(([2468][048]|[02468][48])|[13579][26])|([13579][26]|[02468][048]|0[0-9]|1[0-6])00)[-]?02[-]?29)") {
$True
}
else {
Write-host "The Date is invalid and need to be in this format, 2017-07-25" -ForeGroundColor Yellow
}
})]
[datetime]$date
)
was thinking using try and catch like
[ValidateScript({
try {
$_ -notmatch "^([0-9]{4}[-]?((0[13-9]|1[012])[-]?(0[1-9]|[12][0-9]|30)|(0[13578]|1[02])[-]?31|02[-]?(0[1-9]|1[0-9]|2[0-8]))|([0-9]{2}(([2468][048]|[02468][48])|[13579][26])|([13579][26]|[02468][048]|0[0-9]|1[0-6])00)[-]?02[-]?29)"
} catch [System.Management.Automation.ParameterBindingValidationException] {
Write-host "The Date is invalid and need to be in this format, 2017-07-25" -ForeGroundColor Yellow
}
)]
any suggestions?
Edit:
Changed it to:
Param (
[parameter(mandatory=$false)][alias('d')][string]$date #date in format yyyy-mm-dd
)
if ($date){
try {get-date($date)}
catch{
Write-host "The Date is invalid and need to be in this format, yyyy-mm-dd" -ForeGroundColor Yellow
$date = getdate(read-host)
}
}
works, though if don't obey the format that is requested and go ahead and type for example 070725 again you will get an error. Is there some way to loop it until you get a correct format? maybe a Do Until loop?
catch{ Write-output $_.Exception.Message }It will capture the exception message. That would be enough in your case i believe.ValidateScript{ try{...}catch{...}}- check out dup flagged answer.