如何将哈希表数组转换为字符串数组

时间:2017-05-17 04:43:29

标签: powershell powershell-v4.0

如何将哈希表数组转换为字符串数组?

我尝试创建一个简单的菜单,允许用户从列表中选择服务器。这是列表的一个示例:

$sqlServers = @(@{key="LOCALDB"; serverName="(localdb)\mssqllocaldb"; 
                    credentials="-E"; userEntry="L"; 
                    menuText="(L)ocaldb`t`t((localdb)\mssqllocaldb)"},
                @{key="DEV"; serverName="DEV_SERVER"; 
                    credentials="-E"; userEntry="D"; 
                    menuText="(D)ev`t`t`t(DEV_SERVER)"},
                @{key="TEST"; serverName="TEST_SERVER"; 
                    credentials="-E"; userEntry="T"; 
                    menuText="(T)est`t`t`t(TEST_SERVER)"})

这将显示如下:

(L)ocaldb       ((localdb)\mssqllocaldb) 
(D)ev           (DEV_SERVER)
(T)est          (TEST_SERVER)

我想从我的服务器列表中读取有效用户选择列表,然后检查用户按下的密钥是否在有效选项列表中。这是我到目前为止所得到的:

function Get-UserSelection (
    [Parameter(Mandatory=$True)]
    $servers
    )
{
    Write-Host "Select the server to run the SQL scripts on (type a letter followed by the [Enter] key, or press CTRL+C to exit)"

    foreach ($server in $servers)
    {
        Write-Host "`t" $server.menuText
    }

    $validSelections = $servers | Select-Object {$_.userEntry}
    $userSelection = ""

    while ($True)
    {
        $userSelection = Read-Host         

        ForEach ($validSelection in $validSelections)
        {
            if ($userSelection -eq $validSelection) 
            {
                return $userSelection
            }
        }

        Write-Host "Invalid selection.  Please try again or press CTRL+C to exit"
    }
}

问题在于$validSelection,而不是LD的值,在转换为字符串时具有@{$_.userEntry=L}的值,因此{ {1}}从未被视为有效。

我认为问题出在

$userSelection (eg "d")

如何修改此内容,以便$validSelections = $servers | Select-Object {$_.userEntry} 字符串数组而不是自定义对象数组?

1 个答案:

答案 0 :(得分:1)

你快到了。只需在每个哈希表上使用ForEach-Object cmdlet 迭代,然后选择userEntry

$validSelections = $sqlServers | ForEach-Object {$_.userEntry}