2017-04-21 57 views
0

我试图让多个用户首先和姓氏被转换成格式:使用GUI输入框时的第一个首字母+姓氏。我的代码是错误的,它保留了第一个数组字母,并且不会将其删除以允许其他输入执行相同的任务。我尝试删除以帮助删除固定大小的数组。没有工作。我读到我必须创建另一个数组以从第一个数组中移除。这是我卡住的地方。我如何让第二个数组删除第一个条目,并尽可能保留相同的变量 - 我想在输入框中输入X个名称并为每个用户运行其他任务。Powershell Array

现在的结果如下: jblank jeric jbob

我试着让

jblank,enewnew,BMO

帮助,请。谢谢

Add-Type –assemblyName Microsoft.VisualBasic 
Add-Type –assemblyName System.Windows.Forms 

$User = "joe blank, eric newnew, bob mo" # 
[Microsoft.VisualBasic.Interaction]::InputBox("Enter Employee name or 
names.`nSeparate with a comma (,) or semi-colon (;).`n ** Do not add 
quotation marks **", "Search book") 

If (-Not [System.String]::IsNullOrEmpty($User)) { 
    [string[]]$Username = $User -split ",|;" 
    ForEach ($User in $Username) { 
    #Write-host $User -ForegroundColor Yellow 

$Fname = $User.Split(" ")[0].trim() 
$Lname = $User.Split(" ")[1].trim() 



#initials 
$In = $FName 
$InRM = $In.Remove(1) 
$unID = $InRM+$LName # intials done 

$newID = @() 
    foreach ($u in $User) 
    { 
    if ($User -ne 0) 
    { 
     Write-Host "Remove [0] here or something like that eq to $unID again" 
    } 
} 

Write-Host $unID -foregroundcolor "green" 
## Do more stuff here for each user ## 
+1

不要再使用'在'ForEach'循环$ User'。另外,当你像'$ Username = $ User -split'一样分割空白时,| |“ | ForEach {$ _。trim()}'因为现在'$ UserName'中的第二个字符串具有前面的空格,导致它认为第一个名字是空白的,并且姓氏是eric,并且它放弃了实际的姓氏。 – TheMadTechnician

+0

是的,就是这样..'$ User -split“,|;” | ForEach {$ _。trim()}'在这之后,所有事情都开始了。男人我并不认为输入在第一个条目上会有空格...现在就开始工作了! :) –

回答

0

你觉得这样的事情吗?

$User = "joe blank, eric newnew, bob mo" 
#define arry for later 
$SortUser = @() 
#split users from textbox 
$Users = @($User.Split(",")) 
#loop users 
foreach($i in $Users){ 
    if($i.Substring(0,1) -eq " "){ 
    #remove space which make problems 
     $i = $i.Remove(0,1) 
    } 
    $Split = $i.Split(" ") 
    $First = $Split[0] 
    $Last = $Split[1] 
    $FirstLetter = $First.Remove(1,$First.Length - 1) 

    #Add all informations to object 
    $obj = New-Object PSCustomObject 
    $obj | Add-Member -type NoteProperty -name First -Value $First 
    $obj | Add-Member -type NoteProperty -name Last -Value $Last 
    $obj | Add-Member -type NoteProperty -name Username -Value "$FirstLetter.$Last" 
    #fill all objects in one array 
    $SortUser += $obj 
} 
$SortUser 

结果:

First Last Username 
----- ---- -------- 
joe blank j.blank 
eric newnew e.newnew 
bob mo  b.mo 
+0

'$ Users = @($ User.Split(“,”)。Trim())' – JosefZ