首页 > 解决方案 > 使用映射驱动器填充组合框

问题描述

尝试使用映射的驱动器号(名称)和 FQDN(根)填充组合框。我想我有大部分代码,但组合框条目包括编码条目。

我不仅对如何解决这个问题感到好奇,而且对为什么以这种方式输入结果感到好奇。通过命令行运行它不会以这种方式显示结果。

注意:我还使用一个函数来填充组合框。

检索映射驱动器的代码

Load-ComboBox -ComboBox $cboDomain -Items (Get-PSDrive -PSProvider FileSystem | Select-Object name, @{ n = "Root"; e = { if ($_.DisplayRoot -eq $null) { $_.Root } else { $_.DisplayRoot } } })

加载组合框的功能

function Load-ComboBox{
Param (
    [ValidateNotNull()]
    [Parameter(Mandatory=$true)]
    [System.Windows.Forms.ComboBox]$ComboBox,
    [ValidateNotNull()]
    [Parameter(Mandatory=$true)]
    $Items,
    [Parameter(Mandatory=$false)]
    [string]$DisplayMember,
    [switch]$Append
)
if(-not $Append)
{
    $ComboBox.Items.Clear() 
}
if($Items -is [Object[]])
{
    $ComboBox.Items.AddRange($Items)
}
elseif ($Items -is [System.Collections.IEnumerable])
{
    $ComboBox.BeginUpdate()
    foreach($obj in $Items)
    {
        $ComboBox.Items.Add($obj)   
    }
    $ComboBox.EndUpdate()
}
else
{
    $ComboBox.Items.Add($Items) 
}
$ComboBox.DisplayMember = $DisplayMember}

条目看起来像;
@{名称=C; 根=C:}
@Name=S; 根=\\服务器\共享}

我希望它看起来像;
C<-tab->C:\
S<-tab->\\server\share

*抱歉无法弄清楚如何实际插入标签

标签: winformspowershell

解决方案


由于您将对象发送到函数(Select-Object 返回对象),而不是制表符分隔的字符串数组,因此如果您这样调用该函数,该函数将起作用:

$drives = (Get-PSDrive -PSProvider FileSystem | ForEach-Object { 
    $root = if ($_.DisplayRoot -eq $null) { $_.Root } else { $_.DisplayRoot }
    # output a tab-separated string that gets collected in the $drives variable
    "$($_.Name)`t$root"
})

Load-ComboBox -ComboBox $cboDomain -Items $drives

希望能解释


推荐阅读