Powershell:读取主机以选择阵列索引

问题描述

这是我修改Powershell阵列的方法

ForEach ($userID in $usersList) {
    $allUsers += [pscustomobject]@{ID=$usersCounterTable;UserID=$userID;Name=$userInfo.displayName;Ext=$userInfo.ipPhone;Cellphone=$userInfo.mobile;Enabled=$isEnabled;VDI=$computerType;Title=$userTitle;}
    $usersCounter += 1
    $usersCounterTable = "[$usersCounter]"
}

稍后在代码显示该表,我希望用户能够键入一个数字来打开该值,该数字实际上是数组的索引/偏移量(减1)。我不知道该怎么做。

$userID实际上是用户的选择,因为他们还可以键入其他员工的代码以进行搜索,或搜索其姓名。我希望用户能够选择数组索引号。

if (($userID.length -gt 0) -and ($userID.length -lt 5)) {
    $indexnumber = ($userID - 1)
    [????]  $userFinalChoice = $allUsers[$userID].Name  # NOT VALID
}

如果用户输入1到9999之间的数字,则上述代码有效。 然后,我想这样做:$allUsers[$userID]$userID用户通过“读取主机”选择的号码)。仅有$allUsers[$userID].Name无效,但$allUsers[1].Name才有效。如果我能弄清楚这一点,我将可以修复其余部分并搜索返回值。

还需要确保用户没有输入超出$usersList范围的索引(使用$ErrorActionPreference = "SilentlyContinue"可能会起作用,因为它只是拒绝搜索拒绝,但不是那么干净。)

据我了解,我实际上是在寻找$usersList.IndexOf(‘David’)的反义词,我想提供索引并返回名称

非常感谢-Powershell初学者。

解决方法

您展示给我们的第一个代码块确实令人困惑,因为您似乎只是从某处获取用户详细信息,因此无法确定此信息是否确实属于同一用户。

此外,我真的认为使用格式化表格作为选择菜单不是一个好主意,尤其是如果列表变大的话。也许您应该考虑使用列表框构建表单,或者像Lee_Dailey建议的那样使用Out-GridView

无论如何,如果要用作控制台菜单,请首先确保ID号(实际上是要选择的index)以1开头

$usersCounter = 1
# collect an array of PsCustomObjects in variable $allUsers
$allUsers = foreach ($userID in $usersList) {
    # don't use $allUsers +=,simply output the object
    [PsCustomObject]@{
        ID        = "[$usersCounter]"
        UserID    = $userID
        Name      = $userInfo.DisplayName
        Ext       = $userInfo.ipPhone
        Cellphone = $userInfo.mobile
        Enabled   = $isEnabled
        VDI       = $computerType
        Title     = $userTitle
    }
    $usersCounter++   # increment the counter
}

接下来,将其显示为表格,以便人们可以通过键入“ ID”列中显示的数字来选择用户之一。 循环执行此操作,因此当有人键入有效数字以外的任何内容时,菜单将再次显示。

# start an endless loop
while ($true) {
    Clear-Host
    $allUsers | Format-Table -AutoSize
    $userID = Read-Host "Enter the [ID] number to select a user. Type 0 or Q to quit"
    if ($userID -eq '0' -or $userID -eq 'Q') { break }  # exit from the loop,user quits

    # test if the input is numeric and is in range
    $badInput = $true
    if ($userID -notmatch '\D') {    # if the input does not contain an non-digit
        $index = [int]$userID - 1
        if ($index -ge 0 -and $index -lt $allUsers.Count) {
            $badInput = $false
            # everything OK,you now have the index to do something with the selected user
            # for demo,just write confirmation to the console and exit the loop
            Clear-Host
            Write-Host "You have selected $($allUsers[$index].Name)" -ForegroundColor Green
            break
        }
    }
    # if you received bad input,show a message,wait a couple 
    # of seconds so the message can be read and start over
    if ($badInput) {
        Write-Host "Bad input received. Please type only a valid number from the [ID] column." -ForegroundColor Red
        Start-Sleep -Seconds 4
    }
}