2017-04-21 38 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