Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pick the first element of a list in powershell keeping auto-complete?

Tags:

powershell

This is the command I am invoking:

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

Obviously this call at the end doesn't work because the $_ only works for iterable loops. But I want to pick that element of the list and turn it into a object where I can call auto complete (ctrl + space).

How can I achieve that in Powershell?

like image 551
Daniel Oliveira Avatar asked Jan 25 '26 08:01

Daniel Oliveira


2 Answers

Do you try ?

(Get-ChildItem | where -Property name -like *asda* | select -first 1).Name
like image 165
JPBlanc Avatar answered Jan 26 '26 21:01

JPBlanc


JPBlanc's answer is effective, but let me dig a little deeper:

For a streaming solution - where each object being emitted by Get-ChildItem is processed one by one, as it is being emitted - use a ForEach-Object call with the same simplified syntax you're using with the Where-Object (where) cmdlet:

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

Note: Alternatively, you could use Select-Object -ExpandProperty Name.


For a more concise solution - which involves collecting all Get-ChildItem output up front - use the following:

((Get-ChildItem).Name -like '*asda*')[0]
like image 43
mklement0 Avatar answered Jan 26 '26 22:01

mklement0