Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

powershell - Select option from Array

I am working on a side project and to make it easier for managment since almost all of out server names are 15 charactors long I started to look for an RDP managment option but none that I liked; so I started to write one and I am down to only one issue, what do I do to manage if the user types not enough for a search so two servers will match the Query. I think I will have to put it in an array and then let them select the server they meant. Here is what I have so far

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
    }
}
}

Basically I am looking for a way to manage if a user types server1

that it will ask does he want to connect to Server10 or Server11 since both of them match the filter.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Another option for presenting choices to the user is Out-GridView, with the -OutPutMode switch.

Borrowing from Matt's example:

$selection = Get-ChildItem C:emp -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}   

This example allows for selection of multiple folders, but can you can limit them to a single folder by simply switching -OutPutMode to Single


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...