Skip to main content

Automating SharePoint List Updates with PnP PowerShell and Excel Integration

In this post, we will walk through a PowerShell script that automates updating SharePoint list items using PnP PowerShell commands, including reading data from an Excel file to add new items to a secondary SharePoint list. This is useful for syncing or updating information across SharePoint lists, saving time and reducing manual effort.

Prerequisites

Before diving into the script, ensure you have the following:

  1. PnP PowerShell Module: You can install this via PowerShell by running Install-Module -Name "PnP.PowerShell" -Force -AllowClobber.
  2. Access to SharePoint Online Site: Ensure you have the necessary permissions to read and update SharePoint lists.
  3. Excel File: An Excel file with the data you want to import into the SharePoint list. The script uses the Import-Excel command, which requires the ImportExcel PowerShell module. You can install it using Install-Module -Name ImportExcel.

Script Overview

This script connects to a SharePoint Online site, retrieves items from a Locations List, and for each item, checks if certain conditions are met (in this case, skipping items with specific IDs). If the conditions are not met, it reads an Excel file and adds new items to another SharePoint list called Shifts List.

Here’s a breakdown of the script:

$SiteUrl = "https://[Domain]/sites/SiteCollectionName"

$ListName = "Locations List"


# Connect to the SharePoint site

Connect-PnPOnline -Url $SiteUrl -UseWebLogin 


# Retrieve items from the Locations List

$ListItems = Get-PnPListItem -List $ListName -Fields "Title" -PageSize 2000


# Loop through each item in the Locations List

foreach($ListItem in $ListItems)

{

    Write-Host "ID:" $ListItem["ID"]

    Write-Host "Location Name:" $ListItem["Title"]

    

    # Skip processing for specific items

    if ($ListItem["ID"] -eq "15" -or $ListItem["ID"] -eq "8") {

        Write-Host "ID matches, skipping execution."

        #return  # This would skip the rest of the script if uncommented

    }

    else {

        # Import data from the Excel file

        $data = Import-Excel -Path "C:\FilePath.xlsx"

        

        # Name of the list to add items to

        $ListNameShift = "Shifts List"

        

        # Add records to the Shifts List

        try {

            ForEach($record in $data) {

                Write-Host "Adding record $($ListItem["Title"])"

                

                # Add items to the Shifts List, mapping Excel data to SharePoint fields

                Add-PnPListItem -List $ListNameShift -Values @{

                    "Title" = $($record.'Title')

                    "Location" = $($ListItem["ID"])

                    "SORT_ORDER" = $($record.'SORT_ORDER')

                    "ACTIVE_FLAG" = $($record.'ACTIVE_FLAG')

                }

            }

        } catch {

            Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red

        }

    }

}

Step-by-Step Explanation

  1. Connect to SharePoint Site: The script begins by defining the SharePoint site URL and list names. Then, it uses the Connect-PnPOnline command to authenticate and connect to the SharePoint site using the -UseWebLogin option. This method prompts for credentials if needed.

  2. Retrieve Items from the Locations List: Using Get-PnPListItem, the script fetches all items from the Locations List. It specifies to fetch the "Title" field and limits the number of items fetched to 2000 for performance reasons.

  3. Loop Through List Items: For each item in the Locations List, the script:

    • Displays the ID and Title of the list item.
    • Checks if the item’s ID matches certain values (15 and 8 in this case). If it matches, it skips the rest of the loop and moves to the next item. You can adjust this condition to suit your needs.
  4. Read Excel Data: If the ID does not match the skip condition, the script imports data from an Excel file located at C:\FilePath.xlsx. Each row in the Excel file contains data that will be added to the Shifts List.

  5. Add Items to the Shifts List: The script iterates through the Excel data and adds each record to the Shifts List. The Add-PnPListItem cmdlet is used to create a new item in the list, mapping the relevant fields (e.g., Title, SORT_ORDER, ACTIVE_FLAG) from the Excel file to the SharePoint list columns.

  6. Error Handling: If there are any errors during the process (e.g., issues with the Excel file or SharePoint list), the script will catch the error and display an appropriate message.

Conclusion

This script demonstrates how to automate the process of updating a SharePoint list based on data from another list and an Excel file. By leveraging the PnP PowerShell module, you can streamline SharePoint list management tasks, making it easier to keep your data in sync without manual intervention. Whether you're dealing with large datasets or need to automate repetitive tasks, PowerShell provides a powerful toolset for SharePoint administration.

Let me know if you need help customizing this script for your specific use case or if you have any questions!

    Comments

    Popular posts from this blog

    Get App Expiry Dates using Powershell

    Step 1: Connect-MsolService Step 2: $applist = Get-MsolServicePrincipal -all  |Where-Object -FilterScript { ($_.DisplayName -notlike "*Microsoft*") -and ($_.DisplayName -notlike "autohost*") -and  ($_.ServicePrincipalNames -notlike "*localhost*") } Step 3: foreach ($appentry in $applist) {     $principalId = $appentry.AppPrincipalId     $principalName = $appentry.DisplayName     Get-MsolServicePrincipalCredential -AppPrincipalId $principalId -ReturnKeyValues $false | ? { $_.Type -eq "Password" } | % { "$principalName;$principalId;" + $_.KeyId.ToString() +";" + $_.StartDate.ToString() + ";" + $_.EndDate.ToString() } | out-file -FilePath d:\appsec.txt -append }

    Bulk Import Excel Data to SharePoint List Using PowerShell and PnP

      Managing large datasets in SharePoint can be tricky, especially when you're dealing with Excel files and need to avoid list view threshold issues. In this guide, I’ll walk you through a PowerShell script that efficiently imports data from Excel into a SharePoint Online list using PnP PowerShell — with batching support for performance. Prerequisites Make sure you have the following before running the script: SharePoint Online site URL Excel file with data properly formatted PnP PowerShell module installed ( Install-Module PnP.PowerShell ) Appropriate SharePoint permissions What the Script Does Connects to your SharePoint site Loads and reads an Excel file Converts Excel date values Batches records in groups (to avoid the 5000 item threshold) Adds the items to your SharePoint list or library Logs execution time PowerShell Script $siteUrl = "[Site Collection URL]" Connect-PnPOnline -Url $siteUrl -UseWebLogin # Capture the start time $startTime...

    ๐Ÿš€ Essential SPFx (SharePoint Framework) Commands for Every Developer

    Whether you're new to SharePoint Framework (SPFx) or a seasoned pro, having a go-to list of core commands can significantly improve your development workflow. In this post, we'll walk through the most important SPFx CLI commands—from setting up your environment to packaging and deploying your solution. ๐Ÿ› ️ Setting Up Your SPFx Project Start by scaffolding a new project using the Yeoman generator provided by Microsoft. Make sure Node.js and npm are installed before you proceed. yo @microsoft/sharepoint After scaffolding the project, install all dependencies: npm install To update dependencies later: npm update ๐Ÿ” Trusting the Development Certificate If you're using the local workbench, you need to trust the developer certificate for HTTPS support: gulp trust-dev-cert ๐Ÿงช Running the Local Workbench To build and serve your project locally, use: gulp serve This command starts a local server at: https://localhost:4321/temp/workbench.html You can also test your solution in ShareP...