Excellent! Let's incorporate all three advanced features into a single, more powerful script.
This new version will be a "Swiss Army knife" for folder analysis. It asks the user for all the optional filters and then applies them to generate a customized report and a CSV file.
The Advanced PowerShell Script
This script includes:
- Prompts for optional filtering by file extension and modification date.
- Dynamic application of filters based on user input.
- Clear output that summarizes the active filters.
- A detailed CSV export with columns for Name, Folder, Size (in MB), and Last Modified Date.
<#
.SYNOPSIS
Analyzes a folder with advanced filtering to count files, calculate total size,
and save a detailed file list to a CSV file.
.DESCRIPTION
This script prompts the user for a folder path and offers optional filters for
file extension and modification date (last X days).
It then recursively scans the folder to:
1. Count the total number of files that match the criteria.
2. Calculate the combined size of those files and display it in Megabytes (MB).
3. Save a detailed list (Name, Folder, Size, Last Modified) of the matching
files to a new CSV file named 'FilteredFileList.csv' inside the specified folder.
.AUTHOR
Your Name / AI Assistant
#>
# Clear the screen for a clean start
Clear-Host
# --- 1. Ask for folder path and validate ---
$folderPath = Read-Host -Prompt "Please enter the full path to the folder you want to analyze"
if (-not (Test-Path -Path $folderPath -PathType Container)) {
Write-Host ""
Write-Error "Error: The path '$folderPath' does not exist or is not a folder. Please run the script again."
return
}
# --- 2. Ask for optional filters ---
Write-Host "" # Add a blank line for readability
$extensionFilter = Read-Host -Prompt "OPTIONAL: Enter an extension to filter by (e.g., jpg, txt). Leave blank for all extensions"
$daysFilter = Read-Host -Prompt "OPTIONAL: Only include files modified in the last X days. Leave blank for all dates"
# --- 3. Build and execute the file search ---
Write-Host ""
Write-Host "Analyzing folder: $folderPath"
Write-Host "------------------------------------------"
# Use a hashtable for splatting. This is a clean way to build a command with optional parameters.
$getChildItemParams = @{
Path = $folderPath
Recurse = $true
File = $true
ErrorAction = 'SilentlyContinue'
}
# Add the -Include parameter ONLY if the user provided an extension
if (-not ([string]::IsNullOrWhiteSpace($extensionFilter))) {
# Trim any leading '.' the user might have added and add the wildcard pattern
$formattedExtension = "*.$($extensionFilter.TrimStart('.'))"
$getChildItemParams['Include'] = $formattedExtension
Write-Host "Filtering for extension: $formattedExtension"
}
# Get the initial list of files using the parameters we just built
$files = Get-ChildItem @getChildItemParams
# --- 4. Apply the date filter (if provided) ---
# We do this after Get-ChildItem, as it's more efficient.
$cutoffDate = $null
if ($daysFilter -match '^\d+$') { # Ensure the input is a valid positive number
$cutoffDate = (Get-Date).AddDays(-[int]$daysFilter)
$files = $files | Where-Object { $_.LastWriteTime -gt $cutoffDate }
Write-Host "Filtering for files modified in the last $daysFilter days (after $($cutoffDate.ToString('yyyy-MM-dd')))"
}
# --- 5. Analyze and display results ---
Write-Host "------------------------------------------"
# Check if any files matched the criteria
if ($null -eq $files -or $files.Count -eq 0) {
Write-Warning "No files were found matching your criteria in the specified folder."
return
}
# Count the files
$fileCount = $files.Count
Write-Host "Total files found matching criteria: $fileCount"
# Calculate the total size in MB
$totalSizeInBytes = ($files | Measure-Object -Property Length -Sum).Sum
$totalSizeInMB = $totalSizeInBytes / 1MB
Write-Host "Total size of matching files: $($("{0:N2}" -f $totalSizeInMB)) MB"
# --- 6. Save the list of files to a new .CSV file ---
$outputFilePath = Join-Path -Path $folderPath -ChildPath "FilteredFileList.csv"
try {
# Select specific properties for a clean CSV. We also create a custom "Size(MB)" property.
$files | Select-Object Name, `
@{Name = "Folder"; Expression = { $_.DirectoryName }}, `
@{Name = "Size(MB)"; Expression = {[math]::Round(($_.Length / 1MB), 2)}}, `
LastWriteTime `
| Export-Csv -Path $outputFilePath -NoTypeInformation -Encoding UTF8
Write-Host "" # Add a blank line for readability
Write-Host "Successfully saved the detailed file list to:" -ForegroundColor Green
Write-Host $outputFilePath -ForegroundColor Green
}
catch {
Write-Host ""
Write-Error "Could not save the file list to '$outputFilePath'. Please check your permissions."
}
Write-Host "------------------------------------------"
Write-Host "Analysis complete."