To count files in a folder using PowerShell, you can use the Get-ChildItem cmdlet along with the Measure-Object cmdlet.
Method 1: Count files in a folder using Get-ChildItem
(Get-ChildItem -Path $folderPath -File | Measure-Object).Count
This example returns the total number of files in a folder by using the Get-ChildItem cmdlet with the Measure-Object command.
Method 2: Count files recursively in a folder and subfolders using Get-ChildItem
(Get-ChildItem -Path $folderPath -Recurse -File | Measure-Object).Count
This example returns the total files in a folder and subfolders by using the Get-ChildItem cmdlet along with its parameter -Recurse.
These methods can be used to count files in a folder in PowerShell.
The following examples show how to use these methods.
Count files in a folder using Get-ChildItem
To count files in a folder in PowerShell, use the Get-ChildItem cmdlet with the Measure-Object cmdlet.
The following example shows how to use it with syntax.
(Get-ChildItem -Path C:\temp\ -File| Measure-Object).Count
In this PowerShell script, the Get-ChildItem cmdlet with the -File switch to retrieve only files from the folder name specified “C:\temp\“. It pipes the files to the Measure-Object cmdlet to count the number of files.
The Measure-Object cmdlet counts the objects received from the pipeline and returns the total count of files in a folder.
The output of the above PowerShell script is given below.
PS C:\> (Get-ChildItem -Path C:\temp\ -File| Measure-Object).Count
19
PS C:\>
Count Files Recursively in a Folder and Subfolders Using Get-ChildItem
To count files recursively in a folder in PowerShell, you can use the Get-ChildItem cmdlet with the -Recurse parameter with the -File switch to retrieve files in a folder.
The following example shows how to do it with syntax.
(Get-ChildItem -Path C:\temp\ -Recurse -File| Measure-Object).Count
In this PowerShell script, the Get-ChildItem with the -File and -Recurse switch retrieve files recursively in a folder “C:\temp\” and pipes the output to the Measure-Object cmdlet.
The Measure-Object cmdlet counts the files received from the pipeline and returns the total count.
Output:
PS C:\> (Get-ChildItem -Path C:\temp\ -Recurse -File| Measure-Object).Count
95599
PS C:\>
Conclusion
I hope the above article on how to count files in a folder in PowerShell using the Get-ChildItem cmdlet is helpful to you.
You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.