PowerShell v7发送含希腊字符SMS乱码(显示问号)求助
解决PowerShell v7发送含希腊字符SMS显示问号的问题
问题场景
使用以下PowerShell代码发送含希腊字符的SMS时,接收端的希腊字符全部显示为问号:
$message = "testing greek characters ΓΔΘΞΦΨΩ" $senderId = "smsto1" $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $headers.Add("Authorization", "Bearer $apikey") $headers.Add("Content-Type", "application/json; charset=utf-8") $body = "{`n`"message`": `"$message"`,n`"to`": `"+357$clientPhone"`,n`"sender_id`": `"$senderId"`,n`"encoding`": `"unicode"`n}" $response = Invoke-RestMethod 'https://api.sms.to/sms/send' -Method 'POST' -Headers $headers -Body $body $response | ConvertTo-Json
接收端显示效果:
testing greek characters ???????
尝试修改encoding参数为UTF-8、ISO 8859-7、unicode均无效。
解决方案
问题根源是手动拼接JSON字符串导致Unicode字符编码丢失,改用PowerShell的对象转JSON功能即可解决:
修改后的完整代码
$message = "testing greek characters ΓΔΘΞΦΨΩ" $senderId = "smsto1" $apikey = "你的API密钥" $clientPhone = "目标手机号" # 构造请求体对象,避免手动拼接字符串 $requestBody = @{ message = $message to = "+357$clientPhone" sender_id = $senderId encoding = "unicode" # 保持API要求的Unicode编码标识 } # 自动转换为标准JSON字符串,确保Unicode字符正确编码 $jsonBody = $requestBody | ConvertTo-Json # 简化Headers定义 $headers = @{ Authorization = "Bearer $apikey" "Content-Type" = "application/json; charset=utf-8" } # 发送请求 $response = Invoke-RestMethod 'https://api.sms.to/sms/send' -Method POST -Headers $headers -Body $jsonBody $response | ConvertTo-Json
关键说明
- 避免手动拼接JSON:手动拼接字符串时,PowerShell的字符串插值可能破坏Unicode字符的正确编码,
ConvertTo-Json会自动处理Unicode字符的转义或编码,生成符合标准的JSON内容。 - 保留
encoding="unicode"参数:SMS API的unicode参数对应GSM标准的UCS-2编码,是发送非ASCII字符(如希腊文)的正确配置,之前的问题并非该参数错误,而是JSON构造环节的编码丢失。 - 简化Headers定义:使用PowerShell哈希表替代
System.Collections.Generic.Dictionary,语法更简洁且功能一致。
内容的提问来源于stack exchange,提问作者aristosv
相关产品推荐
相关产品推荐

