PowerShell: List only Files and/or Folders

Its very often that need to have a files/folders copied across as part of various automations in systems administration or infrastructure customization.  Copy operations aren’t an issue for smaller sizes and/or less number of files.  But, when you have to copy a large number of files/folders of around GBs in size, it becomes difficult job.

While setting file folder copy automation, you need a way to ensure that all the required files and folders or both are successfully to the destination.  To assist that, you can check the count of the files/folder objects in both source and destinations apart from verifying the sizes.

Here is the PowerShell way to get the count of either only files/folder or both.

Since all in PowerShell are .Net objects the list of files/folder obtained using Get-ChildItem are also a set of object.  You can use these objects properties to distinguish whether it’s a file or folder.  The attribute/property to be checked is PsIsContainer.

 

Example: To list ONLY Folders/Directories recursively

Syntax: Get-ChildItem <Directory>  -Recurse | where {$_.PsIsContainer}

 

PS C:> Get-ChildItem C:programdataSkype -Recurse | Where {$_.PsIsContainer} | Select-Object -Property Name | ft -auto

Name
—-
Apps
{4E76FF7E-AEBA-4C87-B788-CD47E5425B9D}
login
css
images
js
languages
platform
retina
retina

PS C:>

 

Example: To list ONLY Folders/Directories recursively

Syntax: Get-ChildItem <Directory> -Recurse | where {!$_.PsIsContainer} |

 

PS C:> Get-ChildItem C:programdataSkype -Recurse | Where {!$_.PsIsContainer} | Select-Object -Property Name | ft -auto

Name
—-
index.html
mac.css
win.css


skype@2x.png
skypeicon@2x.png
login.js
es.js
et.js
Skype.msi

PS C:>

 

 

For easier understanding at high level, you can simply refer to the number of objects found in source and destination folder

Only Folders Count:

PS C:> Get-ChildItem C:programdataSkype -Recurse | Where {$_.PsIsContainer} | Measure-Object | Select-Object -Property Count | ft -auto

Count
—–
   10

PS C:>

 

Only Files Count:

PS C:> Get-ChildItem C:programdataSkype -Recurse | Where {!$_.PsIsContainer} | Measure-Object | Select-Object -Property Count | ft -auto

Count
—–
   88

PS C:>

 

Both Files and Folders Count:

PS C:> Get-ChildItem C:programdataSkype -Recurse | Measure-Object | Select-Object -Property Count | ft -auto

Count
—–
   98

PS C:>