2

我正在编写一个脚本,该脚本将通过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"
}
4

1 回答 1

2

假设$ValidCharacters它本身不是一个空字符串,并且包含一个覆盖整个输入字符串的锚定字符范围正则表达式(正则表达式) ,例如,假设运算符默认匹配任何子字符串(请注意,因此参数的更好名称是类似):[1]^[a-z0-9./:]+$-match$ValidationRegex

  • 在第一个函数定义中,您的-and操作的 RHS 是多余的 - 它不会向条件添加任何内容,因为根据定义, if $String -match $ValidCharactersis $true, then so is ! [string]::IsNullOrEmpty($String)

  • 相反,在第二个函数定义中,您的-and操作总是返回$false,因为$String -ceq ""根据定义$false,如果 LHS 返回$true

假设您的意图是防止空输入或全空格输入,并确保任何字符串(修剪掉附带的前导和/或尾随空格)仅由预期字符组成,请使用以下命令:

Function Test-ValidCharacters ($String, $ValidCharacters) {
  # Note: no strict need for `return`.
  $String.Trim() -match $ValidCharacters
}

[1] 或者,坚持$ValidCharacters并传递一个仅描述单个有效字符的正则表达式,例如'[a-z0-9./:]',并在函数内部构造整个字符串匹配的正则表达式'^' + $ValidCharacters + '+$'

于 2021-06-15T23:51:30.807 回答