首页 > 解决方案 > 在powershell的全名文本字段中使用姓氏填充变量

问题描述

我有一系列全名,

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

我想仅将来自该字段的姓氏传递给变量。或者也许只有firstinitiallastname。这是我目前给我的名字姓氏首字母:

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
}

同样,我只想查看姓氏。如何为此调整此代码?

标签: stringpowershelltext

解决方案


为什么不获取所有选项

$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

编辑或将名称拆分为第一位

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

推荐阅读