This question has actually come up for me a couple of times, and despite searching, I haven't been able to find an answer for it. I'm posting here because I've found a working solution that will hopefully help other users, but I'd also like to know if there is a better way to achieve the same result. When we write
Get-ChildItem -Recurse
We are able to specify a maximum depth, and in that case, Powershell will only search subdirectories until that maximum depth. However, I sometimes want to search to at least a minimum depth. For my own purposes, I really just want to exclude the folder that I am searching in.
For example, if I am in C:/MyFolder, I want to get files from subfolders of MyFolder, but I do not want to get any file that is in MyFolder and not one of its subdirectories. So for the command
Get-ChildItem -Recurse -Filter *.txt
Retrieving the following files would be good
C:\MyFolder\test\hello.txt
C:\MyFolder\abc\cde\goodbye.txt
and these would be bad
C:\MyFolder\yes.txt
C:\MyFolder\no.txt
To solve this issue, I can write:
Get-ChildItem -Recurse -Filter *.txt | Where-Object -FilterScript {$_.Directory.FullName -ne $(Get-Location)}
Which I'm actually quite happy with, but I was wondering if there is a better way to search at a minimum depth, as I am a PowerShell novice. Obviously, we could write a function to handle this depth but I am wondering if any of the more experienced users have a better way of doing this.