Powershell循环直到输出为一行

Powershell loop until the output is one line

我想要实现的是,如果输出是一行并且该行被写入变量。这是我现在拥有的代码:

Connect-AzureRmAccount
(get-azurermresourcegroup).ResourceGroupName 
$filter = Read-Host -Prompt "Please filter to find the correct resource group" 
$RGName = get-azurermresourcegroup | Where-Object { $_.ResourceGroupName -match $filter } 
$RGName.resourcegroupname

此代码过滤一次,然后将所有行逐一写入,结果如下:

ResourceGroup-Test
ResourceGroup-Test-1
ResourceGroup-Test-2 

但首选输出是继续过滤直到剩下一个

外网格视图

but the preferred output is to keep filtering until one is left

根据 运行 用户选择的过滤器,这可能是一种惩罚方法/不必要的复杂化。如果您只想要 一个 结果如何,我们改为使用 Out-GridView 之类的东西来允许用户从他们选择的过滤器中 select 一个结果。

$filter = Read-Host -Prompt "Please filter to find the correct resource group" 
$RGName = get-azurermresourcegroup | 
    Where-Object { $_.ResourceGroupName -match $filter } | 
    Out-GridView -OutputMode Single 
$RGName.resourcegroupname

可以使用-PassThru,但这允许多个select离子。 -OutputMode Single。因此,如果 $filter 太模糊,这仍然有可能制作一个巨大的 selection 集,但这是确保您获得一个结果的简单方法。另一个警告是用户可以单击取消。所以你可能还需要一些循环逻辑:do{..}until{}。这取决于你想让这个过程有多大的弹性。

选择

如果Out-GridView不是你的速度。另一种选择是使用 $host.ui.PromptForChoice 创建一个动态选择系统。以下是允许用户从集合中选择子文件夹的示例。

$possibilities = Get-ChildItem C:\temp -Directory

If($possibilities.Count -gt 1){
    $title = "Folder Selection"
    $message = "Which folder would you like to use?"

    # Build the choices menu
    $choices = @()
    For($index = 0; $index -lt $possibilities.Count; $index++){
        $choices += New-Object System.Management.Automation.Host.ChoiceDescription  ($possibilities[$index]).Name
    }

    $options = [System.Management.Automation.Host.ChoiceDescription[]]$choices
    $result = $host.ui.PromptForChoice($title, $message, $options, 0) 

    $selection = $possibilities[$result]
}

$selection

您应该能够按照我在 Out-GridView 中建议的方式将其调整到您的代码中。不过要小心这种方法。选项太多会使屏幕混乱。