Guest User

Untitled

a guest
Apr 26th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. function Remove-Utf8Bom {
  2. <#
  3. .SYNOPSIS
  4. Removes a UTF8 BOM from a file.
  5. .DESCRIPTION
  6. Removes a UTF8 BOM from a file if the BOM appears to be present.
  7.  
  8. The UTF8 BOM is identified by the byte sequence 0xEF 0xBB 0xBF at the beginning of the file.
  9. .EXAMPLE
  10. Remove-Utf8Bom -Path c:\file.txt
  11.  
  12. Remove a BOM from a single file.
  13. .EXAMPLE
  14. Get-ChildItem c:\folder -Recurse -File | Remove-Utf8Bom
  15.  
  16. Remove the BOM from every file returned by Get-ChildItem.
  17. #>
  18.  
  19. [CmdletBinding()]
  20. param (
  21. # The path to a file which should be updated.
  22. [Parameter(Mandatory, Position = 1, ValueFromPipeline, ValueFromPipelineByPropertyName)]
  23. [ValidateScript( { Test-Path $_ -PathType Leaf } )]
  24. [Alias('FullName')]
  25. [String]$Path
  26. )
  27.  
  28. begin {
  29. $encoding = [System.Text.UTF8Encoding]::new($false)
  30. }
  31.  
  32. process {
  33. $Path = $pscmdlet.GetUnresolvedProviderPathFromPSPath($Path)
  34.  
  35. try {
  36. $bom = [Byte[]]::new(3)
  37. $stream = [System.IO.File]::OpenRead($Path)
  38. $null = $stream.Read($bom, 0, 3)
  39. $stream.Close()
  40.  
  41. if ([BitConverter]::ToString($bom, 0) -eq 'EF-BB-BF') {
  42. [System.IO.File]::WriteAllLines(
  43. $Path,
  44. [System.IO.File]::ReadAllLines($Path),
  45. $encoding
  46. )
  47. } else {
  48. Write-Verbose ('A UTF8 BOM was not detected on the file {0}' -f $Path)
  49. }
  50. } catch {
  51. Write-Error -ErrorRecord $_
  52. }
  53. }
  54. }
Add Comment
Please, Sign In to add comment