Powershell : Upload Files/Folders to Sharepoint


If you need to upload files to SharePoint online then I wrote a script to do that, this script can be automated for repetitive tasks, first lets take a loo at the target folder in SharePoint, this is off Documents then Testing notice it is blank:


First we need to install the require module for this to work with the command:

Install-Module -Name SharePointPnPPowerShellOnline -Scope CurrentUser

Then we need the script and we need to set variables in that script before we can run it:

Script : ShellUpload.ps1

# Variables
$siteUrl = "<shrepoint_site_url>"
$filePath = "\c:\temp\test.csv"
$folderPath = "Shared Documents/Testing" 

# Connect to SharePoint
try {
    Connect-PnPOnline -Url $siteUrl -UseWebLogin
    Write-Host "Connected to SharePoint site: $siteUrl"
} catch {
    Write-Error "Failed to connect to SharePoint. Error: $($_.Exception.Message)"
    exit
}

# Upload File
try {
    Add-PnPFile -Path $filePath -Folder $folderPath
    Write-Host "File uploaded successfully to $folderPath."
} catch {
    Write-Error "Failed to upload file. Error: $($_.Exception.Message)"
}

This should then confirm when you run the script that the file has been uploaded:


If we then check the website version of this website, the blank folder should now have a file uploaded and as we can see it does:


Uploading a folder

If you wish to upload a folder and not just a file then that requires some modifications but that will then upload the name of the folder and the files within that folder like this:


The script to do this is as below, again update the variables to match you environment.

Script : ShellFolderUpload.ps1

# Variables
$siteUrl = "<shrepoint_site_url>"
$filePath = "\c:\temp\WillyNilly"
$folderPath = "Shared Documents/Testing" 

# Connect to SharePoint
try {
    Connect-PnPOnline -Url $siteUrl -UseWebLogin
    Write-Host "Connected to SharePoint site: $siteUrl"
} catch {
    Write-Error "Failed to connect to SharePoint. Error: $($_.Exception.Message)"
    exit
}

# Function to upload folder and its contents
function Upload-FolderToSharePoint {
    param (
        [string]$sourceFolder,
        [string]$destFolder
    )

    # Get the source folder name
    $sourceFolderName = Split-Path $sourceFolder -Leaf
    $targetFolderPath = Join-Path $destFolder $sourceFolderName

    # Create the parent folder first
    try {
        Add-PnPFolder -Name $sourceFolderName -Folder $destFolder
        Write-Host "Created main folder: $sourceFolderName in $destFolder"
    } catch {
        Write-Error "Failed to create main folder $sourceFolderName. Error: $($_.Exception.Message)"
        return
    }

    # Get all items in the source folder
    $items = Get-ChildItem -Path $sourceFolder -Recurse

    foreach ($item in $items) {
        # Calculate the relative path from the source folder
        $relativePath = $item.FullName.Replace($sourceFolder, '').TrimStart('\')
        $targetPath = Join-Path $targetFolderPath $relativePath

        if ($item.PSIsContainer) {
            # If item is a folder, create it in SharePoint
            try {
                Add-PnPFolder -Name $item.Name -Folder (Split-Path $targetPath)
                Write-Host "Created subfolder: $($item.Name)"
            } catch {
                Write-Error "Failed to create subfolder $($item.Name). Error: $($_.Exception.Message)"
            }
        } else {
            # If item is a file, upload it
            try {
                Add-PnPFile -Path $item.FullName -Folder (Split-Path $targetPath) -ErrorAction Stop
                Write-Host "Uploaded file: $($item.Name)"
            } catch {
                Write-Error "Failed to upload file $($item.Name). Error: $($_.Exception.Message)"
            }
        }
    }
}

# Execute the folder upload
try {
    Write-Host "Starting folder upload from $sourceFolderPath to $destinationFolderPath..."
    Upload-FolderToSharePoint -sourceFolder $sourceFolderPath -destFolder $destinationFolderPath
    Write-Host "Folder upload completed successfully."
} catch {
    Write-Error "Failed to complete folder upload. Error: $($_.Exception.Message)"
}

When run that should look like this:

Previous Post Next Post

نموذج الاتصال