如何在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
cator>>because they mess up UTF8-BOM encoding Set-Contentis inconsistent across PowerShell versions (no BOM by default in v6+, configuration-dependent in older versions)- Need to loop through
DIL_BG_TXN*.datfiles, 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 fromBOMMarker.txtis 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-ChildItemefficiently finds all files matching yourDIL_BG_TXN*.datpattern in the target directory. - Safe Extension Rename: Using
[System.IO.Path]::ChangeExtensionis 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
相关产品推荐
相关产品推荐

