Hi,
The task appears to be a simple one but I’m out of ideas.
D:\Data\Fol1\fol2\fol3\1.ini
D:\Data\Fol1\fol2\fol3\fol4\2.ini
- start
Get-ChildItem -Recurse -File -Filter ‘.ini’
- as soon as the ini file is found, stop processing the ini folder
D:\Data\Fol1\fol2\fol3\123.ini > D:\Data\Fol1\fol2\fol3\ excluded
D:\Data\Fol1\fol2\fol3\fol4\2.ini should not be included in results
- continue to search for other directories
- finish and return array of objects
An alternative that I know would be using c# yield return but I would like to achieve this via PS 5.1.
Does it matter if you continue the search but filter the results? You could use Select-Object to return just the first result for each subfolder but I realise this isn’t ideal if, for performance reasons, you don’t want to search all subfolders.
$folders = Get-ChildItem -Directory
foreach ($folder in $folders) {
Get-ChildItem $folder -Recurse -File -Filter *.ini | Select-Object -First 1
}
Another import aspect of this is finding it based off of what sort? Name, DateTime, etc.? You’re typically not searching per se, you are filtering a dataset to only return what you want. As Matt eluded, you can use Select-Object -First to find the newest txt file in a directory like so:
PS C:\Users\rasim> Get-ChildItem C:\Scripts\*.txt -File
Directory: C:\Scripts
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 11/22/2019 4:25 PM 0 amy_Temp1.txt
-a---- 11/22/2019 4:25 PM 0 amy_Temp2.txt
-a---- 11/22/2019 4:25 PM 0 amy_Temp5.txt
-a---- 11/22/2019 4:25 PM 0 amy_Temp8.txt
-a---- 1/10/2020 1:17 PM 43 domains.txt
-a---- 1/29/2020 11:07 PM 729 file2.txt
-a---- 11/25/2019 9:28 AM 100 john_Temp0.txt
-a---- 11/22/2019 4:25 PM 0 john_Temp4.txt
-a---- 11/22/2019 4:25 PM 0 john_Temp6.txt
-a---- 11/22/2019 4:25 PM 0 john_Temp7.txt
-a---- 1/30/2020 9:50 AM 140 ls.txt
-a---- 7/23/2020 11:48 AM 20 random.txt
-a---- 7/23/2020 11:45 AM 20 random2.txt
-a---- 11/22/2019 4:25 PM 0 sally_Temp10.txt
-a---- 11/22/2019 4:25 PM 0 sue_Temp3.txt
-a---- 11/22/2019 4:25 PM 0 sue_Temp9.txt
-a---- 3/16/2020 4:46 PM 10893 tfile.txt
PS C:\Users\rasim>
Get-ChildItem C:\Scripts\*.txt -File |
Sort-Object LastWriteTime -Descending |
Select-Object Name, LastWriteTime -First 1
Name LastWriteTime
---- -------------
random.txt 7/23/2020 11:48:44 AM