gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:27:29 25 4
gpt4 key购买 nike

我编写了一个 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设置为包含特殊字符的值之类的操作。

编辑:“普通”非 ISE Powershell 调用的行为相同。

最佳答案

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

我的第一次尝试并不成功,因此我切换回非 BOM,但是通过以下步骤,它成功了:

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

  2. 获取原始内容(您将在 Powershell 中将其视为一系列数字,我假设它们是 ascii 代码?)并使用 [system.Text.Encoding]::UTF8 转换其字节.GetString($resp.RawContentStream.ToArray()); 到包含所需字符的数组。

  3. 通过 .NET 的 WriteAllText 保存文件时,请确保使用 UTF8,
    [System.IO.File]::WriteAllText($newFile, $fileContents, [System.Text.Encoding]::UTF8)
    。在本例中,UTF8 被理解为带有字节顺序标记的 UTF8,这正是 Powershell 所需要的。

关于powershell - 从另一个powershell脚本调用一个powershell脚本并保证它是UTF8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41383050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com