2016-01-21 59 views
1

我們的自動構建腳本也會對powershell腳本進行簽名。但是我們的一些powershell腳本沒有簽名。當我分析時,我們發現有一個已知的問題,Powershell ise保存的文件保存在Unicode BigEndian中,無法簽名。如何將Unicode BigEndian中的ps1文件更改爲ASCII?

因爲它是自動化的過程,所以如果一種方法檢查一個文件是否以Unicode大端存儲,那麼把它改爲ASCII就可以解決我們的問題。

在powershell有沒有辦法?

+0

的PowerShell ISE(在v3中驗證)創建_UTF-8_1文件_with BOM_(字節順序標記),而不是Big-Endian Unicode文件。物料清單可能是個問題,因爲物料清單的概念在技術上不適用於UTF-8,並且不鼓勵使用它,但在Windows平臺上,它用於將文件顯式標記爲UTF-8。 – mklement0

+2

請注意,如果您的源代碼包含非ASCII字符,它們將被文字'?'字符替換。用'Out-File -Encoding ASCII'保存。不幸的是,保存爲UTF-8文件是不平常的,因爲「Out-File」不支持它 - 參見http://stackoverflow.com/q/5596982/45375 – mklement0

回答

2

我發現了一個功能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 
} 
相關問題