Search code examples
powershellpowershell-4.0

Combining Powershell script to call function and get the AD attributes value


I need to use a PowerShell function to format the phone number like below:

Function Format-TelephoneNumber
{
    Param (
        [Parameter(ValueFromPipeline = $true, Position = 0)]
        [Alias('Number')]
        [string]$TelephoneNumber,
        [Parameter(Position = 1)]
        [string]$DefaultCountryCode = '+44'
    )
    Process
    {
        $formattedNumber = $TelephoneNumber -replace '[\x09 ]'
        If ($formattedNumber -match '\A(?<CountryCode>\+[1-9]\d|0)(?<Number>\d*)\Z')
        {
            If ($Matches['CountryCode'] -eq '0')
            {
                $countryCode = $defaultCountryCode
            }
            Else
            {
                $countryCode = $Matches['CountryCode']
            }
            $formattedNumber = $countryCode + ' '
            $formattedNumber += -join $Matches['Number'][0 .. 2] + ' '
            $formattedNumber += -join $Matches['Number'][3 .. 5] + ' '
            $formattedNumber += -join $Matches['Number'][6 .. 8]
            $formattedNumber
        }
        Else
        {
            Write-Error "Unable to parse the string '$($number)' as telephone number!"
        }
    }
}

The below script is for retrieving the value of Phone Number from AD Attribute:

$sysInfo = New-Object -ComObject 'ADSystemInfo'
$userDN = $sysInfo.GetType().InvokeMember('UserName', 'GetProperty', $null, $sysInfo, $null)
$adUser = [ADSI]"LDAP://$($userDN)"
[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($sysInfo)

Write-Host $adUser.mobile.ToString() -ForegroundColor Green

How can I call the script?

I have tried below but failed:

Write-Host "This is raw from AD: $($adUser.mobile.ToString())" -ForegroundColor Yellow

$Formatted = Format-TelephoneNumber -TelephoneNumber $adUser.mobile.ToString()
Write-Host "This is processed using Function: " "$($Formatted)" -ForegroundColor Green

Solution

  • Personally, I'd use a different Format-TelephoneNumber function because as James C commented, your function may truncate last digit(s) from the number. Below is my attempt:

    function Format-TelephoneNumber {
        Param(
            [Parameter(ValueFromPipeline = $true, Position = 0)]
            [Alias('Number')]
            [string]$TelephoneNumber,
    
            [Parameter(Position = 1)]
            [string]$DefaultCountryCode = '+44'
        )
        Process {
            # replace all hyphens and other possible joining characters with space and trim the result
            $number = ($TelephoneNumber -replace '[._~-]', ' ').Trim()
            # test if the number starts with a country code
            if ($number -match '^(\+\d+)\s') {
                $countryCode = $Matches[1]
                $number = $number.Substring($countryCode.Length).Trim()
            }
            else {
                $countryCode = $DefaultCountryCode
            }
    
            # remove leading zero and any non-digits
            $number = $number -replace '^0|\D', ''
    
            if ($number.Length -lt 9) {
                Write-Warning "Unable to parse the string '$($TelephoneNumber)' as telephone number!"
            }
            else {
                $parts = @($countryCode)
                # split the remaining string in to 3-character parts (+ possible remainder)
                $parts += $number -split '(\d{3})' | Where-Object { $_ }
                return $parts -join ' '
            }
        }
    }
    

    Why not use the Get-ADUser cmdlet to find the mobile property? Something like:

    Import-Module ActiveDirectory
    
    # return the mobile phone number for a user as string or nothing if not found
    # $userID is either the users distinguished name, the GUID, the user SID, or the SamAccountName.
    $mobile = Get-ADUser -Identity $userID -Properties MobilePhone | Select-Object -ExpandProperty MobilePhone
    

    Note: MobilePhone is the PowerShell or GUI name for the mobile attribute, but you may use either.

    Then, if you have this mobile number as string format it using the Format-TelephoneNumber function:

    if ($mobile) { 
        Write-Host "This is raw from AD: $mobile" -ForegroundColor Yellow
        $formatted = Format-TelephoneNumber -TelephoneNumber $mobile
        Write-Host "This is formatted: $formatted" -ForegroundColor Green
    }
    

    Hope that answers your question