【问题标题】:How to change the ps1 file in Unicode BigEndian to ASCII?如何将 Unicode BigEndian 中的 ps1 文件更改为 ASCII?
【发布时间】:2016-01-21 13:07:41
【问题描述】:

我们的自动构建脚本也会签署 powershell 脚本。但是我们的一些 powershell 脚本没有签名。当我分析时,我们发现有一个已知的陷阱,即 Powershell ise 保存的文件保存在无法签名的 Unicode BigEndian 中。

由于它是自动化过程,如果有一种方法可以检查文件是否以 Unicode 大端格式保存,然后将其更改为 ASCII 将解决我们的问题。

在powershell中有没有办法?

【问题讨论】:

  • PowerShell ISE(在 v3 中验证)创建 UTF-8 文件带有 BOM(字节顺序标记),而不是 Big-Endian Unicode 文件. BOM 可能是问题所在,因为 BOM 的概念在技术上不适用于 UTF-8,并且不鼓励使用,但在 Windows 平台上,它用于将文件显式标记为 UTF-8。
  • 请注意,如果您的源代码包含非 ASCII 字符,它们将被替换为文字 ? 字符。使用Out-File -Encoding ASCII 保存。不幸的是,没有 BOM 保存到 UTF-8 文件并非易事,因为 Out-File 不支持它 - 请参阅 stackoverflow.com/q/5596982/45375

标签: powershell ascii powershell-2.0 powershell-3.0


【解决方案1】:

我找到了一个获取文件编码的函数here

<#
.SYNOPSIS
Gets file encoding.
.DESCRIPTION
The Get-FileEncoding function determines encoding by looking at Byte Order Mark (BOM).
Based on port of C# code from http://www.west-wind.com/Weblog/posts/197245.aspx
.EXAMPLE
Get-ChildItem  *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'}
This command gets ps1 files in current directory where encoding is not ASCII
.EXAMPLE
Get-ChildItem  *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'} | foreach {(get-content $_.FullName) | set-content $_.FullName -Encoding ASCII}
Same as previous example but fixes encoding using set-content
#>
function Get-FileEncoding
{
    [CmdletBinding()] Param (
     [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [string]$Path
    )

    [byte[]]$byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $Path

    if ( $byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf )
    { Write-Output 'UTF8' }
    elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff)
    { Write-Output 'Unicode' }
    elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff)
    { Write-Output 'UTF32' }
    elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76)
    { Write-Output 'UTF7'}
    else
    { Write-Output 'ASCII' }
}

并使用this重新编码为ASCII:

If ((Get-FileEncoding -Path $file) -ine "ascii") {
    [System.Io.File]::ReadAllText($file) | Out-File -FilePath $file -Encoding Ascii
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-07
    • 2011-06-13
    • 1970-01-01
    • 2015-01-09
    • 2013-05-10
    • 2013-02-28
    • 1970-01-01
    • 2015-04-28
    相关资源
    最近更新 更多