【问题标题】:How to pick the first element of a list in powershell keeping auto-complete?如何在powershell中选择列表的第一个元素保持自动完成?
【发布时间】:2022-01-23 02:59:10
【问题描述】:

这是我正在调用的命令:

Get-ChildItem | where -Property name -like *asda* | select -first 1 | $_.Name

很明显,最后这个调用不起作用,因为$_ 仅适用于可迭代循环。但我想选择列表中的那个元素并将其转换为我可以调用自动完成(ctrl + 空格)的对象。

如何在 Powershell 中实现这一点?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    你试试?

    (Get-ChildItem | where -Property name -like *asda* | select -first 1).Name
    

    【讨论】:

    • 太棒了!谢谢!
    【解决方案2】:

    JPBlanc's answer 有效,但让我再深入一点:

    对于流式处理解决方案 - Get-ChildItem 发出的每个对象在发出时逐个处理 -使用与 Where-Object (where) cmdlet 相同的 simplified syntax 调用 ForEach-Object

    Get-ChildItem |
      Where-Object -Property Name -like *asda* | 
        Select-Object -First 1 |
          ForEach-Object -MemberName Name
    

    注意:或者,您可以使用 Select-Object -ExpandProperty Name


    对于更简洁解决方案 - 包括收集所有Get-ChildItem 输出预先 - 使用以下内容:

    ((Get-ChildItem).Name -like '*asda*')[0]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-07
      • 2019-10-24
      • 2015-06-07
      • 2017-04-16
      • 1970-01-01
      • 2011-12-30
      • 2019-05-20
      • 1970-01-01
      相关资源
      最近更新 更多