You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell编码转换报错:无法转为System.Byte[],需解决俄文显示问题

解决PowerShell转换Windows-1251编码显示俄文字符的错误

错误原因

直接将字符串强制转换为[Byte[]]是错误的,.NET不允许这种类型转换,必须通过System.Text.Encoding类的方法来处理字符串与字节数组的转换。

修正后的代码

如果需要将字符串按Windows-1251编码处理以正确显示俄文字符,正确写法如下:

$result = 'Invoke-RestMethod -Method "Post" -Uri https://ntfy.sh/most -Body "Hello 123 Привет" -UseBasicParsing'

# 先把Unicode字符串转成Windows-1251字节数组,再解码回字符串
$rus_result = [System.Text.Encoding]::GetEncoding('windows-1251').GetString(
    [System.Text.Encoding]::GetEncoding('windows-1251').GetBytes($result)
)

# 输出处理后的结果
$rus_result

针对实际需求的优化

如果你的真实需求是调用Invoke-RestMethod时用Windows-1251编码发送请求体,不需要处理整个命令字符串,只需单独编码请求体即可:

$body = "Hello 123 Привет"
# 将请求体转换为Windows-1251编码的字节数组
$encodedBody = [System.Text.Encoding]::GetEncoding('windows-1251').GetBytes($body)

# 指定ContentType为Windows-1251发送请求
Invoke-RestMethod -Method "Post" -Uri https://ntfy.sh/most -Body $encodedBody -UseBasicParsing -ContentType "text/plain; charset=windows-1251"

错误信息翻译

原错误信息翻译为:

InvalidArgument: 无法将值"Invoke-RestMethod -Method "Post" -Uri https://ntfy.sh/most -Body "Hello 123 Привет" -UseBasicParsing" 转换为类型"System.Byte[]"。错误:"无法将值"Invoke-RestMethod -Method "Post" -Uri https://ntfy.sh/most -Body "Hello 123 Привет" -UseBasicParsing" 转换为类型"System.Byte"。错误:"输入字符串格式不正确。""

内容的提问来源于stack exchange,提问作者kiki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 14:45:38