Upload Files to Sharepoint Library using an Application via PowerShell

Copper Contributor

Help please,

I have the below script, which has been cobbled together from various elements of googling and AI.


$siteUrl = "https://mydomainname.sharepoint.com/sites/Software"
$libraryName = "Shared Documents"
$filePath = "C:\temp\test.txt"
$appId = "myappid"
$tenantId = "mytenantid"
$clientSecret = "mysecretkey"


# Acquire Token
$tokenEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/token"
$tokenBody = @{
grant_type = "client_credentials"
client_id = $appId
client_secret = $clientSecret
resource = "https://graph.microsoft.com"
$tokenResponse = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -Body $tokenBody

$subfolder = "Calls"
$fileEndpoint = "$siteUrl/_api/web/lists/getbytitle('$libraryName')/RootFolder/SubFolders('$subfolder')/Files/Add(url='$(Split-Path $filePath -Leaf)')"

# Upload File
$headers = @{
Authorization = "Bearer $($tokenResponse.access_token)"
}##$fileEndpoint = "$siteUrl/_api/web/lists/getbytitle('$libraryName')/RootFolder/Files/Add(url='$(Split-Path $filePath -Leaf)')"
Invoke-RestMethod -Uri $fileEndpoint -Headers $headers -Method Post -InFile $filePath -ContentType "application/octet-stream"


From what I can see I am authorising successfully with the appid, secret and tenantid and I get a bearer token back from 365.  I have assigned Application permissions to SharePoint for my app and consented at the admin level.  


When I run the script I get the following error


Invoke-RestMethod : {"error_description":"Exception of type
'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown."}
At line:1 char:1
+ Invoke-RestMethod -Uri $fileEndpoint -Headers $headers -Method Post - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand


Can anyone help in pointing me in the right direction on this?  I maybe totally off mark as I'm not an advanced coder.  My aim is to have a script running on a VM which will automatically start and have a scheduled task running a PowerShell script which can authenticate to 365, run reports and then upload these automatically to a SharePoint site.  I have tried so many options but each method keeps generating an error. I have spent several days on this and I'm no further on.  I'm hoping this is possible and that someone can offer my some help.





0 Replies