Home > Enterprise >  powershell how to set a character limit of no more than 15 characters, if more then prompt to re-ent
powershell how to set a character limit of no more than 15 characters, if more then prompt to re-ent

Time:11-17

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

CodePudding user response:

Keep looping until the input string satisfies your constraint:

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

CodePudding user response:

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.

CodePudding user response:

even an if condition will work.

$VM = "qwertyuiop"

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

$VM
  • Related