从另一个 powershell 脚本调用 powershell 脚本并保证它是 UTF8
Calling a powershell script from another powershell script and guaranteeing it is UTF8
我组装了一个 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++ 中正确打开,但在 ISE(我现在正在执行脚本的地方)中不能正确打开。
有什么方法可以确保脚本被正确读取?有必要支持UTF8,因为脚本可能需要执行操作,例如将AppSetting设置为包含特殊字符的值。
编辑:"vanilla" 非 ISE Powershell 调用的行为相同。
根据@lit 和@PetSerAI,BOM 是 Powershell 正常工作所必需的。
我的第一次尝试没有成功,所以我切换回非 BOM,但是,通过以下步骤,它奏效了:
使用 -ContentType "application/octet-stream;charset=utf-8"
执行 Invoke-WebRequest
抓取原始内容(您会在 Powershell 中看到它是一系列数字,我假设它是 ascii 代码?)并使用 [system.Text.Encoding]::UTF8.GetString($resp.RawContentStream.ToArray());
将其字节转换为包含的数组你想要的字符。
通过 .NET 的 WriteAllText 保存文件时,确保使用 UTF8,
[System.IO.File]::WriteAllText($newFile, $fileContents, [System.Text.Encoding]::UTF8)
。在这种情况下,UTF8被理解为带有字节顺序标记的UTF8 ,并且是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++ 中正确打开,但在 ISE(我现在正在执行脚本的地方)中不能正确打开。
有什么方法可以确保脚本被正确读取?有必要支持UTF8,因为脚本可能需要执行操作,例如将AppSetting设置为包含特殊字符的值。
编辑:"vanilla" 非 ISE Powershell 调用的行为相同。
根据@lit 和@PetSerAI,BOM 是 Powershell 正常工作所必需的。
我的第一次尝试没有成功,所以我切换回非 BOM,但是,通过以下步骤,它奏效了:
使用
-ContentType "application/octet-stream;charset=utf-8"
执行 Invoke-WebRequest
抓取原始内容(您会在 Powershell 中看到它是一系列数字,我假设它是 ascii 代码?)并使用
[system.Text.Encoding]::UTF8.GetString($resp.RawContentStream.ToArray());
将其字节转换为包含的数组你想要的字符。通过 .NET 的 WriteAllText 保存文件时,确保使用 UTF8,
[System.IO.File]::WriteAllText($newFile, $fileContents, [System.Text.Encoding]::UTF8)
。在这种情况下,UTF8被理解为带有字节顺序标记的UTF8 ,并且是Powershell所需要的。