0

Upload a document into sharepoint using invoke-webrequest works but comes back with an unhelpful error when overwrite=false is used

I have used postman to send the same request and get back a sharepoint exception error

<m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
    <m:code>-2130575257, Microsoft.SharePoint.SPException</m:code>
    <m:message xml:lang="en-US">A file with the name docs/a.txt already exists. It was last modified by [redacted] on 08 Aug 2019 15:23:02 +0100.</m:message>
</m:error>
try
{
 Invoke-webrequest -method post -uri $uri -infile $fullpath -headers $Headers -credential $credential
}
catch
{
    $errors = $_.exception
}

instead of getting the error that is in postman I get "The remote server returned an error: (400) Bad Request."

Theo
  • 57,719
  • 8
  • 24
  • 41

1 Answers1

0

I got around this by following the parserror function suggested here

How to get Powershell Invoke-Restmethod to return body of http 500 code response

function ParseErrorForResponseBody($Error) {
    if ($PSVersionTable.PSVersion.Major -lt 6) {
        if ($Error.Exception.Response) {  
            $Reader = New-Object System.IO.StreamReader($Error.Exception.Response.GetResponseStream())
            $Reader.BaseStream.Position = 0
            $Reader.DiscardBufferedData()
            $ResponseBody = $Reader.ReadToEnd()
            if ($ResponseBody.StartsWith('{')) {
                $ResponseBody = $ResponseBody | ConvertFrom-Json
            }
            return $ResponseBody
        }
    }
    else {
        return $Error.ErrorDetails.Message
    }
}

try
{
 Invoke-restmethod -method post -uri $uri -infile $fullpath -headers $Headers -credential $credential
}
catch
{
    ParseErrorForResponseBody($_)
}