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

如何在PowerShell脚本中用copy /b批量给指定文件加BOM并改扩展名

Great question, and I totally get why the standard solutions aren't working for you—those encoding and cross-version compatibility issues are tricky. Here's a solid, reliable solution that meets all your requirements:

First, let's recap the key constraints we need to work around:

  • Can't use cat or >> because they mess up UTF8-BOM encoding
  • Set-Content is inconsistent across PowerShell versions (no BOM by default in v6+, configuration-dependent in older versions)
  • Need to loop through DIL_BG_TXN*.dat files, prepend the BOM marker, and output to matching .txt files

Solution Script

This PowerShell script uses binary copy to preserve encoding integrity, handles file traversal, and renames outputs correctly:

# Set your target directory here (update to your actual path)
$targetDirectory = "C:\Your\File\Directory"

# Get all .dat files matching the specified pattern
$datFiles = Get-ChildItem -Path $targetDirectory -Filter "DIL_BG_TXN*.dat" -File

# Path to your BOM marker file (adjust if it's stored elsewhere)
$bomMarkerPath = Join-Path -Path $targetDirectory -ChildPath "BOMMarker.txt"

# Process each matched file
foreach ($file in $datFiles) {
    # Create output filename by replacing .dat extension with .txt
    $outputFilePath = [System.IO.Path]::ChangeExtension($file.FullName, ".txt")
    
    # Execute binary copy to prepend the BOM marker to the .dat file
    copy /b "$bomMarkerPath"+"$($file.FullName)" "$outputFilePath"
    
    # Optional: Print progress message
    Write-Host "Processed: $($file.Name) -> $([System.IO.Path]::GetFileName($outputFilePath))"
}

Why This Works

  • Binary Copy (copy /b): This command concatenates raw bytes, so the UTF8-BOM from BOMMarker.txt is added correctly without altering the original .dat file's content or encoding. It works consistently across all PowerShell versions, no configuration dependencies.
  • Pattern-Based Traversal: Get-ChildItem efficiently finds all files matching your DIL_BG_TXN*.dat pattern in the target directory.
  • Safe Extension Rename: Using [System.IO.Path]::ChangeExtension is a robust way to swap extensions without error-prone manual string edits.

To clarify why this isn't a duplicate question:

  • Most related answers don't combine pattern-based file traversal with binary concatenation and extension renaming
  • They often rely on text-based commands that break UTF8-BOM encoding requirements
  • None account for the cross-version PowerShell compatibility you need

内容的提问来源于stack exchange,提问作者rmcsharry

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:26:44