powershellpowershell-4.0

Use Read-Host to gather a Phone number


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.


Solution

  • 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