Code Explainer

PowerShell Script for SharePoint File Management

This PowerShell script leverages the PnP PowerShell module to connect to SharePoint, read file names from a CSV, and move the specified files to a designated folder while handling potential duplicates and errors.


Empty image or helper icon

Prompt

# Import PnP PowerShell module
Import-Module PnP.PowerShell

# Connect to the SharePoint site
Connect-PnPOnline -Url "https://yourtenant.sharepoint.com/sites/yoursite" -UseWebLogin

# Path to your CSV file
$csvPath = "C:\path\to\your\filenames.csv"

# Destination folder relative URL
$destinationFolder = "/sites/yoursite/Shared Documents/YourDestinationFolder"

# Import the CSV file
$files = Import-Csv -Path $csvPath

# Loop through each file name in the CSV
foreach ($file in $files) {
    $fileName = $file.FileName # Assuming your CSV has a column 'FileName'

    # Search for the file in the document library
    $fileItems = Get-PnPListItem -List "Documents" -Query "$fileName"

    # If multiple items are found or it's not an array, ensure it's treated properly
    if ($fileItems.Count -eq 1) {
        $fileItem = $fileItems[0] # Get the first (and hopefully only) item
        $fileUrl = $fileItem.FieldValues["FileRef"]

        # Move the file to the destination folder
        Move-PnPFile -ServerRelativeUrl $fileUrl -TargetUrl "$destinationFolder/$fileName" -Force
        Write-Output "Moved $fileName to $destinationFolder"
    } elseif ($fileItems.Count -gt 1) {
        Write-Output "Multiple files found for $fileName, skipping."
    } else {
        Write-Output "File $fileName not found."
    }
}

# Disconnect from SharePoint
Disconnect-PnPOnline

Answer

Explanation of the PowerShell Code Snippet

This PowerShell script utilizes the PnP PowerShell module to connect to a SharePoint site and move files based on a list of names provided in a CSV file. Below is a detailed breakdown of the code.

Code Breakdown

1. Importing the PnP PowerShell Module

Import-Module PnP.PowerShell

This line loads the PnP PowerShell library, which is specifically designed for working with SharePoint Online and enhances PowerShell's capabilities to interact with SharePoint.

2. Connecting to SharePoint

Connect-PnPOnline -Url "https://yourtenant.sharepoint.com/sites/yoursite" -UseWebLogin

Here, we establish a connection to the specified SharePoint site. The -UseWebLogin flag allows for a web-based login, prompting the user to enter their credentials interactively.

3. Defining the CSV File Path

$csvPath = "C:\path\to\your\filenames.csv"

This variable stores the path to the CSV file that contains file names to be processed.

4. Setting the Destination Folder

$destinationFolder = "/sites/yoursite/Shared Documents/YourDestinationFolder"

This variable indicates the relative URL of the folder within the SharePoint site where the files will be moved.

5. Importing the CSV File

$files = Import-Csv -Path $csvPath

The Import-Csv cmdlet reads the CSV file at the specified path and converts its content into an array of objects. Each object corresponds to a row in the CSV file, allowing for easy iteration.

6. Loop Through Each File Name

foreach ($file in $files) {
    $fileName = $file.FileName 

This foreach loop iterates over each file object in the $files array. The variable $fileName fetches the value from the 'FileName' column of the CSV.

7. Searching for the File in the Document Library

$fileItems = Get-PnPListItem -List "Documents" -Query "$fileName"

The Get-PnPListItem cmdlet retrieves items from the "Documents" library in SharePoint based on the CAML query provided. This query searches for files with a name that matches $fileName.

8. Handling Multiple File Retrieval

if ($fileItems.Count -eq 1) {
    $fileItem = $fileItems[0] 
    $fileUrl = $fileItem.FieldValues["FileRef"]

The code checks if exactly one item has been retrieved. If so, it accesses that file's information and extracts the URL of the file using the "FileRef" field.

9. Moving the File

Move-PnPFile -ServerRelativeUrl $fileUrl -TargetUrl "$destinationFolder/$fileName" -Force

The Move-PnPFile cmdlet is used to move the identified file to the target destination folder. The -Force parameter overwrites any existing file with the same name at the target location.

10. Handling Multiple/No File Found Cases

} elseif ($fileItems.Count -gt 1) {
    Write-Output "Multiple files found for $fileName, skipping."
} else {
    Write-Output "File $fileName not found."
}

This section outputs messages to inform the user about the status of the file search:

  • If multiple items are found, it notifies that multiple files exist and skips moving.
  • If no items are found, it indicates that the file is not present.

11. Disconnecting from SharePoint

Disconnect-PnPOnline

Finally, this command disconnects the session from the SharePoint site, ensuring proper resource management.

Key Concepts Explained

  • PnP PowerShell: It is a community-driven resource that allows for simplified management and automation of SharePoint Online operations.
  • CAML Query: Collaborative Application Markup Language (CAML) is used to query SharePoint lists and libraries, providing a way to filter and sort the returned items.
  • CSV File Handling: PowerShell’s Import-Csv cmdlet simplifies reading and manipulating CSV data, converting it into manageable objects.

Additional Example

To illustrate a similar concept, consider a scenario where you want to list file names instead of moving them. The modified loop might look like this:

foreach ($file in $files) {
    $fileName = $file.FileName
    Write-Output "Processing file: $fileName"
    # Other logic can be executed here, such as logging, not moving files
}

By using PowerShell and the PnP module effectively, users can achieve various automation tasks related to SharePoint management.

This comprehensive breakdown aims to enhance your understanding of the script's functionality and the PowerShell framework used in SharePoint Online management.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This PowerShell script leverages the PnP PowerShell module to connect to SharePoint, read file names from a CSV, and move the specified files to a designated folder while handling potential duplicates and errors.