Jimmy W
Jimmy W

Reputation: 13

Modifying phone number variable from Active Directory in Powershell

We have a Powershell script to automatically create outlook signatures using data pulled from Active Directory.

Currently we're pulling in phone numbers with the following line:

Update-Sig -attribute "TelephoneNumber" -value "$([string]($ADUser.TelephoneNumber))"

This will return a number in the format +61112345678.

What I want to do is change that string so that it's always in the format +61 1 1234 5678 with spaces.

Is this possible? I'm thinking I need to take the string, turn it into a variable and then add a space after a certain amount of characters.. but i'm unsure how to do that.

Thanks

Upvotes: 0

Views: 2512

Answers (2)

Theo
Theo

Reputation: 61158

Credits for this should go to @Lee_Daily because of the string format. You can do something like below to format the expected '+61' numbers and if there is something else in the property it will print it out so you can check.

$phone = '+61112345678'

# test if the string starts with a `+` or at least the digits `61`
if ($phone.Trim() -match '^(\+|61)') {
    $phone = '+{0:## # #### ####}' -f ([int64]($phone -replace '\D',''))
    Write-Host "Formatted TelephoneNumber: '$phone'" -ForegroundColor Green
}
else {
    # not a '+61' number. Write it out so you can check/correct manually
    Write-Host "Unexpected TelephoneNumber: '$phone'" -ForegroundColor Red
}


UPDATE

To answer your latest comment, indeed, the code above does not set the newly formatted telephone number in the ADUser's attribute.
I thought the question was all about the formatting, not the setting.

Although your link is broken, it would be easy enough to set this in the AD.
It seems you already have an object called $ADUser and I imagine this came from an earlier Get-ADUser call you did. Setting the formatted number you obtained using the above code, you can simply update the users number using for instance:

# using piping the user object to Set-ADUser
$ADUser | Set-ADUser -OfficePhone $phone

# using one of the users properties as 'Identity' and update using the LDAP attribute name
# for parameter Identity, the cmdlet accepts either the DistinguishedName, objectGUID, objectSid, or the SamAccountName
Set-ADUser -Identity $ADUser.DistinguishedName -Replace @{telephoneNumber = $phone }

p.s. There is also an attribute called HomePhone (LDAP name homePhone), but that is not the one you use in your code.

Hope that helps

Upvotes: 0

Lee_Dailey
Lee_Dailey

Reputation: 7489

you can use the string format operator to do that. it has a "number placeholder" option. however, that only works on actual numbers and your data is almost certainly a string. so ... i converted the numeric part to an [int64]. [grin]

$SourceValue = '+61112345678'
'+{0:## # #### ####}' -f ([int64]$SourceValue.TrimStart('+'))

output = +61 1 1234 5678

Upvotes: 2

Related Questions