从另一个PowerShell脚本调用powershell脚本并保证它是UTF8

时间:2016-12-29 15:56:35

标签: powershell azure encoding utf-8 azure-powershell

我组装了一个Powershell脚本,旨在获取Azure blob上托管的其他脚本,然后执行它们。

相关代码块:

获取脚本:

$resp = (Invoke-WebRequest -Uri $scriptUri -Method GET -ContentType "application/octet-stream;charset=utf-8")
$migrationScript = [system.Text.Encoding]::UTF8.GetString($resp.RawContentStream.ToArray());
$tempPath = Get-ScriptDirectory
$fileLocation = CreateTempFile $tempPath "migrationScript.ps1" $migrationScript

创建文件:

$newFile = "$tempFolder"+"\"+"$fileName"
Write-Host "Creating temporary file $newFile"
[System.IO.File]::WriteAllText($newFile, $fileContents)

然后我用

调用下载的文件
Invoke-Expression "& `"$fileLocation`" $migrationArgs"

这对我需要的东西很有效。但是,Invoke-Expression无法正确读取文件的编码。它在Notepad或Notepad ++中正确打开,但不在ISE中(我现在正在执行脚本)。

有没有办法可以确保正确读取脚本?有必要支持UTF8,因为脚本可能需要执行操作,例如将AppSetting设置为包含特殊字符的值。

编辑:" vanilla"上的行为是相同的。非ISE Powershell调用。

1 个答案:

答案 0 :(得分:0)

根据@lit和@PetSerAI,Powershell正常工作所需的BOM

我的第一次尝试没有成功,所以我切换回非BOM,但是,通过以下步骤,它有效:

  1. 使用-ContentType "application/octet-stream;charset=utf-8"

  2. 执行Invoke-WebRequest
  3. 获取原始内容(您将在Powershell中看到它作为一系列数字,我假设是ascii代码?)并将其字节[system.Text.Encoding]::UTF8.GetString($resp.RawContentStream.ToArray());转换为包含您想要的字符的数组

  4. 通过.NET的WriteAllText保存文件时,请确保使用UTF8 [System.IO.File]::WriteAllText($newFile, $fileContents, [System.Text.Encoding]::UTF8)。在这种情况下,UTF8被理解为带有字节顺序标记的UTF8 ,并且是Powershell需要的。