Home > PowerShell > It’s the little things

It’s the little things

It’s the little things in PowerShell that make a rigid C# developer smile… In the following example, I distribute an array result to separate variables in one line.

$NPA,$NXX,$Digits = Split-Phone 202-456-1111

# In C#, the equivalent would be
# string[] results = SplitPhone("202-456-1111");
# string npa = results.Length > 0 ? results[0] : null;
# string nxx = results.Length > 1 ? results[1] : null;
# string digits = results.Length > 2 ? results[2] : null;

And even the C# syntax mentioned above doesn’t exactly do the same thing because in PowerShell, if the array contains more elements than you’re distributing, the last variable can receive the “remainder” of the array. Since C# doesn’t really have a concept of singleton arrays being treated as strings, there is no direct analogy.

##############################################################################
#.SYNOPSIS
# Splits a phone number into NPA, NXX, and 4 digit components.
#
#.PARAMETER TN
# The telephone number to split.
#
#.RETURNVALUE
# If the specified number is a valid US telephone number, the return value is
# a 3 element array containing NPA, NXX, and the 4 digit line. Otherwise, an
# exception is thrown.
##############################################################################
function Split-Phone {

    param ( [String]$TN )

    
    $Pad = '\s*'
    $Sep = '(\s+|\.|\-)?'
    $Intl = '(?<intl>\+?1)?'
    $NPA = '(\s*\(?\s*(?<npa>\d{3})\s*\)?\s*)'
    $NXX = '(?<nxx>\d{3})'
    $Digits = '(?<digits>\d{4})?'
    
    $Pattern = "^$Pad$Intl$Sep$NPA$Sep$NXX$Sep$Digits$Pad`$"
    
    Write-Debug "Split-Phone Pattern: $Pattern"
    
    if ( $TN -match $Pattern ) {
        if ( $Matches['digits'] ) {
            @(  $Matches['npa'],
                $Matches['nxx'],
                $Matches['digits'] )
        }
        else {
            @(  $Matches['npa'],
                $Matches['nxx'] )
        }
    }
    else {
        throw "Invalid TN: $TN" 
    }
       
}
Categories: PowerShell
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.