Invoke-WebRequest服务模式下URI插入CR致请求失败求助
问题:PowerShell服务模式下Invoke-WebRequest因URI含换行符下载失败
现象详情
- 交互模式下,使用
Invoke-WebRequest下载Google Cloud Storage文件可正常执行,代码及请求日志如下:
$Ack = $Msg.ackId $BucketID = $Msg.message.attributes.bucketId $FullName = $Msg.message.attributes.ObjectId $MsgName = ($Msg.message.attributes.ObjectId -split "/", 5)[4] # split the name $ObjectID = [uri]::EscapeDataString($FullName) # convert " " in %20 and / in %2F $uribucket = "https://www.googleapis.com/download/storage/v1/b/{0}/o/{1}?alt=media" -f $BucketID, $ObjectID Invoke-WebRequest -uri $uribucket -Headers $Header -OutFile $WrkDir\$MsgName -Verbose
请求日志:
GET https://www.googleapis.com/download/storage/v1/b/bucket_name/o/blabla/REGIE/L216/WRK/myfile.docx?alt=media with 0-byte payload
- 服务模式下请求失败,疑似URI中被插入换行符(如
/L216/变为/L2\n16/),错误详情如下:
GET https://www.googleapis.com/download/storage/v1/b/bucket_name/o/blabla/REGIE/L2 16/WRK/myfile.docx?alt=media with 0-byte payload StatusCode: NotFound ErrorMessage: Not Found
注:使用curl.exe在交互和服务模式下均可正常运行,但需使用原生PowerShell命令解决。
解决方案
问题根源是$Msg.message.attributes.ObjectId中包含隐藏的换行/回车控制字符,服务模式下PowerShell未自动过滤这些字符,导致转义后的URI异常。通过以下步骤修复:
清理ObjectId中的控制字符:在获取
$FullName时,移除所有回车、换行符$FullName = $Msg.message.attributes.ObjectId -replace '[\r\n]', ''基于清理后的字符串处理文件名:拆分文件名时使用已清理的
$FullName,避免拆分结果异常$MsgName = ($FullName -split "/", 5)[4]保留原转义逻辑:继续使用
[uri]::EscapeDataString处理路径中的特殊字符,确保URI格式合规
完整修复后的代码:
$Ack = $Msg.ackId $BucketID = $Msg.message.attributes.bucketId $FullName = $Msg.message.attributes.ObjectId -replace '[\r\n]', '' # 清理换行/回车符 $MsgName = ($FullName -split "/", 5)[4] $ObjectID = [uri]::EscapeDataString($FullName) $uribucket = "https://www.googleapis.com/download/storage/v1/b/{0}/o/{1}?alt=media" -f $BucketID, $ObjectID Invoke-WebRequest -uri $uribucket -Headers $Header -OutFile $WrkDir\$MsgName -Verbose
内容的提问来源于stack exchange,提问作者Francois ARELLA
相关产品推荐
相关产品推荐

