我正在编写一个脚本,该脚本将通过Read-Host
(设置为$String
)接受用户输入,并且我想避免任何可能由变量的空白值引起的问题。因为我会经常使用它,所以我想将它实现为一个验证没有使用无效字符的函数。
我想我可以使用 if 语句![string]::IsNullOrEmpty($String)
作为条件之一:
Function Test-ValidCharacters ($String, $ValidCharacters) {
if (($String -match $ValidCharacters) -and (!([string]::IsNullOrEmpty($String)))) {
return $true
}
else {return $false}
}
我也试过这个:
Function Test-ValidCharacters ($String, $ValidCharacters) {
if (($String -match $ValidCharacters) -and ($String -ceq "")) {
return $true
}
else {return $false}
}
在这两种情况下,当出现 $String 的 Read-Host 提示时,我只需按 Enter 键,脚本的行为就好像函数返回$True
(然后遇到致命错误)。$ValidCharacters
另一半有效 - 如果我包含函数未指定的字符,则按$False
预期返回。
我确定我在这里遗漏了一些东西。我什至尝试做第二个嵌套 if 语句并得到相同的结果。
编辑:这是我调用函数并注意到问题的代码片段。
$ValidCharacters = '[^a-zA-Z0-9]'
$FirstN = Read-Host -Prompt "New user's first name"
While (Test-ValidCharacters $FirstN $ValidCharacters -eq $false) {
Write-Output "$FirstN contains illegal characters. A-Z, a-z, and 0-9 are accepted."
$FirstN = Read-Host -Prompt "New user's first name"
}