Update List/Library Metadata of SharePoint List(Online) using PNP PowerShell

cls
$error.Clear()

#get the location of the script file
$scriptBase=Split-Path $SCRIPT:MyInvocation.MyCommand.Path -Parent

 Set-Location $scriptBase 

$path=Get-Location 

$FilePath="$path\"+"Documents.csv" 

#Output log file name
$outputFile="updateMetadataLog.csv" 

$outputfilepath="$path\"+$outputFile 

#Portal url
$SiteURL= "SITEURL" 

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -ClientId CLIENTID
#Get the Root Web
$Web = Get-PnPWeb

#Get the Site Title
Write-host -f Green $Web.Title 

# Library Name
$libraryName="DOCUMENT LIBRARY"
$DocId=""
$srcFileName=""
$metadatastatus="" 

#function to export to log file

function exporttoLog()
{
   $data = @{ 

           "SourceFileName"=$srcFileName        
           "Status"=$metadatastatus
           }
   New-Object PSObject -Property $data
}

 function UpdateMetadataForDocs()

{
    $arr=@{}

    Write-Host "Path"  $FilePath 

    #Get Source CSV. this CSV has my columns data that need to be updated in the list/library
    $Documents=Import-Csv -Path $FilePath -UseCulture

     foreach($row in $Documents)

    {
        $srcFileName=$row.FileName
        $FolderPath=$row.FilePath
        $SiteRelativeURL="PATH TILL LIBRARY NAME"+$FolderPath+"/"+$srcFileName
        Write-Host -f yellow "Source File name --- " $srcFileName
        Write-Host -f yellow "Folder Path ---- " $SiteRelativeURL

         $FileItem=Get-PnPFile -Url $SiteRelativeURL -AsListItem

         Write-Host -f Green  "Item from Doc Lib --- " $FileItem["Title"]

        Write-Host -f Green "Id of the File Item --- " $FileItem["ID"]

         # Update column values for documents 

        try
        {

    $li= Set-PnPListItem -List $libraryName  -Identity $FileItem["ID"]  -Values @{'Title' = $row.DocumentTitle;'Department'=$row.Department;'Status'=$row.Status;'Author'=$row.CreatedBy;'Created'=$row.Created;'Modified'=$row.Modified;'Editor'=$row.ModifiedBy;}

                 $metadatastatus="Updated successfully"

                 Write-host -f Red "Metadata Update" for $FileItem["Title"]

        }

        catch
        {
          $metadatastatus=$_.Exception.Message

           Write-Host  $_.Exception.Message  

         }

   exporttoLog  

     }

     }

UpdateMetadataForDocs |  Export-Csv -NoTypeInformation -Path $outputfilepath

Comments

Popular posts from this blog

Developing Custom workflows in SharePoint 2007 using Visual Studio 2005

Sharepoint 2010:ECMA script to retrieve list data

Tabs for sharepoint list forms using Jquery