Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save olegrumiancev/cd7f91c8fe13a3df21f308c6d82d3ac9 to your computer and use it in GitHub Desktop.
Save olegrumiancev/cd7f91c8fe13a3df21f308c6d82d3ac9 to your computer and use it in GitHub Desktop.
PowerShell - Upload a folder to SharePoint Online using PnP framework
function UploadDocuments() {
Param(
[ValidateScript({If(Test-Path $_){$true}else{Throw "Invalid path given: $_"}})]
$LocalFolderLocation,
[String]
$siteUrl,
[String]
$documentLibraryName
)
Process {
$path = $LocalFolderLocation.TrimEnd('\')
Write-Host "Provided Site: "$siteUrl -ForegroundColor Green
Write-Host "Provided Path: "$path -ForegroundColor Green
Write-Host "Provided Document Library name: "$documentLibraryName -ForegroundColor Green
try {
Connect-PnPOnline -Url $siteUrl -UseWebLogin #-CreateDrive -Credentials $credentials
# Ensure doc lib exists
$lib = $null
$lib = Get-PnPList -Identity $documentLibraryName
if ($lib -eq $null) {
$lib = New-PnPList -Title $documentLibraryName -Url $documentLibraryName -Template DocumentLibrary
}
$file = Get-ChildItem -Path $LocalFolderLocation -Recurse
$i = 0;
Write-Host "Uploading documents to Site..." -ForegroundColor Cyan
(dir $path -Recurse) | Foreach {
try {
$i++
if ($_.GetType().Name -eq "FileInfo") {
$SPFolderName = $documentLibraryName + $_.DirectoryName.Substring($path.Length);
$status = "Uploading Files :'" + $_.Name + "' to Location :" + $SPFolderName
Write-Progress -activity "Uploading Documents.." -status $status -PercentComplete (($i / $file.length) * 100)
$te = Add-PnPFile -Path $_.FullName -Folder $SPFolderName
}
}
catch {
}
}
}
catch {
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
}
$localFolderLocation = "C:\Location\"
$spSiteUrl = "https://tenant.sharepoint.com/sites/target"
$docLibInternalName = "libInternalName" # script handles edge case when library is not present by creating it
UploadDocuments -LocalFolderLocation $localFolderLocation -siteUrl $spSiteUrl -documentLibraryName $docLibInternalName
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment