Certainly! I'd be happy to help enhance your Copy-FilesContent function. Below, I've made several improvements to the script:
-
Use continue Instead of return in Loops: In your ForEach-Object loop, using return exits the entire function whenever a condition is met, which likely isn't the intended behavior. Replacing return with continue ensures the loop skips to the next item without exiting the function.
-
Simplify Exclusion Logic: Consolidated exclusion patterns and used -notmatch or -notlike operators to improve readability and maintainability.
-
Add Parameter Validation: Included checks to ensure the provided directory exists and that the output file can be created.
-
Improve Logging and Error Handling: Used Write-Verbose, Write-Warning, and Write-Error for better logging practices. Added the [CmdletBinding()] attribute to support common parameters like -Verbose.
-
Make Include/Exclude Lists Configurable: Added parameters to allow customization of included extensions and excluded patterns.
-
Optimized File Retrieval: Used the -File parameter with Get-ChildItem to ensure only files are processed.
Here's the enhanced version of your function:
function Copy-FilesContent {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Directory,
[Parameter(Mandatory = $true)]
[string]$OutputFile,
[string[]]$IncludeExtensions = @(".tsx", ".js", ".ts", ".config.mjs", ".json", ".alo"),
[string[]]$ExcludePatterns = @("*.ico", "*.jpg", "*.jpeg", "*.png", "*.svg", "*.bmp", "*.gif", "*.db", "*.gz", "*node_modules*", "*settings.json", "*.next*", "*ssr*", "*vendor-chunks*", "*next.config.js", "*package-lock.json")
)
# Check if the directory exists
if (-not (Test-Path -Path $Directory)) {
Write-Error "The directory '$Directory' does not exist."
return
}
# Clear and create the output file
try {
if (Test-Path -Path $OutputFile) {
Remove-Item -Path $OutputFile -Force
}
New-Item -Path $OutputFile -ItemType File -Force | Out-Null
}
catch {
Write-Error "Error preparing the output file '$OutputFile': $($_.Exception.Message)"
return
}
# Include specific files first
$specialFiles = @("package.json", "tsconfig.json", ".eslintrc.json")
foreach ($specialFile in $specialFiles) {
$specialFilePath = Join-Path -Path $Directory -ChildPath $specialFile
if (Test-Path -Path $specialFilePath) {
Add-Content -Path $OutputFile -Value "`n`n// $specialFilePath"
try {
$specialFileContent = Get-Content -Path $specialFilePath -Raw
Add-Content -Path $OutputFile -Value $specialFileContent
}
catch {
Write-Warning "Error reading '$specialFilePath': $($_.Exception.Message)"
}
} else {
Write-Verbose "Special file '$specialFilePath' not found."
}
}
# Process files recursively
Get-ChildItem -Path $Directory -Recurse -File | ForEach-Object {
$file = $_.FullName
# Check if the file matches any exclude patterns
foreach ($pattern in $ExcludePatterns) {
if ($file -like $pattern) {
Write-Verbose "Skipping file: $file (excluded by pattern '$pattern')"
continue 2 # Skip to the next file
}
}
# Check if the file extension is in the include list
if ($IncludeExtensions -contains $_.Extension.ToLower()) {
try {
Add-Content -Path $OutputFile -Value "`n`n// $file"
$fileContent = Get-Content -Path $file -Raw
Add-Content -Path $OutputFile -Value $fileContent
}
catch {
Write-Warning "Error processing '$file': $($_.Exception.Message)"
continue
}
} else {
Write-Verbose "Skipping file: $file (extension not included)"
}
}
Write-Output "Text files content copied to '$OutputFile'"
}
# Main script
$outputFile = "output.txt"
Copy-FilesContent -Directory "." -OutputFile $outputFile -Verbose
Explanation of Enhancements:
-
Use of continue: Replaced return with continue inside loops to avoid prematurely exiting the entire function when skipping files.
-
Parameter Validation: Added checks to ensure the directory exists before proceeding and that the output file can be prepared.
-
Configurable Include/Exclude Patterns: Added $IncludeExtensions and $ExcludePatterns parameters, allowing you to modify which files are included or excluded without changing the function code.
-
Improved Logging: Utilized Write-Verbose, Write-Warning, and Write-Error for better logging practices. Now, you can run the script with the -Verbose flag to see detailed output.
-
Optimized File Selection: Used Get-ChildItem with the -File parameter to ensure only files are processed, which can improve performance and prevent unnecessary processing of directories.
-
Error Handling: Wrapped file reading and writing operations in try-catch blocks to handle exceptions gracefully and continue processing other files.
Usage:
To run the enhanced script, simply execute it in your PowerShell environment:
$outputFile = "output.txt"
Copy-FilesContent -Directory "." -OutputFile $outputFile -Verbose
The -Verbose flag is optional but recommended if you want to see detailed processing information.
Customizing Include/Exclude Patterns:
You can customize which file extensions to include or which patterns to exclude by providing arrays to the -IncludeExtensions and -ExcludePatterns parameters:
Copy-FilesContent -Directory "." -OutputFile $outputFile -IncludeExtensions @(".txt", ".md") -ExcludePatterns @("*.log", "*temp*") -Verbose
Notes:
-
Special Files: The script still processes package.json, tsconfig.json, and .eslintrc.json first, if they exist in the root directory. You can modify the $specialFiles array within the function to include other files if needed.
-
Line Filtering: If you need to filter out specific lines within files (e.g., lines containing certain keywords), you can add filtering logic within the file processing try block.
Conclusion:
This enhanced function offers better flexibility, error handling, and logging, making it more robust for various use cases. Feel free to modify the function further to suit your specific needs.
Let me know if you have any questions or need additional assistance!