Link to home
Start Free TrialLog in
Avatar of chris_miller
chris_miller

asked on

Help formatting phone numbers using powershell

Hello,  I am trying to create a powershell to take all my users in active directory and format all of their phone numbers the same  (XXX)XXX-XXXX

I have the script getting the users and stripping all no numeric characters and writing the stripped number to the office phone field in AD.  however the formatting is not applying.  It does not error.  It just ignores it and writes the 10 digit number.

Here is the Powershell I am running. (this one has been modified to a single user for testing)

# Retrieve Single User
$Users =  Get-ADUser -LDAPFilter "(sAMAccountName=testuser)" -Properties sAMAccountName, telephoneNumber
ForEach ($User In $Users)
 {
     $Name  = $User.sAMAccountName
     # Replace non-digits with blank.
     $Phone = $User.telephoneNumber -Replace "[^0-9]", ""
     # Check length.
     If ($Phone.Length -eq 10)
     {
         # Format number as (xxx)xxx-xxxx
         $Phone= "{0:(###)###-####}" -f $Phone
         # Save corrected value for telephoneNumber.
         Set-ADUser -Identity $Name -OfficePhone $Phone
     }
     Else {"$Name invalid value: $Phone"}
 }
ASKER CERTIFIED SOLUTION
Avatar of SubSun
SubSun
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of chris_miller
chris_miller

ASKER

yes that worked :)  thanks so much.  

I was trying -as [long] but I had it on the wrong line.