Forum Discussion
Find all files inside directory Trees with a given name. Powershell question
- Nov 05, 2020
This is the updated code
Set-location c:\ Get-ChildItem -Include *.txt -Recurse | where {$_.FullName -like "*\AD\*"}
you don't need to use the path if you already use set-location.
the update here is adding the where filter to filter all the stream from the Get-ChildItem and check if in the full path of the result include a folder named AD.
as you are scanning the entire root this should give you the result you are looking for.
farismalaeb Thank you for the reply but I'm looking for the reason why.
I've updated the original post to include more details. The exercise is to find all the files in a directory tree or on a drive with a given directory name. The directory can be located in multiple places on the drive or in the tree. I used AD for the example but it could be "Users", "Temp" or "Deleted Items.IMAP" etc.
My ideal code would not have me search the drive for all the instances of the requested Directory name and then process that object looking for the files within. I'm new to Powershell programming and how cmdlets behave. The path parm acts differently depending on some variables I do not understand. I've tested the above code and have gotten different results depending on where the current path is set. Some times no results. Some times the first instance of the Directory, Some times everything that is requested. What is affecting the behavior?
I see the -path parm is not a reliable method of finding a specific directory name if there are multiple instances of the name in different places in the tree.
This is the updated code
Set-location c:\
Get-ChildItem -Include *.txt -Recurse | where {$_.FullName -like "*\AD\*"}
you don't need to use the path if you already use set-location.
the update here is adding the where filter to filter all the stream from the Get-ChildItem and check if in the full path of the result include a folder named AD.
as you are scanning the entire root this should give you the result you are looking for.
- TampaCCTNov 06, 2020Copper Contributor
farismalaeb You didn't answer my question but I agree code given will work every time constantly. I will stay away from wild cards in the path. Thank you I was hoping by using the wildcards in the path that I could improve the speed and reduce memory consumption. Get-childitems of an entire drive can take a long time.
- PeterJ_InobitsNov 16, 2020Iron Contributor