如何用PowerShell的Import-Csv cmdlet处理目录下所有CSV文件
Batch Process CSV Files in a Directory with PowerShell
Got it, let's adjust your existing script to handle all CSV files in a specified directory instead of just one. Here's a robust, flexible solution with clear explanations:
Full Batch Processing Script
# Configure your paths first $sourceDirectory = "J:\consult evv" $outputDirectory = "C:\Users\CFOSTER\Desktop\stuff" # Make sure the output directory exists (no errors if it already does) if (-not (Test-Path -Path $outputDirectory)) { New-Item -ItemType Directory -Path $outputDirectory | Out-Null } # Loop through every CSV in the source directory Get-ChildItem -Path $sourceDirectory -Filter "*.csv" | ForEach-Object { # Create a unique output filename (adds "mod_" prefix to original name) $outputFilePath = Join-Path -Path $outputDirectory -ChildPath "mod_$($_.Name)" # Run your core processing logic on each file Import-Csv -Header (1..39) -Path $_.FullName | Select-Object '30', '31', '39' -Unique | Export-Csv -Path $outputFilePath -NoTypeInformation # Optional: Print progress to the console Write-Host "✅ Processed: $($_.Name) → Saved to: $outputFilePath" }
Key Improvements & Explanations
- Directory Safety: The script checks if your output directory exists and creates it if not—no more "path not found" errors mid-run.
- Batch Traversal:
Get-ChildItemgrabs all CSV files in your source directory. If you need to include subdirectories too, add the-Recurseflag to this command. - Dynamic Filenames: Uses
Join-Pathto safely build output paths (avoids messy string concatenation) and adds amod_prefix so you can easily distinguish processed files from originals. - Reusable Logic: Keeps your original core processing intact—we just wrapped it in a loop to handle multiple files seamlessly.
Optional Enhancements
Filter Specific Files
If you only want to process files starting with splitfile_ (like your original single file), update the Get-ChildItem filter:
Get-ChildItem -Path $sourceDirectory -Filter "splitfile_*.csv"
Error Handling
Add try/catch to prevent the script from stopping if one file fails to process:
Get-ChildItem -Path $sourceDirectory -Filter "*.csv" | ForEach-Object { $outputFilePath = Join-Path -Path $outputDirectory -ChildPath "mod_$($_.Name)" try { Import-Csv -Header (1..39) -Path $_.FullName | Select-Object '30', '31', '39' -Unique | Export-Csv -Path $outputFilePath -NoTypeInformation Write-Host "✅ Processed: $($_.Name)" } catch { Write-Warning "❌ Failed to process $($_.Name): $($_.Exception.Message)" } }
内容的提问来源于stack exchange,提问作者cfoster5
相关产品推荐
相关产品推荐

