How to prevent Get-ChildItem from going through a specific directory?

Let me say that I looked at Failed to exclude a directory using the Get-ChildItem -Exclude option in Powershell and How can I exclude multiple folders using Get-ChildItem -exclude? . None of them have an answer that solves my problem.

I need to search the directory recursively for files with a specific extension. For simplicity, let me say that I need to find *.txt . Normally this command would be enough:

 Get-ChildItem -Path 'C:\mysearchdir\' -Filter '*.txt' -Recurse 

But I have a serious problem. There node_modules is somewhere inside C:\mysearchdir\ , and NPM creates very deep C:\mysearchdir\ . (The detail that this is an NPM managed directory is important only because it means that the depth is out of my control.) This leads to the following error:

 Get-ChildItem : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters. 

I believe this error occurs due to limitations in the .NET IO libraries.

I can not find in other directories around it very easily. This is not at the top of the directory; it's deeper, say, in C:\mysearchdir\dir1\dir2\dir3\node_modules , and there are directories that I need to search at all these levels. Thus, simply searching for other directories around it will be cumbersome and not very convenient, as more files and directories are added.

I tried the -Exclude without any success. This is not surprising, since I just read that -Exclude applies only after the results are received. I cannot find any real information on using -Filter (as indicated in this answer ).

Is there a way that I can work with Get-ChildItem , or am I stuck with my own recursive workaround?

+6
source share
2 answers

Oh man, I feel stupid. I encountered the same problem as you. I worked with @ DarkLite1's answer, trying to parse it when I hit the "-A SilentlyContinue" part.

Facepalm

FACEPALM!

That is all you need!

This worked for me, try:

 Get-ChildItem -Path 'C:\mysearchdir\' -Filter '*.txt' -Recurse -ErrorAction SilentlyContinue 

Note. This does not exclude node_modules from the search, it simply hides any errors that occur when passing a long path. If you need to completely eliminate it, you will need a more complex solution.

+5
source

Perhaps you could try something like this:

 $Source = 'S:\Prod' $Exclude = @('S:\Prod\Dir 1', 'S:\Prod\Dir 2') Get-ChildItem -LiteralPath $Source -Directory -Recurse -PipelineVariable Dir -EV e -EA SilentlyContinue | Where {($Exclude | Where {($Dir.FullName -eq "$_") -or ($Dir.FullName -like "$_\*")}).count -eq 0} 
+1
source

Source: https://habr.com/ru/post/983624/


All Articles