【问题标题】:Powershell loop until the output is one linePowershell循环直到输出为一行
【发布时间】:2018-11-06 12:51:03
【问题描述】:

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

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 

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

【问题讨论】:

  • 所以你想继续从主机读取,直到它们过滤得足够具体以获得一个结果?为什么不改用Out-GridView -passthru 之类的东西呢?您可以强制一个结果(来自一组),它允许最终用户找到他们想要的结果而不会因为不够具体而受到惩罚?
  • 听起来是个好计划!只是我不知道在代码中的哪里添加它,您建议我将它放在代码中的哪里?

标签: azure powershell azure-cli azure-cli2


【解决方案1】:

Out-GridView

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

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

$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,但这允许进行多项选择。 -OutputMode Single。因此,如果$filter 太模糊,这仍然有可能产生大量选择集,但这是确保获得一个结果的简单方法。另一个警告是用户可以单击取消。所以你可能仍然需要一些循环逻辑: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 中建议的方式将其调整到您的代码中。不过要小心这种方法。选项太多会使屏幕混乱。

【讨论】:

  • 是否还有一种方法可以不使用 gridview 并且它只是在现有的 cmd 中继续?
  • 不确定你的意思。不是单独的窗口?它确实继续
  • PS C:\Patht> (get-azurermresourcegroup).ResourceGroupName >RG-test >RG-test-1 这就是我想要的结果
  • Where-Object { $_.ResourceGroupName -match $filter } | Select -Expand ResourceGroupName | Out-GridView -OutputMode Single ?
  • 有没有办法避免这个答案为零?
猜你喜欢
  • 2021-03-13
  • 1970-01-01
  • 2016-04-25
  • 1970-01-01
  • 2016-07-11
  • 1970-01-01
  • 2018-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多