Trying to upload files to subfolder in Sharepoint Online via Powershell - powershell

I am new to Powershell and I am trying to upload files from a local folder into Sharepoint online. I seem to get the files into the library, but not into the second subfolder where i want them.
Script so far:
#Specify tenant admin and site URL
$User = "admin#contoso.no"
$SiteURL = "https://contoso.sharepoint.com"
$Folder = "E:\LocalFolder"
$DocLibName = "Libraryname"
$FolderName = "Folder/SubFolder"
#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
$Password = "password" | ConvertTo-SecureString -AsPlainText -Force
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds
#Retrieve list
$List = $Context.Web.Lists.GetByTitle($DocLibName)
$Context.Load($List)
$Context.ExecuteQuery()
#Retrieve folder
$FolderToBindTo = $List.RootFolder.Folders
$Context.Load($FolderToBindTo)
$Context.ExecuteQuery()
$FolderToUpload = $FolderToBindTo | Where {$_.Name -eq $FolderName}
#Upload file
Foreach ($File in (dir $Folder -File))
{
$FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $File
$Upload = $FolderToUpload.Files.Add($FileCreationInfo)
$Context.Load($Upload)
$Context.ExecuteQuery()
}
If I use &FolderName = "Folder" the script runs fine. But what do i do to get the files into a subfolder? If I set a filepath as FolderName it does not work. I get the following errors:
You cannot call a method on a null-valued expression.
+ $Upload = $FolderToUpload.Files.Add($FileCreationInfo)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Cannot find an overload for "Load" and the argument count: "1".
+ $Context.Load($Upload)
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
enter code here
Been stuck on this for days :(

The error You cannot call a method on a null-valued expression. occurs since the $FolderToUpload object is not getting initialized at line:
$FolderToUpload = $FolderToBindTo | Where {$_.Name -eq $FolderName}
when $FolderName object points to sub folder name
The point is that $List.RootFolder.Folders returns only a folders located one level beneath under list or library, hence sub folder could not be referenced this way.
Instead you could consider the following options to reference a sub folder to add a file.
Using FileCreationInformation.Url property
Use FileCreationInformation.Url property to specify the folder url for a uploaded file.
#Retrieve list
$List = $Context.Web.Lists.GetByTitle($DocLibName)
$Context.Load($List.RootFolder)
$Context.ExecuteQuery()
#Upload file(s)
Foreach ($File in (dir $Folder -File))
{
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.Content = [System.IO.File]::ReadAllBytes($File.FullName)
$FileCreationInfo.URL = $List.RootFolder.ServerRelativeUrl + "/" + $FolderName + "/" + $File.Name
$UploadFile = $List.RootFolder.Files.Add($FileCreationInfo)
$Context.Load($UploadFile)
$Context.ExecuteQuery()
}
Using Web.GetFolderByServerRelativeUrl method
Use Web.GetFolderByServerRelativeUrl method to retrieve a folder where file have to be uploaded:
#Retrieve list
$List = $Context.Web.Lists.GetByTitle($DocLibName)
$Context.Load($List.RootFolder)
$Context.ExecuteQuery()
$TargetFolder = $Context.Web.GetFolderByServerRelativeUrl($List.RootFolder.ServerRelativeUrl + "/" + $FolderName);
#Upload file(s)
Foreach ($File in (dir $Folder -File))
{
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.Content = [System.IO.File]::ReadAllBytes($File.FullName)
$FileCreationInfo.URL = $File.Name
$UploadFile = $TargetFolder.Files.Add($FileCreationInfo)
$Context.Load($UploadFile)
$Context.ExecuteQuery()
}

You can also use the Office 365 Import service to bulk upload files to sharepoint online instead of using CSOM scripts.
This uses the new Sharepoint API which provides much faster speeds without any throttling as it uses scalable azure infrastructure.
https://support.office.com/en-us/article/Use-network-upload-to-import-SharePoint-data-to-Office-365-ed4a43b7-c4e3-45c8-94c8-998153407b8a

Related

powershell download file from Get-PnPListItem

Im new to scripting and powershell so bare with me.
My goal is to connect to Sharepoint online, and download the latest file uploaded to the a specific site.
Currently I am able to Connect to Sharepoint with Connect-PnPonline, then i use PnPListItem to query the file i need, but i am stuck at the last step to download the file.
here is my code:
cls
$SPOsite="https://example.sharepoint.com/sites/example"
$TargetFile="C:\example"
Connect-PnPOnline -Url $SPOsite -ClientId xxxxx-xxxxx-xxxxx-xxxx -ClientSecret secretsecret112233
$ListItems = Get-PnPListItem -List Documents | select -last 1
$ctx= Get-PnPContext
foreach ($item in $ListItems)
{
$file = $item.file
$fileversions = $file.Versions
$ctx.load($file)
$ctx.load($fileversions)
$ctx.ExecuteQuery()
Write-Host $file.Name,$fileversions.VersionLabel
}
Get-PnPFile -Url "https://example.sharepoint.com/sites/example" -Filename $ListItems -Path $TargetFile -AsFile
Error message that i get is
Get-PnPFile : File Not Found.
At \\cifs-share.example.org\Usershome\user\Desktop\PowerShell\dwnldSPfiles.ps1:20 char:1
+ Get-PnPFile -Url "https://example.sharepoint.com/sites/example" -Fi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (:) [Get-PnPFile], ServerException
+ FullyQualifiedErrorId : EXCEPTION,PnP.PowerShell.Commands.Files.GetFile
Try this:
$SharePointFolderPath = "Shared Documents"
$Files = Get-PnPFolderItem -FolderSiteRelativeUrl $SharePointFolderPath -ItemType File
foreach($File in $Files) {
if($File.Name -eq "file name"){
Get-PnPFile -Url $File.ServerRelativeUrl -Path c:\Temp -FileName $File.Name -AsFile
}
}
Url should be the ServerRelativeUrl to the file which you want to download.

Uploading 2 files with same name to FTP using powershell script

I am a beginner at powershell script and I am stuck
I am trying to upload 2 xml files with the same name to FTP, but I am getting the following error
Exception calling "UploadFile" with "2" argument(s): "An
exception occurred during a WebClient request." At
C:\powershell\ExternalWidgets\upload-to-ftp.ps1:51 char:16
+ $webclient.UploadFile($uri.AbsoluteUri, $LocalPath)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException`
Here is the script:
#SET CREDENTIALS
$credentials = new-object System.Net.NetworkCredential($user, $pass)
cd $target
$DirectoryContent = Get-ChildItem -Directory
foreach($item in $DirectoryContent){
cd $item
$currentFolderItems = Get-ChildItem
foreach( $subfolderItem in $currentFolderItems)
{
if ($subfolderItem.name -eq "package.json") {
$subItem = Get-ChildItem -Directory
foreach($subItem in $subItem)
{
if ($subItem.name -eq "coverage") {
$files = Get-ChildItem -Path $subItem
$n = 0
foreach ($file in $files)
{
#rename coverage file
if($file.Name -eq "cobertura-coverage.xml") {
$newFileName=$file.Name.Replace("cobertura-coverage.xml","cobertura-coverage$n.xml")
Rename-Item $file -NewName $newFileName
$newFileName
}
$n++
}
}
}
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object
System.Net.NetworkCredential($user,$pass)
$uri = New-Object System.Uri($ftp + "/" + $folder)
#Delete files from FTP
# $fileUploaded =($uri + "\" + $newFileName)
# $fileUploaded
# Remove-Item $fileUploaded
$LocalPath =($target + "\" + $item + "\" + "coverage" + "\" +
$newFileName).Replace(".\", "").Replace('\', '/')
$webclient.UploadFile($uri, $LocalPath)
#cd..
}
}
cd ..
}
I also get an error when I want to rename one of the files. What step am I missing? Thank you

Powershell script errors first time but works on second attempt

I have a powershell script that searches for xls files and converts them to xlsx. Every time I run it for the first time I will get the error
Unable to find type [Microsoft.Office.Interop.Excel.XlFileFormat].
At C:\Users\wpauling\Documents\Quarter Report Scripts\convert.ps1:2 char:18
+ ... xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpen ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Offic...el.XlFileFormat:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
However the second time I run it everything works as expected, what is the problem I am going nuts. Here is my script
#Converts xls into xlsx
$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpenXMLWorkbook
write-host $xlFixedFormat
$excel = New-Object -ComObject excel.application
$excel.visible = $false
$folderpath = "C:\Users\user1\Documents\Q4"
$filetype ="*xls"
Get-ChildItem -Path $folderpath -Include $filetype -recurse |
ForEach-Object `
{
$path = ($_.fullname).substring(0, ($_.FullName).lastindexOf("."))
"Converting $path"
$workbook = $excel.workbooks.open($_.fullname)
$path += ".xlsx"
$workbook.saveas($path, $xlFixedFormat)
$workbook.close()
remove-item $_.fullname
}
$excel.Quit()
$excel = $null
[gc]::collect()
[gc]::WaitForPendingFinalizers()
Start the script with the line
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
Hope that helps.
p.s. Much less descriptive of course, but you can also use the numeric enum value 51 for the variable and not use the Add-Type.
See: XlFileFormat enumeration

PowerShell script return "The remote server returned an error: (401) Unauthorized"

I want to download all files from Share point and found a useful resource: https://social.technet.microsoft.com/Forums/en-US/7b8a27f9-ae0e-443e-a4a4-8c1cb2ee3429/downloading-files-in-sharepoint-online-powershell?forum=sharepointdevelopment, followed steps
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
$userName = "myemail#web.com"
$siteCollectionUrl = "https://web.sharepoint.com"
$webUrl = $siteCollectionUrl + "/sites"
$docLibraryTitle = "Application"
$destinationLocalFolder = "C:\test"
#------------------------------------------------
Import-Module C:\SPOMod\SPOMod20160326.psm1
#------------------------------------------------
Connect-SPOCSOM -Username $userName -Url $webUrl
#Download document function
function HTTPDownloadFile ($serverFileLocation, $downloadPath)
{
#create secure password
$sPassword = $password | ConvertTo-SecureString -AsPlainText -Force
$webClient = New-Object System.Net.WebClient
$webClient.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $sPassword)
$webClient.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
[System.Uri]$destinationUri = [System.Uri]$serverFileLocation
Write-Host "Downloading" $serverFileLocation "as" $downloadPath
$webClient.DownloadFile($destinationUri, $DownloadPath)
$webClient.Dispose()
}
#------------------------------------------------
#Get files (not dirs)
$listItems = Get-SPOListItems -ListTitle $docLibraryTitle -IncludeAllProperties $true -Recursive | where {$_.FsObjType -eq 0}
#Iteration on all files in doc. library
foreach ($item in $listItems)
{
[string]$sourceDirectory = $item.FileDirRef
[string]$sourceFileName = $item.FileLeafRef
[String]$sourceFileUrl = $siteCollectionUrl + $item.FileRef
#create destination directory
[string]$destinationDirectory = $destinationLocalFolder + $sourceDirectory
$destinationDirectory = $destinationDirectory.Replace("/","\")
if (!(Test-Path -path $destinationDirectory))
{
New-Item -path $destinationDirectory -type directory
}
#download current version document
[string]$destinationFilePath = $destinationDirectory + "\" + $sourceFileName
HTTPDownloadFile $sourceFileUrl $destinationFilePath
}
Script finds all files but when trying to download :
error:
Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (401) Unauthorized."
At C:\Users\SHAREPOINT.ps1:28 char:5
+ $webClient.DownloadFile($destinationUri, $DownloadPath)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
Please help.
Test script:
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
$userName = "user#xxx.onmicrosoft.com"
$siteCollectionUrl = "https://xxx.sharepoint.com"
$webUrl = $siteCollectionUrl + "/sites/lee"
$docLibraryTitle = "MyDoc4"
$destinationLocalFolder = "C:\test"
#------------------------------------------------
Import-Module C:\Lee\Script\SPOMod\SPOMod20160326.psm1
#------------------------------------------------
Connect-SPOCSOM -Username $userName -Url $webUrl
#Download document function
function HTTPDownloadFile ($serverFileLocation, $downloadPath)
{
#create secure password
#$sPassword=$global:Password
$webClient = New-Object System.Net.WebClient
$webClient.Credentials = $global:ctx.Credentials
$webClient.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
#$webClient.Headers.Add("User-Agent: Other");
[System.Uri]$destinationUri = [System.Uri]$serverFileLocation
Write-Host "Downloading" $serverFileLocation "as" $downloadPath
$webClient.DownloadFile($destinationUri, $DownloadPath)
$webClient.Dispose()
}
#------------------------------------------------
#Get files (not dirs)
$listItems = Get-SPOListItems -ListTitle $docLibraryTitle -IncludeAllProperties $true -Recursive | where {$_.FsObjType -eq 0}
#Iteration on all files in doc. library
foreach ($item in $listItems)
{
[string]$sourceDirectory = $item.FileDirRef
[string]$sourceFileName = $item.FileLeafRef
[String]$sourceFileUrl = $siteCollectionUrl + $item.FileRef
#create destination directory
[string]$destinationDirectory = $destinationLocalFolder + $sourceDirectory
$destinationDirectory = $destinationDirectory.Replace("/","\")
if (!(Test-Path -path $destinationDirectory))
{
New-Item -path $destinationDirectory -type directory
}
#download current version document
[string]$destinationFilePath = $destinationDirectory + "\" + $sourceFileName
HTTPDownloadFile $sourceFileUrl $destinationFilePath
}

Uploading bulk files from local system to SharePoint online using PowerShell script throwing an error you cannot call null valued expression

My requirement is to upload multiple files using PowerShell script to SharePoint online.
while uploading files to a folder in the SharePoint document library, it showing me this error.
I am extracting only file name before uploading and create a folder with that filename and want to upload the file in that particular folder using PowerShell script .
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
### Variables for Processing
$WebUrl = "https://tanviteddu.sharepoint.com/sites/Powershell/"
$LibraryName ="Documents"
$ListURL="/sites/Powershell/Shared Documents/Reports"
$SourceFolder="C:\Hari Priya"
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))
#Set up the context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl)
$Context.Credentials = $Credentials
#Get the Library
$Library = $Context.Web.Lists.GetByTitle($LibraryName)
#upload each file from the directory
Foreach ($File in (dir $SourceFolder -File))
{
$fn=(Split-path -Path $file -Leaf).Split(".")[0];
Try
{
#Set up the context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
$Context.Credentials = $credentials
#Get the List Root Folder
$ParentFolder=$Context.web.GetFolderByServerRelativeUrl($ListURL)
#sharepoint online powershell create folder
$Folder = $ParentFolder.Folders.Add($fn)
$ParentFolder.Context.ExecuteQuery()
Write-host "New Folder Created Successfully!" -ForegroundColor Green
}
catch
{
write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}
#Get the file from disk
$FileStream = ([System.IO.FileInfo] (Get-Item $File.FullName)).OpenRead()
$FinalUrl=$ListURL+"\"+$fn+"\"+$file
#Upload the File to SharePoint Library
$FileCreationInfo = New-Object
Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $File
$FileUploaded = $FinalUrl.RootFolder.Files.Add($FileCreationInfo)
#powershell to upload files to sharepoint online
$Context.Load($FileUploaded)
$Context.ExecuteQuery()
#Close file stream
$FileStream.Close()
write-host "File: $($File) has been uploaded!"
}
While uploading, it is showing the error as below:
You cannot call a method on a null-valued expression.
At line:26 char:5
+ $FileUploaded = $FinalUrl.RootFolder.Files.Add($FileCreationInfo)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeExceptio
+ FullyQualifiedErrorId : InvokeMethodOnNull
Cannot find an overload for "Load" and the argument count: "1".
At line:28 char:5
+ $Context.Load($FileUploaded)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Please help me out
The below is working code - upload files from local drive to SharePoint online using PowerShell CSOM:
#Load SharePoint CSOM Assemblies
#Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
#Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
cls
$fileName = "File_Uploading_Report"
#'yyyyMMddhhmm yyyyMMdd
$enddate = (Get-Date).tostring("yyyyMMddhhmmss")
#$filename = $enddate + '_VMReport.doc'
$logFileName = $fileName +"_"+ $enddate+"_Log.txt"
$invocation = (Get-Variable MyInvocation).Value
$directoryPath = Split-Path $invocation.MyCommand.Path
$directoryPathForLog=$directoryPath+"\"+"LogFiles"
if(!(Test-Path -path $directoryPathForLog))
{
New-Item -ItemType directory -Path $directoryPathForLog
#Write-Host "Please Provide Proper Log Path" -ForegroundColor Red
}
#$logPath = $directoryPath + "\" + $logFileName
$logPath = $directoryPathForLog + "\" + $logFileName
$isLogFileCreated = $False
#DLL location
$directoryPathForDLL=$directoryPath+"\"+"Dependency Files"
if(!(Test-Path -path $directoryPathForDLL))
{
New-Item -ItemType directory -Path $directoryPathForDLL
#Write-Host "Please Provide Proper Log Path" -ForegroundColor Red
}
#DLL location
$clientDLL=$directoryPathForDLL+"\"+"Microsoft.SharePoint.Client.dll"
$clientDLLRuntime=$directoryPathForDLL+"\"+"Microsoft.SharePoint.Client.dll"
Add-Type -Path $clientDLL
Add-Type -Path $clientDLLRuntime
#Files to upload location
$directoryPathForFileToUploadLocation=$directoryPath+"\"+"Files To Upload"
if(!(Test-Path -path $directoryPathForFileToUploadLocation))
{
New-Item -ItemType directory -Path $directoryPathForFileToUploadLocation
#Write-Host "Please Provide Proper Log Path" -ForegroundColor Red
}
#Files to upload location ends here.
function Write-Log([string]$logMsg)
{
if(!$isLogFileCreated){
Write-Host "Creating Log File..."
if(!(Test-Path -path $directoryPath))
{
Write-Host "Please Provide Proper Log Path" -ForegroundColor Red
}
else
{
$script:isLogFileCreated = $True
Write-Host "Log File ($logFileName) Created..."
[string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)
Add-Content -Path $logPath -Value $logMessage
}
}
else
{
[string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)
Add-Content -Path $logPath -Value $logMessage
}
}
#The below function will upload the file from local directory to SharePoint Online library.
Function FileUploadToSPOnlineLibrary()
{
param
(
[Parameter(Mandatory=$true)] [string] $SPOSiteURL,
[Parameter(Mandatory=$true)] [string] $SourceFilePath,
[Parameter(Mandatory=$true)] [string] $File,
[Parameter(Mandatory=$true)] [string] $TargetLibrary,
[Parameter(Mandatory=$true)] [string] $UserName,
[Parameter(Mandatory=$true)] [string] $Password
)
Try
{
$securePassword= $Password | ConvertTo-SecureString -AsPlainText -Force
#Setup the Context
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SPOSiteURL)
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $securePassword)
$list = $ctx.Web.Lists.GetByTitle($TargetLibrary)
$ctx.Load($list)
$ctx.ExecuteQuery()
$tarGetFilePath=$siteURL+"/"+"$TargetLibrary"+"/"+$File
$fileOpenStream = New-Object IO.FileStream($SourceFilePath, [System.IO.FileMode]::Open)
$fileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$fileCreationInfo.Overwrite = $true
$fileCreationInfo.ContentStream = $fileOpenStream
$fileCreationInfo.URL = $File
$uploadFileInfo = $list.RootFolder.Files.Add($FileCreationInfo)
$ctx.Load($uploadFileInfo)
$ctx.ExecuteQuery()
Write-host -f Green "File '$SourceFilePath' has been uploaded to '$tarGetFilePath' successfully!"
}
Catch
{
$ErrorMessage = $_.Exception.Message +"in uploading File!: " +$tarGetFilePath
Write-Host $ErrorMessage -BackgroundColor Red
Write-Log $ErrorMessage
}
}
#Variables
$siteURL="https://globalsharepoint.sharepoint.com/sites/TestSite/"
$listName="TestDocumentLibrary"
$fromDate="2019-10-28"
$toDate="2019-11-09"
$filesFolderLoaction=$directoryPathForFileToUploadLocation;
$userName = "YourSPOAccount#YourTenantDomain.com"
$password = "YourPassWord"
$securePassword= $password | ConvertTo-SecureString -AsPlainText -Force
#Variables ends here.
$filesCollectionInSourceDirectory=Get-ChildItem $filesFolderLoaction -File
$uploadItemCount=1;
#Extract the each file item from the folder.
ForEach($oneFile in $filesCollectionInSourceDirectory)
{
try
{
FileUploadToSPOnlineLibrary -SPOSiteURL $siteURL -SourceFilePath $oneFile.FullName -File $oneFile -TargetLibrary $listName -UserName $UserName -Password $Password
$fileUploadingMessage=$uploadItemCount.ToString()+": "+$oneFile.Name;
Write-Host $fileUploadingMessage -BackgroundColor DarkGreen
Write-Log $fileUploadingMessage
$uploadItemCount++
}
catch
{
$ErrorMessage = $_.Exception.Message +"in: " +$oneFile.Name
Write-Host $ErrorMessage -BackgroundColor Red
Write-Log $ErrorMessage
}
}
Write-Host "========================================================================"
Write-Host "Total number of files uploaded: " $filesCollectionInSourceDirectory.Count
Write-Host "========================================================================"
Reference URL:
https://global-sharepoint.com/powershell/upload-files-to-sharepoint-online-document-library-using-powershell-csom/