Blake
Blake

Reputation: 29

Broken if/else statement

This script currently uses an if...else to ensure users enter a proper naming convention. The script executes just fine if they enter the proper convention. If they don't, it will prompt them to use the naming convention, but once entered, the program closes without continuing.

I want to change it so that it prompts them for the proper naming convention until it's entered correctly, then proceed to ask them for the alias (the alias requires no convention).

I've tried do...while/until but end up in a continuous loop, regardless of what gets entered. Can anyone tell me how to fix this?

$name = Read-Host 'What is the SX20 name?'
if ($name -notlike "SX20VTC-[a-z , 0-9]*") {
    Read-Host 'Please begin naming conventions with "SX20VTC-".'
} else {
    $description = Read-Host 'What is the SX20 alias?'
    $content = (Get-Content C:\Users\SX20_Backup.txt) -replace 'NGMNVC-[a-z , 0-9]*', $name -replace 'SetDescriptionX', $description
    $filename = "$env:USERPROFILE\Desktop\$name.txt"
    [IO.File]::WriteAllLines($filename, $content)
}

Upvotes: 0

Views: 107

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

You're misusing if/else. Else means if not. So if the use enters a name that is not following the naming convention, the else block never gets executed.

You want that part executed no matter what happens:

$name = Read-Host 'What is the SX20 name?'
if ($name -notlike "SX20VTC-[a-z , 0-9]*") {
    $name = Read-Host 'Please begin naming conventions with "SX20VTC-".'
}
$description = Read-Host 'What is the SX20 alias?'
$content = (Get-Content C:\Users\SX20_Backup.txt) -replace 'NGMNVC-[a-z , 0-9]*', $name -replace 'SetDescriptionX', $description
$filename = "$env:USERPROFILE\Desktop\$name.txt"
[IO.File]::WriteAllLines($filename, $content)

With a do{}until() loop, you could keep asking for the $name value until they get it right:

do  {
    $name = Read-Host 'Please enter SX20 name, must start with "SX20VTC-".'
} until ($name -like "SX20VTC-[a-z , 0-9]*")

Upvotes: 3

Related Questions