问题
I need to modify the below code with some International Phone area code formatting from the Active Directory without modifying the actual AD attribute value:
$defaultTelephone = '1800 552 001'
#Get Active Directory information for the currently logged on user
$sysInfo = New-Object -ComObject 'ADSystemInfo'
$userDN = $sysInfo.GetType().InvokeMember('UserName', 'GetProperty', $null, $sysInfo, $null)
$adUser = [ADSI]"LDAP://$($userDN)"
[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($sysInfo)
#Get the phone number from the Active Directory and assign it into the International phone country code format
$IntlPhoneNumber = $(If ($ADUser.telephoneNumber) { $ADUser.telephoneNumber.ToString() }
Else { $defaultTelephone })
$IntlPhoneNumber
in the above script, it pulls the Information As is from the AD Attributes which is now set 08 8211 8911
What I wanted to display as the value of $IntlPhoneNumber is + 1 8 8211 8911
So I need to:
- Add +1 as Country code
- Remove 0 from the variable but not removing or modifying the Active Directory value.
- If the phone number is NOT in the form of 2digits 4digits 4digits, then display it as is no need to change into +1 Country Code and removing the zero.
回答1:
After reading the number from Active Directory, check if it should be changed and do it if necessary. Like this, the number won't be changed in Active Directory (there is no write operation anyway):
$IntlPhoneNumber = "08 8211 8911"
if($IntlPhoneNumber -match '^\d{2}(\s\d{4}){2}$'){
$IntlPhoneNumber = $IntlPhoneNumber -replace '^0', '+1 '
}
$IntlPhoneNumber # +1 8 8211 8911
The RegEx
^\d{2}(\s\d{4}){2}$
matches only with telephone numbers with the format 2digits 4digits 4digits.
来源:https://stackoverflow.com/questions/53514044/modifying-powershell-to-display-phone-number-in-international-format-without-cha