Search code examples
powershellpowershell-3.0powershell-4.0

Get files from specific folders in a directory in PowerShell


I have 4 folders in a directory. All of those folders contains some files. I want to list the file names only from the two folders.

C:\MainFolder\FolderOne\FileOne.txt
C:\MainFolder\FolderTwo\FileTwo.txt
C:\MainFolder\FolderThree\FileThree.txt
C:\MainFolder\FolderFour\FileFour.txt

I only want to list the files under FolderTwo and FolderThree.

If I use -Recurse -Include "FolderNames" it'll list only the folder names.


Solution

  • $source="c:\MainFolder" #location of starting directory
    $files=@("*.txt", "*.doc") #if you want to include extensions add -include ($files) to get-ChildItem
    
    Get-ChildItem -recurse ($source) -File | Where-Object {$_.PSParentPath -match "Two|Three"}