英文:
Use Read-Host to gather a Phone number
问题
我正在编写一个 Powershell 脚本,它会请求多个情报信息,然后使用这些数据创建一个AD用户对象。其中一件我想要添加的是用户的 电话号码。在美国,电话号码通常由 10个数字 组成。我希望代码能确保没有人在区号、交换机等之间添加连字符或句号,因为我只需要 数字。我计划使用 格式运算符 来使其在AD用户对象中看起来好看(规范化它)。我尝试过在变量中添加[int]
,但这只能帮助我到一定程度,因为我似乎无法指定10个数字。
我之前使用过Read-Host
来提示用户选择(A、B、C等),所以我知道这个方法。如果除了这些字母之外的其他内容被用作答案,它会再次询问问题,直到回答正确。如果有更好的方法来请求一个10位数的号码,我会乐意学习一些新知识。
英文:
I'm working on a Powershell script that asks for several pieces of intel and then it creates an AD User Object with the data. One thing I'd like to add is the user's phone number. Here, in the States, phone numbers are generally composed of 10 digits. I'd like the code to make sure nobody is adding hyphens or periods between the area code, exchange, etc. because I just want the digits. I had planned on using the format operator to make it look good (normalize it) in the AD User Object. I tried playing with adding [int]
to my variable but that only gets me so far as I can't seem to specify 10 digits.
I've used Read-Host
before to prompt a user with choices (A, B, C, etc.) so that's what I know. If something other than one of those letters was used as an answer, it would ask the question again - until it was answered correctly. If there's a better way to request a 10-digit number, I'll be all for learning something new.
答案1
得分: 3
我建议允许用户以他们喜欢的任何格式输入电话号码,然后在之后进行清理:
# 读取输入
$phoneNumber = Read-Host "输入10位数字电话号码"
# 删除非数字字符
$cleanNumber = $phoneNumber -replace '[^0-9]'
# 验证
if ($cleanNumber.Length -ne 10){
# 错误处理在这里,
# 也许你想要返回
# 到包含循环的顶部
Write-Error "无效的电话号码!"
}
else {
$formattedNumber = '({0}) {1}-{2}' -f $cleanNumber.Substring(0,3),$cleanNumber.Substring(3,3),$cleanNumber.Substring(6)
Write-Host "您输入的电话号码是:$formattedNumber"
}
现在用户可以在提示中以任何他们喜欢的格式输入电话号码:
输入10位数字电话号码: 1234567890
您输入的电话号码是:(123) 456-7890
或者
输入10位数字电话号码: (123) 4567890
您输入的电话号码是:(123) 456-7890
英文:
I'd suggest allowing the user to input the phone number in whatever format they want, then sanitize it after the fact:
# Read input
$phoneNumber = Read-Host "Input 10 digit phone number"
# Remove anything that isn't a digit
$cleanNumber = $phoneNumber -replace '[^0-9]'
# Validate
if ($cleanNumber.Length -ne 10){
# error handling goes here,
# perhaps you wanna go back
# to the top of a containing loop
Write-Error "Invalid phone number!"
}
else {
$formattedNumber = '({0}) {1}-{2}' -f $cleanNumber.Substring(0,3),$cleanNumber.Substring(3,3),$cleanNumber.Substring(6)
Write-Host "You entered the phone number: $formattedNumber"
}
Now the user can pick whatever formatting they want when writing the password in the prompt:
Input 10 digit phone number: 1234567890
You entered the phone number: (123) 456-7890
or
Input 10 digit phone number: (123) 4567890
You entered the phone number: (123) 456-7890
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论