Luk*_*uke 1 powershell active-directory powershell-4.0
我正在进行一个侧面项目,并且为了管理更容易,因为几乎所有服务器名称都是15个字符长,我开始寻找RDP管理选项,但没有我喜欢的; 所以我开始编写一个,我只讨论一个问题,如果用户键入的内容不足以进行搜索,我该怎么做才能管理,这样两个服务器就会匹配Query.我想我必须把它放在一个数组中然后让他们选择他们想要的服务器.这是我到目前为止所拥有的
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
基本上我正在寻找一种方法来管理用户是否输入server1
它会问他是否想要连接到Server10或Server11,因为它们都匹配过滤器.
我确信mjolinor 有它很棒的地方。我只是想展示另一种使用PromptForChoice 的方法。在下面的示例中,我们从中获取结果Get-ChildItem,如果有多个结果,我们将构建一个选择集合。用户将选择一个,然后该对象将被传递到下一步。
$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
Run Code Online (Sandbox Code Playgroud)
-Directory需要 PowerShell v3,但您使用的是 4,所以您会很好。
在 ISE 中,它看起来像这样:

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

截至目前,您必须输入整个文件夹名称才能在提示中选择选项。很难在快捷键(也称为加速键)的多个选择中获得唯一值。将其视为确保他们做出正确选择的一种方法!
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}
Run Code Online (Sandbox Code Playgroud)
此示例允许选择多个文件夹,但您可以通过简单地切换-OutPutMode到单个文件夹将它们限制为单个文件夹