PowerShell 5中Invoke-RestMethod的Form参数替代方案咨询
PowerShell 5兼容的FPR文件上传至SSC修改方案
问题说明
你提供的PowerShell 7代码中,Invoke-RestMethod的-Form参数是PowerShell 7及以上版本专属特性,PowerShell 5不支持该参数,因此运行时会触发报错。需要修改文件上传逻辑,手动构造multipart/form-data格式的请求来替代-Form参数的功能。
修改后的完整代码
Write-Host -ForegroundColor Green ("Scan completed!") `n #3. Export the scan to the FPR format $fprurl = 'http://' + $wiAPIurl + '/webinspect/scanner/scans/' + $scanId + '.fpr ' $path = $scanId + '.fpr' Write-Host ("Downloading the result file (fpr)...") Invoke-RestMethod -Credential $cred -Method GET -OutFile $path -uri "$fprurl" Write-Host -ForegroundColor Green ("Result file (fpr) download done!") `n #4. Upload the Results to SSC - PowerShell 5兼容版本 # 生成随机边界符,用于分隔表单内容 $boundary = [System.Guid]::NewGuid().ToString() # 读取FPR文件的二进制内容 $fileContent = [System.IO.File]::ReadAllBytes($path) # 构造multipart/form-data请求体 $bodyLines = @( "--$boundary", 'Content-Disposition: form-data; name="file"; filename="' + (Split-Path $path -Leaf) + '"', 'Content-Type: application/octet-stream', '', [System.Text.Encoding]::UTF8.GetString($fileContent), "--$boundary--", '' ) $body = [System.Text.Encoding]::UTF8.GetBytes($bodyLines -join "`r`n") # 设置请求头,注意Content-Type要包含边界符 $sscheaders = @{ "Authorization" = "FortifyToken $sscToken" "accept" = "application/json" "Content-Type" = "multipart/form-data; boundary=$boundary" } $sscuploadurl = $sscURL + 'api/v1/projectVersions/' + $applicationVersionID + '/artifacts' Write-Host ("Starting Upload to SSC...") Invoke-RestMethod -Uri $sscuploadurl -Method POST -Headers $sscheaders -Body $body Write-Host -ForegroundColor Green ("Finished! Scan Results are now available in the Software Security Center!")
关键修改点说明
- 简化请求头构造:直接用哈希表定义请求头,移除不必要的
Invoke-Expression调用,同时动态设置带边界符的Content-Type - 生成边界符:用GUID生成唯一的边界字符串,确保表单字段分隔逻辑正确
- 手动构造请求体:严格按照
multipart/form-data格式要求,拼接文件字段描述、文件内容和边界符,最终转换为字节数组 - 替换
-Form参数:通过-Body参数传入构造好的请求体,实现PowerShell 5环境下的文件上传功能
内容的提问来源于stack exchange,提问作者cekodis681 cekodis681
相关产品推荐
相关产品推荐

