Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interrupt [IO.Directory]::GetFiles() in powershell?

I'm using the following to quickly find specific files from powershell CLI.

[IO.Directory]::GetFiles($searchDir, $searchFile, [IO.EnumerationOptions] @{AttributesToSkip='Hidden,Device,Temporary,SparseFile'; RecurseSubdirectories=$true; IgnoreInaccessible=$true })

This is aliased in a function, and when I run it and it has found a match, but still searching for more, I cannot interrupt (CTRL+C) the call, forcing me to wait for all results.

Q: How can I can enable interrupting the process once a match is found?

like image 289
not2qubit Avatar asked Dec 28 '25 14:12

not2qubit


1 Answers

Remarks from both documentations state that:

The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names before the whole collection is returned. When you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.

To answer your question, if you want to interrupt the method in the middle of a pipeline the correct method to call will be Directory.EnumerateFiles:

[IO.Directory]::EnumerateFiles($searchDir, $searchFile, [IO.EnumerationOptions] @{AttributesToSkip='Hidden,Device,Temporary,SparseFile'; RecurseSubdirectories=$true; IgnoreInaccessible=$true })

This method will allow you to interrupt either with Select-Object -First, foreach + break / return and CTRL + C without performing unnecessary enumeration.

like image 74
Santiago Squarzon Avatar answered Dec 30 '25 17:12

Santiago Squarzon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!