Home > Back-end >  Return only folders containing files using Powershell
Return only folders containing files using Powershell

Time:12-02

Suppose I have a directory tree as follows:

root
├───A
│   ├───1
│   │       a.txt
│   │       b.txt
│   │
│   ├───2
│   │       a.txt
│   │
│   └───3
├───B
│   ├───1
│   │       a.txt
│   │       b.txt
│   │
│   └───3
└───C
    ├───1
    └───2

Using Powershell, I would like to return only the directories which contain files as follows:

root/A/1
root/A/2
root/B/1

What is the best way to do this using Powershell?

CodePudding user response:

From whatever root folder you want to test, you can get all directories where a file exists with this:

$path = "path you wish to evaluate"
#recurse all directories under $path, 
#returning directories where there is a leaf child item below it
Get-ChildItem $path -Directory -Recurse | 
  Where-Object { Test-Path "$_\*" -PathType Leaf } |
  Select FullName

CodePudding user response:

Pipe the output from Get-ChildItem -Directory -Recurse to Where-Object and test if any files exist immediately under each:

Get-ChildItem -Directory -Recurse |Where-Object { $_ |Get-ChildItem -File |Select -First 1 }

CodePudding user response:

I just tested this. Please note normally people attempt to code first, and get help with errors in the code...

Try the below

$a = Get-ChildItem -Recurse -File *.txt  | sort Count -Descending
$a | Select Name, BaseName, Directory, DirectoryName

If you want to select more to view from - System.IO.FileInfo

$a | get-member

CodePudding user response:

One more way... This gets a list of all directories, then checks to see if each one contains files.

Get-ChildItem -Directory -Recurse -Path 'C:\' |
    ForEach-Object { if ((Get-ChildItem -File -Path $_).Length -gt 0) { $_.FullName }}
  • Related