Advertisement
Old-Lost

Remove-UTF8BOMEncoding

Jul 14th, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function Remove-UTF8BOMEncoding {
  2.     [CmdletBinding()]
  3.     Param (
  4.         [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)][Alias('PSPath')][string] $Path
  5.     )
  6.     begin {
  7.         $utf8NoBomEncoding = New-Object System.Text.UTF8Encoding($False)
  8.     }
  9.     process {
  10.         foreach ($p in $Path) {
  11.             Try {
  12.                 [System.IO.FileInfo] $file = Get-Item -Path $p
  13.                 $sequenceBOM = New-Object System.Byte[] 3
  14.                 $reader = $file.OpenRead()
  15.                 $bytesRead = $reader.Read($sequenceBOM, 0, 3)
  16.                 $reader.Dispose()
  17.                 #A UTF-8+BOM string will start with the three following bytes. Hex: 0xEF0xBB0xBF, Decimal: 239 187 191
  18.                 if ($bytesRead -eq 3 -and $sequenceBOM[0] -eq 239 -and $sequenceBOM[1] -eq 187 -and $sequenceBOM[2] -eq 191) {
  19.                     [System.IO.File]::WriteAllLines($file.FullName, (Get-Content $file.FullName), $utf8NoBomEncoding)
  20.                     Write-Verbose "Remove UTF-8 BOM successfully from $($file.PSChildName)"
  21.                 }
  22.             } Catch [Exception] {
  23.                 Write-Error $_.Exception.ToString()
  24.             }
  25.         }
  26.     }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement