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

将CURL文件上传命令转为PowerShell Invoke-RestMethod遇错求助

问题描述

在PowerShell中使用curl.exe执行文件上传命令可正常工作,但转换为Invoke-RestMethod实现时,返回INVALID_ARGUMENT错误。

可正常运行的curl命令:

function curlPush() {
    $url = "$post_url/$dset_id/transactions/$trid"
    $header = "Authorization: Bearer $token"
    curl.exe --request POST --url $url --header $header -F file="@$folder_path"
}

报错的Invoke-RestMethod实现:

function pushFile() {
    $url = "$post_url/$dset_id/transactions/$trid"
    $header = @{
        'Authorization' = "Bearer $token"
        'Content-Type' = 'multipart/form-data'
    }
    $response = Invoke-RestMethod -Uri $url -header $header -Method POST -InFile $folder_path
    if (!$?) {
        Write-Host $_.ErrorDetails.Message
    }
    $response
}

错误信息:

Invoke-RestMethod : {"errorCode":"INVALID_ARGUMENT","errorName":"Default:InvalidArgument","errorInstanceId":"0bc80c74-35ae-4837-a87e-ff0e214b451b","parameters":{}}
At C:\Users\Documents\Software Projects\SolarWinds\PushFiles.ps1:42 char:17
+ ... $response = Invoke-RestMethod -Uri $url -header $header -Method POST  ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
解决思路与修正代码

问题根源有两点:

  1. 手动指定Content-Type: multipart/form-data时,未自动添加boundary分隔符,导致服务器无法解析表单数据
  2. -InFile仅直接发送文件内容,未模拟curl中-F file=@path的表单字段结构(将文件包装在名为file的表单项中)

修正后的代码:

function pushFile() {
    $url = "$post_url/$dset_id/transactions/$trid"
    $headers = @{
        'Authorization' = "Bearer $token"
    }
    # 创建对应表单字段的multipart数据
    $form = @{
        file = Get-Item -Path $folder_path
    }
    try {
        $response = Invoke-RestMethod -Uri $url -Headers $headers -Method POST -Form $form
        $response
    }
    catch {
        Write-Host $_.ErrorDetails.Message
    }
}
关键说明
  • 移除手动Content-Type设置:使用-Form参数时,PowerShell会自动生成带正确boundary的multipart/form-data请求头,确保服务器能解析表单内容
  • 用-Form替代-InFile:哈希表的键对应表单字段名(与curl的file字段一致),值为文件对象,完全模拟curl的表单上传逻辑
  • 改用try/catch捕获错误:相比$?和$_的组合,try/catch能更稳定地捕获并输出错误详情

内容的提问来源于stack exchange,提问作者Dr.YSG

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:45:46