powershell how to set a character limit of no more than 15 characters, if more then prompt to re-enter the name

Viewed 490

how do i go about setting a character limit for the following code? would i need a IF statement here checking the length?

do { $VM = Read-Host "Enter Server Name" } 
until ($VM)

i have tried

do { [string][validatelength(0,15)] $VM = Read-Host "Enter Server Name" } 
until ($VM)

this is great if the input text is no more than 15... if its over it errors out i need it to loop back so it asks for the correct name

how do i go about tweaking this?

thanks

3 Answers

Keep looping until the input string satisfies your constraint:

do {
  $VM = Read-Host "Enter Server Name"
} while($VM.Length -gt 15)

You can do the following :

$VM = "anything over 15"

while ($VM -match ".{15}" ){
$VM = Read-Host "Enter Server Name"
}

I found info about checking length in this post post

And here's microsoft's documentation about while loops.

even an if condition will work.

$VM = "qwertyuiop"

if ($VM.length -gt 15) {
    Write-Output "Please enter more than 15 characters."
    $VM = Read-Host "Re-enter VM Name"
}

$VM
Related