【问题标题】:Get-AzureRmWebApp: filtering results has unexpected behaviorGet-AzureRmWebApp:过滤结果出现意外行为
【发布时间】:2017-01-14 07:20:11
【问题描述】:

我在 Powershell 中键入以下内容,以列出我所有的 azure Web 应用程序的名称:

Get-AzureRmWebApp | % { $_.Name }

它输出:

coolum-exercise-web-app
practice-web-app
AzureSandbox

但是我想根据名称过滤此输出。我输入这个:

Get-AzureRmWebApp | ? { $_.Name -like "coolum-exercise-web-app" } | % { $_.Name }

我希望只看到一个输出。相反,我看到了

coolum-exercise-web-app
practice-web-app
AzureSandbox

为什么没有应用名称过滤器?

如果我直接在Get-AzureRmWebApp 上使用-Name 参数,它可以工作:

Get-AzureRmWebApp -Name "coolum-exercise-web-app" | % { %_.Name }

输出:

coolum-exercise-web-app

但是为什么where-object 无法按预期应用过滤器?


这里有一些非常令人费解的行为:如果你将Get-AzureRmWebApp 括在括号中,过滤器会按照你的预期工作。
(Get-AzureRmWebApp) | ? { $_.Name -like "coolum-exercise-web-app" } | % { $_.Name }

输出:

coolum-exercise-web-app

谁能解释这种行为?为什么将命令括在括号中会使过滤起作用?

【问题讨论】:

    标签: azure azure-web-app-service azure-powershell


    【解决方案1】:

    请尝试:(注意括号)

    (Get-AzureRmWebApp) | ? { $_.Name -like 'cool*' }
    

    看起来整个 where 子句被视为 Get-AzureRmWebApp 的默认命名参数。这就是为什么你必须用括号将 CmdLet 与 where 子句分开。

    实际上 Get-AzureRmWebApp 返回一个列表,而像 Get-AzureRmVM 这样的其他 CmdLet 返回一个对象。

    Get-AzureRmWebApp | gm
    Get-AzureRmVM | gm
    

    【讨论】:

      【解决方案2】:

      这是一个已知错误:#1544 Get-AzureRmWebApp - unable to pipe into select-object

      Get-AzureRmWebApp 的结果是一个列表。您会期望列表中的每一项都通过管道逐项发送。相反,整个列表作为单个对象通过管道发送一次。

      演示:

       Get-AzureRmWebApp | % { $_.GetType().FullName }
      

      展示

      System.Collections.Generic.List`1[[Microsoft.Azure.Management.WebSites.Models.Site, Microsoft.Azure.Management.Websites, Version=1.0.0.2, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]
      

      虽然

      (Get-AzureRmWebApp) | % { $_.GetType().FullName }
      

      展示

      Microsoft.Azure.Management.WebSites.Models.Site
      Microsoft.Azure.Management.WebSites.Models.Site
      Microsoft.Azure.Management.WebSites.Models.Site
      

      出现该错误是因为底层 C# 代码调用 WriteObject(sendToPipeline = list),而它应该调用 WriteObject(sendToPipeline = list, enumerateCollection = true)


      将调用包装在括号中的行为将返回的列表分配给本地临时对象。这个本地临时对象的行为就像一个普通的列表。

      我希望 Azure 团队解决这个问题,因为这会给不幸的自动化脚本编写者带来意想不到的后果。

      比如我原来的调用:

      Get-AzureRmWebApp | ? { $_.Name -like "coolum-exercise-web-app" } | % { $_.Name }
      

      被解释为“如果 任何 值具有 Name,例如 coolum-exercise-web-app,则显示所有值。”


      编辑(2019 年 3 月)

      我已经用Azure Az Powershell Modules 对此进行了测试,我可以看到这个问题已经得到解决。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-18
        • 2015-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-07
        • 2015-05-30
        • 1970-01-01
        相关资源
        最近更新 更多