PowerShell Get-ChildItem Files Only [with Practical Examples]

As a PowerShell expert with over a decade of experience, I’ve seen countless scenarios where administrators need to retrieve only files from directories while excluding folders. When working with file system operations, you’ll often need to list files only without including directories in your results. You can do this using the Get-ChlidItem PowerShell cmdlet. In this tutorial, we will learn everything about the PowerShell Get-ChildItem Files Only with examples.

PowerShell Get-ChildItem

The Get-ChildItem cmdlet in PowerShell retrieves items from one or more specified locations. By default, it returns both files and directories. Here’s the basic syntax:

Get-ChildItem [-Path] <String[]> [parameters]

Basic Example

# This returns both files and folders
Get-ChildItem C:\Users\fewli\Downloads

When you execute Get-ChildItem without any filtering parameters, it returns all items in the specified location, including both files and directories.

Each returned object contains properties that help distinguish between files and directories, such as the PSIsContainer property (which is $false for files and $true for directories) and the Mode attribute that displays permissions and file type information.

Now let me show you different methods to get files only using the PowerShell Get-ChildItem cmdlet.

Method 1: Using the -File Parameter

The -File parameter, available in PowerShell 3.0 and later, represents the most straightforward method for retrieving only files. This parameter was specifically designed to address the common need for file-only operations, providing excellent performance by filtering at the cmdlet level rather than through post-processing operations.

The simplest implementation involves adding the -File parameter to exclude all directories from results:

Get-ChildItem -Path "C:\Users\fewli\Downloads" -File

This command returns only files in the Documents directory, completely excluding any subdirectories.

Here is the exact output in the screenshot below:

PowerShell Get-ChildItem Files Only

Recursive File Discovery

When combined with the -Recurse parameter, -File enables comprehensive file discovery across directory trees:

Get-ChildItem -Path "C:\Users\Username\Documents" -File -Recurse

This traverses all subdirectories and returns only files, ignoring the directory structure itself.

Depth-Limited Recursion

For performance optimization in deep directory structures, you can control recursion depth:

Get-ChildItem -Path "C:\Program Files" -File -Recurse -Depth 2

This limits traversal to two directory levels, preventing excessive processing time in deeply nested folder hierarchies.

Check out PowerShell Get-ChildItem Filter Examples

Method 2: Pipeline Filtering with Where-Object

The Where-Object cmdlet provides maximum flexibility for file filtering, especially when working with older PowerShell versions or when complex filtering criteria are required. This method works by retrieving all items first, then filtering based on object properties.

Basic PSIsContainer Filtering

The fundamental approach uses the PSIsContainer property to identify files:

Get-ChildItem -Path "C:\Data" | Where-Object {$_.PSIsContainer -eq $false}

This filters out all directories by selecting only items where PSIsContainer equals $false.

Size-Based Filtering

Complex filtering scenarios often require multiple criteria, such as finding large files that may need cleanup:

Get-ChildItem -Path "C:\Downloads" | Where-Object {($_.PSIsContainer -eq $false) -and ($_.Length -gt 1MB)}

This identifies files larger than 1MB while excluding directories, useful for disk space analysis.

Time-Based Filtering

Date-based filtering helps identify recently modified files for maintenance or auditing purposes:

$SevenDaysAgo = (Get-Date).AddDays(-7)
Get-ChildItem -Path "C:\Logs" | Where-Object {($_.PSIsContainer -eq $false) -and ($_.LastWriteTime -gt $SevenDaysAgo)}

This finds files modified within the last seven days, excluding directories from consideration.

Check out How to List Hidden Files in PowerShell?

Method 3: Include Parameter with Extensions

The -Include parameter offers a middle-ground approach that works particularly well for targeting specific file types. Since directories typically don’t have file extensions, patterns like *.* effectively filter out most directories while including files.

Basic Extension Filtering

Using wildcard patterns to match files with extensions, below is an example.

Get-ChildItem -Path "C:\Documents" -Include "*.*" -Recurse

This matches any filename containing a dot, effectively excluding directories that typically don’t have extensions.

Specific File Type Targeting

When working with particular file types, you can specify exact extensions:

Get-ChildItem -Path "C:\Scripts" -Include "*.ps1", "*.psm1" -Recurse

This targets only PowerShell script and module files, useful for code management tasks.

Document Type Filtering

For document management operations, you can target office file formats:

Get-ChildItem -Path "C:\Reports" -Include "*.docx", "*.xlsx", "*.pdf" -Recurse

This identifies common document formats for processing or archival operations.

Now, let me show you some real examples.

Read Find Files Modified After a Specific Date Using PowerShell

PowerShell Get-ChildItem Files Only Examples

Example 1: Disk Space Analysis

This example identifies the largest files consuming disk space, helping prioritize cleanup efforts:

Get-ChildItem -Path "C:\Users" -File -Recurse -ErrorAction SilentlyContinue |
Sort-Object Length -Descending |
Select-Object -First 10 |
Select-Object Name, @{Name="SizeGB"; Expression={[math]::Round($_.Length/1GB, 3)}}, DirectoryName

The script finds the 10 largest files across user directories and displays their sizes in gigabytes for easy interpretation.

Example 2: Log File Management

This example identifies large log files that may need rotation or cleanup:

