.netwindowspowershellsystem.io.directory

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?


Solution

  • 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.