You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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-ChildItem grabs all CSV files in your source directory. If you need to include subdirectories too, add the -Recurse flag to this command.
  • Dynamic Filenames: Uses Join-Path to safely build output paths (avoids messy string concatenation) and adds a mod_ 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:45:48