if / else语句坏了

时间:2015-12-30 21:00:58

标签: powershell

此脚本当前使用if...else来确保用户输入正确的命名约定。如果脚本输入正确的约定,脚本就会执行得很好。如果他们不这样做,它会提示他们使用命名约定,但一旦输入,程序就会关闭而不会继续。

我想更改它,以便在正确输入之前提示他们正确的命名约定,然后继续向他们询问别名(别名不需要约定)。

我已经尝试了do...while/until,但不管输入的是什么,都会以连续循环结束。谁能告诉我如何解决这个问题?

$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)
}

1 个答案:

答案 0 :(得分:3)

你在滥用if/else Else 表示,如果不是。因此,如果使用按照命名约定输入 not 的名称,则永远不会执行else块。

无论发生什么情况,您都希望执行该部分:

$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)

使用do{}until()循环,您可以继续询问$name值,直到它们正确为止:

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