Select 数组中的选项

Select option from Array

我正在做一个业余项目,为了让管理更容易,因为几乎所有的服务器名称都是 15 个字符长,我开始寻找 RDP 管理选项,但我喜欢 none;所以我开始写一个,我只剩下一个问题,如果用户输入的内容不足以进行搜索,那么我该如何管理,以便两个服务器匹配查询。我想我必须把它放在一个数组中,然后让他们 select 他们想要的服务器。这是我目前所拥有的

function Connect-RDP
{

param (
    [Parameter(Mandatory = $true)]
    $ComputerName,
    [System.Management.Automation.Credential()]
    $Credential
)

# take each computername and process it individually
$ComputerName | ForEach-Object{
    Try
    {
        $Computer = $_
        $ConnectionDNS = Get-ADComputer -server "DomainController:1234" -ldapfilter "(name=$computer)" -ErrorAction Stop | Select-Object -ExpandProperty DNSHostName
        $ConnectionSearchDNS = Get-ADComputer -server "DomainController:1234" -ldapfilter "(name=*$computer*)" | Select -Exp DNSHostName            
        Write-host $ConnectionDNS
        Write-host $ConnectionSearchDNS
        if ($ConnectionDNS){
        #mstsc.exe /v ($ConnectionDNS) /f
        }Else{
        #mstsc.exe /v ($ConnectionSearchDNS) /f
        }
    }
    catch
    {
        Write-Host "Could not locate computer '$Computer' in AD." -ForegroundColor Red
    }
}
}

基本上我正在寻找一种方法来管理用户是否键入 server1

它会询问他是否想连接到 Server10 或 Server11,因为它们都匹配过滤器。

我确定 mjolinor has it great. I just wanted to show another approach using PromptForChoice。在下面的示例中,我们从 Get-ChildItem 中获取结果,如果有多个结果,我们将构建一个选择集合。用户将 select 一个,然后该对象将被传递到下一步。

$selection = Get-ChildItem C:\temp -Directory

If($selection.Count -gt 1){
    $title = "Folder Selection"
    $message = "Which folder would you like to use?"

    # Build the choices menu
    $choices = @()
    For($index = 0; $index -lt $selection.Count; $index++){
        $choices += New-Object System.Management.Automation.Host.ChoiceDescription ($selection[$index]).Name, ($selection[$index]).FullName
    }

    $options = [System.Management.Automation.Host.ChoiceDescription[]]$choices
    $result = $host.ui.PromptForChoice($title, $message, $options, 0) 

    $selection = $selection[$result]
}

$selection

-Directory 需要 PowerShell v3,但你使用的是 4,所以你会很好。

在 ISE 中它看起来像这样:

在标准控制台中你会看到这样的东西

截至目前,您必须将整个文件夹名称键入 select 提示中的选项。对于也称为加速键的快捷方式,很难在多个选择中获得唯一值。将其视为确保他们做出正确选择的一种方式!

另一个向用户显示选择的选项是 Out-GridView,带有 -OutPutMode 开关。

借用马特的例子:

$selection = Get-ChildItem C:\temp -Directory

If($selection.Count -gt 1){
   $IDX = 0
   $(foreach ($item in $selection){
   $item | select @{l='IDX';e={$IDX}},Name
   $IDX++}) |
   Out-GridView -Title 'Select one or more folders to use' -OutputMode Multiple |
   foreach { $selection[$_.IDX] }
 }

 else {$Selection}   

此示例允许选择多个文件夹,但是您可以通过简单地将 -OutPutMode 切换为 Single

来将它们限制为单个文件夹吗