$LogFiles = Get-ChildItem -Path "C:\Logs" -File -Include "*.log" -Recurse |
Where-Object {$_.Length -gt 50MB}

$LogFiles | Select-Object FullName, 
@{Name="SizeMB"; Expression={[math]::Round($_.Length/1MB, 2)}},
LastWriteTime | Format-Table -AutoSize

The script targets log files larger than 50MB and displays their paths, sizes, and last modification times.

Example 3: Security Audit for Executable Files

This example scans user directories for executable files that might indicate unauthorized software:

$ExecutableExtensions = "*.exe", "*.msi", "*.bat", "*.cmd", "*.scr"
$UserDirs = Get-ChildItem -Path "C:\Users" -Directory

foreach ($UserDir in $UserDirs) {
    $Executables = Get-ChildItem -Path $UserDir.FullName -File -Include $ExecutableExtensions -Recurse -ErrorAction SilentlyContinue
    if ($Executables) {
        Write-Output "Executables found in $($UserDir.Name):"
        $Executables | Select-Object Name, Directory, CreationTime | Format-Table
    }
}

This comprehensive scan checks each user directory for various executable file types and reports findings.

Example 4: Backup Verification Script

This example verifies that recent backup files exist and meet the expected criteria:

$BackupPath = "D:\Backups"
$Yesterday = (Get-Date).AddDays(-1)

$RecentBackups = Get-ChildItem -Path $BackupPath -File -Include "*.bak", "*.zip", "*.7z" |
Where-Object {$_.LastWriteTime -gt $Yesterday}

if ($RecentBackups.Count -gt 0) {
    Write-Output "Found $($RecentBackups.Count) recent backup files:"
    $RecentBackups | Select-Object Name, 
    @{Name="SizeMB"; Expression={[math]::Round($_.Length/1MB, 2)}},
    LastWriteTime | Format-Table
} else {
    Write-Warning "No recent backup files found! Check backup system."
}

The script validates that backup files were created within the last day and provides size information for verification.

Example 5: File Type Distribution Report

This example analyzes file type distribution to understand storage usage patterns:

$FileTypeReport = Get-ChildItem -Path "C:\Data" -File -Recurse -ErrorAction SilentlyContinue |
Group-Object Extension |
Select-Object @{Name="FileType"; Expression={if($_.Name -eq "") {"No Extension"} else {$_.Name}}},
             @{Name="FileCount"; Expression={$_.Count}},
             @{Name="TotalSizeMB"; Expression={[math]::Round(($_.Group | Measure-Object Length -Sum).Sum / 1MB, 2)}} |
Sort-Object TotalSizeMB -Descending

$FileTypeReport | Format-Table -AutoSize
Write-Output "Total file types analyzed: $($FileTypeReport.Count)"

This analysis groups files by extension and calculates total space used by each file type, useful for storage planning.

Example 6: Automated File Cleanup Based on Age

This example identifies old temporary files that can be safely removed:

$TempPaths = @("C:\Temp", "C:\Windows\Temp", "$env:USERPROFILE\AppData\Local\Temp")
$ThresholdDate = (Get-Date).AddDays(-30)
$TotalCleaned = 0

foreach ($TempPath in $TempPaths) {
    if (Test-Path $TempPath) {
        $OldFiles = Get-ChildItem -Path $TempPath -File -Recurse -ErrorAction SilentlyContinue |
        Where-Object {$_.LastAccessTime -lt $ThresholdDate}

        if ($OldFiles) {
            $SizeBeforeCleanup = ($OldFiles | Measure-Object Length -Sum).Sum
            Write-Output "Found $($OldFiles.Count) old files in $TempPath"
            Write-Output "Total size: $([math]::Round($SizeBeforeCleanup/1MB, 2)) MB"

            # Uncomment the next line to actually delete files
            # $OldFiles | Remove-Item -Force -ErrorAction SilentlyContinue

            $TotalCleaned += $SizeBeforeCleanup
        }
    }
}

Write-Output "Total space that could be cleaned: $([math]::Round($TotalCleaned/1GB, 2)) GB"

This script identifies files older than 30 days in temporary directories and calculates potential space savings.

Best Practices and Performance Tips

  • When working with Get-ChildItem for file-only operations, always implement error handling using -ErrorAction SilentlyContinue to prevent script failures when encountering access denied errors.
  • Use specific paths rather than scanning entire drives to improve performance and reduce processing time.
  • For better performance, apply filters at the cmdlet level using parameters like -File, -Include, and -Filter rather than filtering through pipeline operations. When working with large datasets, consider using ForEach-Object for streaming processing instead of storing all results in memory.
  • Always test scripts in development environments before deploying to production, especially when performing file operations that could modify or delete data. Implement appropriate logging and validation to ensure script reliability in enterprise environments.

Conclusion

In this tutorial, I explained how to use the Get-ChildItem PowerShell cmdlet to get files only from a folder. We covered multiple methods, from the simple -File parameter to advanced filtering techniques using Where-Object and complex pipeline operations.

  • Use the -File parameter for PowerShell 3.0+ for simplicity.
  • Employ Where-Object filtering for complex conditions and older PowerShell versions.
  • Leverage the -Include parameter for extension-based filtering.
  • Always implement proper error handling with -ErrorAction
  • Consider performance implications when working with large directory structures.

You may also like:

Leave a Comment

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.