Restricting Directory.EnumerateFiles by Linq (Take) in Powershell

youki 1,021 Reputation points
2023-02-15T15:49:59.32+00:00

I've read on an other forum that i can restrict it by the following code but i get an exception, why?

I use PowerShell 5.1 & .NET 4.8.

Issue:

No overload can be found for 'take' and the following argument count: '1'.
https://learn.microsoft.com/de-de/dotnet/api/system.linq.enumerable.take?view=net-7.0

$test = [System.IO.Directory]::EnumerateFiles($folderPath,'*.TAR', [System.IO.SearchOption]::AllDirectories).[System.Linq.Enumerable]::Take(4).[System.Linq.Enumerable]::ToArray()
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,878 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 57,231 Reputation points
    2023-02-15T16:37:47.9933333+00:00

    Is there any reason you are trying to do this using .NET functions instead of just using the built in PS cmdlets?

    Get-ChildItem $folderPath -include *.tar -recurse | Select-Object -First 4
    

    That should give you the first 4 files that match the given extension, recursively searching the given folder path.

    But if you want to use LINQ directly then you can, it's just more complex.

    [System.IO.Directory]::EnumerateFiles($folderPath, '*.tar', [System.IO.SearchOption]::AllDirectories) | Select-Object -First 4  
    

    Note that Take is an extension method and cannot be called on the object returned by EnumerateFiles. It is effectively a static method. In C# we can call it using instance method syntax but that is a C# thing only.

    [System.Linq.Enumerable]::Take([System.IO.Directory]::EnumerateFiles($folderPath, '*.tar', [System.IO.SearchOption]::AllDirectories), 4)  
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.