我有一个供应商每月发送 5-10 个文件。最近他们开始向我们发送 Windows 格式文件和 Unix 格式文件的混合体。众所周知,这个供应商很难合作,所以我自己可以更快地解决这个问题。
我有一个简短的 Powershell 7 脚本,适用于 Unix 文件,但会对 Windows 文件造成严重破坏:
$Files = Get-ChildItem '\\XD1\Vendor_Incoming\*.csv'
foreach($file in $Files){
(Get-Content -Raw -Path $file) -replace "`n","`r`n" | Set-Content -NoNewline -Path $file
}
在搜索了SO和一般的谷歌搜索之后,我还没有找到一种有效的方法来测试foreach语句中每个文件的文件格式,例如:
foreach($f in $Files){ If(thisfileisUnix){Process-File} }
感谢您的宝贵时间。
务实的解决方案:
Get-ChildItem '\\XD1\Vendor_Incoming\*.csv' |
ForEach-Object {
$original = $_ | Get-Content -Raw
$modified = $original -replace '(?<!\r)\n', "`r`n"
if (-not [object]::ReferenceEquals($original, $modified)) {
Set-Content $_.FullName -Value $modified
}
}