1

I have an array of full names,

$doctors = @(
    'John Q. Smith',
    'Mary X. Jones',
    'Thomas L. White',
    "Sonia M. O'Toole"
)

I would like to pass in to a variable the lastname only from that field. Or maybe only firstinitiallastname. Here is what I currently have giving me the firstnamelastinitial:

try {
    # add firstnames to list
    $firstnames = New-Object System.Collections.ArrayList
    foreach ($doctor in $doctors) {
        $docname = ($doctor -split '\s')
        $docname = $docname[0]+$docname[-1][0]
        $firstnames += $docname
}

Again, I would like to see only the last name. How do I adjust this code for that?

Omar Einea
  • 2,478
  • 7
  • 23
  • 35

3 Answers3

0

EBGreen is on-point...

$last_name_only = @()
$first_init_last_name = @()

foreach ($doctor in $doctors) {
    $docname = ($doctor -split '\s')
    $last_name_only += $docname[-1]
    $first_init_last_name += "{0}, {1}" -f $doctor[0], $docname[-1]
}

$last_name_only
$first_init_last_name
Adam
  • 3,891
  • 3
  • 19
  • 42
0

Why not get all options

$Docs = ForEach ($doctor in $doctors) {
    $First,$Middle,$Last = ($doctor -split '\s')
    [PSCustomObject]@{
       Fullname  = $doctor
       Firstname = $First
       Middle    = $Middle
       Lastname  = $Last
       Docname   = $First+$Last[0]
    }
}
$Docs | ft -auto

Fullname         Firstname Middle Lastname Docname
--------         --------- ------ -------- -------
John Q. Smith    John      Q.     Smith    JohnS
Mary X. Jones    Mary      X.     Jones    MaryJ
Thomas L. White  Thomas    L.     White    ThomasW
Sonia M. O'Toole Sonia     M.     O'Toole  SoniaO

$Docs.DocName -join ', '
JohnS, MaryJ, ThomasW, SoniaO

EDIT Or split the names first place with

$doctors = @(
    'John Q. Smith',
    'Mary X. Jones',
    'Thomas L. White',
    "Sonia M. O'Toole"
)| ConvertFrom-Csv -Delimiter ' ' -Header Firstname.MiddleInitial,Lastname
0

You can use the -replace operator, which accepts an array-valued LHS:

$lastNames = $doctors -replace '.* (.*)$', '$1'

$1 in the replacement operand refers to what the 1st (and only ) capture group ((...)) in the regex operand captured, effectively replacing each input string with the last whitespace-separated token.

For more on how the -replace operator works, see this answer of mine.

A complete example:

# The input array.
# Note that there's no need to use @(...) to create an array literal.
$doctors =
    'John Q. Smith',
    'Mary X. Jones',
    'Thomas L. White',
    "Sonia M. O'Toole"

# Create a parallel array of last names only.
$lastNames = $doctors -replace '.* (.*)$', '$1'

$lastNames  # output the result

The above yields:

Smith
Jones
White
O'Toole
mklement0
  • 382,024
  • 64
  • 607
  • 775