如何实现PowerShell仅接受Int类型输入以完成AD用户选择验证
PowerShell脚本实现仅接受整数输入的解决方案
原脚本中直接用[int]$selection = Read-Host强制转换输入,遇到非数字内容会报错。要实现仅接受有效整数且在索引范围内的输入,可通过[int]::TryParse()方法结合循环验证来解决。
核心修改部分
替换原脚本中从#Prompt开始的代码段:
# 循环获取有效输入 do { $inputValue = Read-Host "`nEnter number for user you want to modify" # 验证输入是否为整数 if ([int]::TryParse($inputValue, [ref]$selection)) { # 验证整数是否在有效索引范围内 $maxIndex = $ResultsArray[0].length - 1 if ($selection -ge 0 -and $selection -le $maxIndex) { break # 输入有效,退出循环 } else { Write-Host "INVALID SELECTION!!! 请输入0到$maxIndex之间的数字" -ForegroundColor Red } } else { Write-Host "请输入有效的整数!" -ForegroundColor Red } } while ($true) # 输出选中的用户信息 Write-Host "`nYou selected user " -nonewline Write-Host $ResultsArray[0][$selection] -nonewline -ForegroundColor Green Write-Host " with user ID a of " -nonewline Write-Host $ResultsArray[1][$selection] -nonewline -ForegroundColor Green
关键说明
[int]::TryParse():这是PowerShell中安全转换字符串到整数的方法,转换成功时返回$true,并将结果存入$selection;失败时返回$false,不会抛出错误。- 循环验证:使用
do-while循环持续提示用户输入,直到输入符合“有效整数+索引范围内”的要求。 - 动态范围检查:根据实际查询到的用户数量计算最大索引(
$ResultsArray[0].length - 1),替代原脚本中固定的范围限制,适配不同数量的查询结果。
完整修改后的脚本
#prompt for last name (or at least portion of last name, then conver to a string with wild card for use in filter $lname = Read-Host "`nEnter at least the first three chars of users last name (you may enter full last name)" $search = $lname + "*" #Empty arrays $ResultsArray=@("") $ADUsersList=@("") #add aduser properties to array, return error and exit if no user found $ADUsersList += Get-ADUser -filter "surname -like `$search" -Properties * | select name,samaccountname,DistinguishedName if ($ADUsersList.count -le 1){ Write-host "USER NOT FOUND" return } #populate a 2D array with NAM and with UserID $ResultsArray = @(($ADUsersList.name),($ADUsersList.samaccountname)) #return list of found users and user ids. Preface with index number to use for selection menu for($i=0;$i-le $ResultsArray[0].length-1;$i++){ "[{0}] = {1} `t {2}" -f $i,$ResultsArray[0][$i],$ResultsArray[1][$i] } # 循环获取有效输入 do { $inputValue = Read-Host "`nEnter number for user you want to modify" # 验证输入是否为整数 if ([int]::TryParse($inputValue, [ref]$selection)) { # 验证整数是否在有效索引范围内 $maxIndex = $ResultsArray[0].length - 1 if ($selection -ge 0 -and $selection -le $maxIndex) { break # 输入有效,退出循环 } else { Write-Host "INVALID SELECTION!!! 请输入0到$maxIndex之间的数字" -ForegroundColor Red } } else { Write-Host "请输入有效的整数!" -ForegroundColor Red } } while ($true) # 输出选中的用户信息 Write-Host "`nYou selected user " -nonewline Write-Host $ResultsArray[0][$selection] -nonewline -ForegroundColor Green Write-Host " with user ID a of " -nonewline Write-Host $ResultsArray[1][$selection] -nonewline -ForegroundColor Green
内容的提问来源于stack exchange,提问作者RookieMistake
相关产品推荐
相关产品推荐

