Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function Remove-Utf8Bom {
- <#
- .SYNOPSIS
- Removes a UTF8 BOM from a file.
- .DESCRIPTION
- Removes a UTF8 BOM from a file if the BOM appears to be present.
- The UTF8 BOM is identified by the byte sequence 0xEF 0xBB 0xBF at the beginning of the file.
- .EXAMPLE
- Remove-Utf8Bom -Path c:\file.txt
- Remove a BOM from a single file.
- .EXAMPLE
- Get-ChildItem c:\folder -Recurse -File | Remove-Utf8Bom
- Remove the BOM from every file returned by Get-ChildItem.
- #>
- [CmdletBinding()]
- param (
- # The path to a file which should be updated.
- [Parameter(Mandatory, Position = 1, ValueFromPipeline, ValueFromPipelineByPropertyName)]
- [ValidateScript( { Test-Path $_ -PathType Leaf } )]
- [Alias('FullName')]
- [String]$Path
- )
- begin {
- $encoding = [System.Text.UTF8Encoding]::new($false)
- }
- process {
- $Path = $pscmdlet.GetUnresolvedProviderPathFromPSPath($Path)
- try {
- $bom = [Byte[]]::new(3)
- $stream = [System.IO.File]::OpenRead($Path)
- $null = $stream.Read($bom, 0, 3)
- $stream.Close()
- if ([BitConverter]::ToString($bom, 0) -eq 'EF-BB-BF') {
- [System.IO.File]::WriteAllLines(
- $Path,
- [System.IO.File]::ReadAllLines($Path),
- $encoding
- )
- } else {
- Write-Verbose ('A UTF8 BOM was not detected on the file {0}' -f $Path)
- }
- } catch {
- Write-Error -ErrorRecord $_
- }
- }
- }
Add Comment
Please, Sign In to add comment