Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...