Tuesday, July 26, 2022

Download All Files From Library in SharePoint online

 #Load SharePoint CSOM Assemblies

Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"

Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

 

Function Download-AllFilesFromLibrary()

{

    param

    (

        [Parameter(Mandatory=$true)] [string] $SiteURL,

        [Parameter(Mandatory=$true)] [Microsoft.SharePoint.Client.Folder] $SourceFolder,

        [Parameter(Mandatory=$true)] [string] $TargetFolder

    )

    Try {

         

        #Create Local Folder, if it doesn't exist

        $FolderName = ($SourceFolder.ServerRelativeURL) -replace "/","\"

        $LocalFolder = $TargetFolder + $FolderName

        If (!(Test-Path -Path $LocalFolder)) {

                New-Item -ItemType Directory -Path $LocalFolder | Out-Null

        }

         

        #Get all Files from the folder

        $FilesColl = $SourceFolder.Files

        $Ctx.Load($FilesColl)

        $Ctx.ExecuteQuery()

 

        #Iterate through each file and download

        Foreach($File in $FilesColl)

        {

            $TargetFile = $LocalFolder+"\"+$File.Name

            #Download the file

            $FileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($Ctx,$File.ServerRelativeURL)

            $WriteStream = [System.IO.File]::Open($TargetFile,[System.IO.FileMode]::Create)

            $FileInfo.Stream.CopyTo($WriteStream)

            $WriteStream.Close()

            write-host -f Green "Downloaded File:"$TargetFile

        }

         

        #Process Sub Folders

        $SubFolders = $SourceFolder.Folders

        $Ctx.Load($SubFolders)

        $Ctx.ExecuteQuery()

        Foreach($Folder in $SubFolders)

        {

            If($Folder.Name -ne "Forms")

            {

                #Call the function recursively

                Download-AllFilesFromLibrary -SiteURL $SiteURL -SourceFolder $Folder -TargetFolder $TargetFolder

            }

        }

  }

    Catch {

        write-host -f Red "Error Downloading Files from Library!" $_.Exception.Message

    }

}

 

#Set parameter values

$SiteURL="<SITEURL>"

$LibraryName="Style Library"

$TargetFolder="D:\0\"

 

#Setup Credentials to connect

$Cred= Get-Credential

$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

 

#Setup the context

$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)

$Ctx.Credentials = $Credentials

      

#Get the Library

$List = $Ctx.Web.Lists.GetByTitle($LibraryName)

$Ctx.Load($List)

$Ctx.Load($List.RootFolder)

$Ctx.ExecuteQuery()

 

#Call the function: sharepoint online download multiple files powershell

Download-AllFilesFromLibrary -SiteURL $SiteURL -SourceFolder $List.RootFolder -TargetFolder $TargetFolder


Tuesday, July 12, 2022

Delete all Items from SharePoint Online List

 Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"

Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

     

#Config Parameters

$SiteURL="SharePoint Site URL"

$ListName="List Name"

$BatchSize = 500

   

#Setup Credentials to connect

$Cred = Get-Credential

   

Try {

    #Setup the context

    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)

    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

   

    #Get the web and List

    $Web = $Ctx.Web

    $List=$web.Lists.GetByTitle($ListName)

    $Ctx.Load($List)

    $Ctx.ExecuteQuery()

    Write-host "Total Number of Items Found in the List:"$List.ItemCount

  

    #Define CAML Query to get list items in batches

    $Query = New-Object Microsoft.SharePoint.Client.CamlQuery

    $Query.ViewXml = "<View Scope='RecursiveAll'><RowLimit Paged='TRUE'>$BatchSize</RowLimit></View>"

  

    Do {  

        #Get items from the list in batches

        $ListItems = $List.GetItems($Query)

        $Ctx.Load($ListItems)

        $Ctx.ExecuteQuery()

          

        #Exit from Loop if No items found

        If($ListItems.count -eq 0) { Break; }

  

        Write-host Deleting $($ListItems.count) Items from the List...

  

        #Loop through each item and delete

        ForEach($Item in $ListItems)

        {

            $List.GetItemById($Item.Id).DeleteObject()

        } 

        $Ctx.ExecuteQuery()

  

    } While ($True)

  

    Write-host -f Green "All Items Deleted!"

}

Catch {

    write-host -f Red "Error Deleting List Items!" $_.Exception.Message

}

Copy Items from One List to Another List

 #Load SharePoint CSOM Assemblies

Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"

Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

 

Function Copy-ListItems()

{

    param

    (

        [Parameter(Mandatory=$true)] [string] $SiteURL,

        [Parameter(Mandatory=$true)] [string] $SourceListName,

        [Parameter(Mandatory=$true)] [string] $TargetListName

    )    

    Try {

        #Setup Credentials to connect

        $Cred = Get-Credential

        $Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

     

        #Setup the context

        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)

        $Ctx.Credentials = $Cred

 

        #Get the Source List and Target Lists

        $SourceList = $Ctx.Web.Lists.GetByTitle($SourceListName)

        $TargetList = $Ctx.Web.Lists.GetByTitle($TargetListName)

     

        #Get All Items from Source List

        $SourceListItems = $SourceList.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())

        $Ctx.Load($SourceListItems)

        $Ctx.ExecuteQuery()

     

        #Get each column value from source list and add them to target

        ForEach($SourceItem in $SourceListItems)

        {

            $NewItem =New-Object Microsoft.SharePoint.Client.ListItemCreationInformation

            $ListItem = $TargetList.AddItem($NewItem)

         

            #Map each field from source list to target list - INTERNAL NAMES

            $ListItem["Title"] = $SourceItem["Title"]

            $ListItem["Title1"] = $SourceItem["Title"]

            $ListItem["Title2"] = $SourceItem["Title"]

            

            $ListItem.update()

        }

        $Ctx.ExecuteQuery()

 

        write-host  -f Green "Total List Items Copied from '$SourceListName' to '$TargetListName' : $($SourceListItems.count)"

    }

    Catch {

        write-host -f Red "Error Copying List Items!" $_.Exception.Message

    }

}

 

#Set Parameters

$SiteURL= "Sharepoint Site URL"

$SourceListName="List Name"

$TargetListName="List Name"

 

#Call the function to copy list items

Copy-ListItems -siteURL $SiteURL -SourceListName $SourceListName -TargetListName $TargetListName