RogerDingo
RogerDingo

Reputation: 13

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

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

Upvotes: 1

Views: 2231

Answers (3)

Dilly B
Dilly B

Reputation: 1472

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

Upvotes: 0

Tim
Tim

Reputation: 28

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.

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174555

Keep looping until the input string satisfies your constraint:

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

Upvotes: 1

Related Questions