# 把 .bat/.cmd 的行尾统一为 CRLF —— cmd.exe 必须用 CRLF, 裸 LF 会让它误解析。 # 症状: `if not defined X (` 被拆成 `'ned' 不是内部或外部命令` 之类的乱码报错。 # 触发场景: 用工具/编辑器写 .bat 时默认写成 LF (本项目踩过)。 # # 幂等: 已是 CRLF 的文件不会被改动。 # 用法: # powershell -NoProfile -ExecutionPolicy Bypass -File tools\fix-lineend.ps1 # 处理项目根 + tools 下全部 .bat/.cmd # powershell ... -File tools\fix-lineend.ps1 -Files "a.bat","b.cmd" # 只处理指定文件 param([string[]]$Files) if (-not $Files) { $root = Split-Path $PSScriptRoot -Parent $Files = @() $Files += Get-ChildItem (Join-Path $root '*.bat') -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName } $Files += Get-ChildItem (Join-Path $root '*.cmd') -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName } $Files += Get-ChildItem (Join-Path $PSScriptRoot '*.bat') -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName } $Files += Get-ChildItem (Join-Path $PSScriptRoot '*.cmd') -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName } } foreach ($f in $Files) { if (-not (Test-Path $f)) { Write-Output ("跳过(不存在): " + $f); continue } $bytes = [System.IO.File]::ReadAllBytes($f) # 统一成 CRLF: 先把 CRLF 归一为 LF, 再把 LF 展开为 CRLF $text = [System.Text.Encoding]::UTF8.GetString($bytes) $text = $text -replace "`r`n", "`n" $text = $text -replace "`r", "`n" $new = $text -replace "`n", "`r`n" if ($new -eq [System.Text.Encoding]::UTF8.GetString($bytes)) { Write-Output ("已是 CRLF: " + (Split-Path $f -Leaf)) } else { # 不加 BOM (cmd 对 BOM 敏感, 且 .bat 无需 BOM) $enc = New-Object System.Text.UTF8Encoding($false) [System.IO.File]::WriteAllText($f, $new, $enc) Write-Output ("已修正为 CRLF: " + (Split-Path $f -Leaf)) } }