I want to upload all .csv files from a C:/ to SharePoint. The script runs up to $Ctx.ExecuteQuery() and returns this error. I am able to run other PowerShell scripts on the site, and am the site owner, I suspect it is something other than access privileges.
Where do I start looking ?
Exception calling "ExecuteQuery" with "0" argument(s): "The remote server returned an error: (403) Forbidden." + $Ctx.ExecuteQuery() + ~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : WebException
Get-ChildItem "c:\users\xxx\downloads" -Filter *.csv | % {
$eachFile =Get-ChildItem "c:\users\xxxx\downloads\" -Filter *.csv
$eachFile | ForEach-Object{
#parameters
$SiteURL = "https://xxx.sharepoint.com/sites/nrg"
$LibraryName="Audit History"
$UserName = "[email protected]"
$Password = "xx"
$SecurePassword= $Password | ConvertTo-SecureString -AsPlainText -Force
#Setup the Context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
$Ctx.Credentials = $Credentials
#Get the Library
$Library = $Ctx.Web.Lists.GetByTitle($LibraryName)
#Get the file from disk
$FileStream = ([System.IO.FileInfo] (Get-Item $OutputFile)).OpenRead()
#Get File Name from source file path
$SourceFileName = Split-path $eachFile -leaf
#sharepoint online upload file powershell
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $SourceFileName
$FileUploaded = $Library.RootFolder.Files.Add($FileCreationInfo)
#powershell upload single file to sharepoint online
$Ctx.Load($FileUploaded)
$Ctx.ExecuteQuery()
#Close file stream
$FileStream.Close()
write-host "File has been uploaded!"
}
}
$eachFile
withForEach-Object{..}
, you need to change$SourceFileName = Split-path $eachFile -leaf
into$SourceFileName = Split-path $_ -leaf
. Also, variable$OutputFile
is never defined.. – Theo