Format Data Returned from Get-PnPListItem

If you have ever used the SharePoint PnP PowerShell Cmdlets you know that the data returned from the list is not done in the cleanest manor. It is returned as a hashtable and it includes all the internal columns. So, I created a function that will convert this hashtable to a standard PowerShell object and only return the columns you really care about. These are the custom columns you’ve added and some of the common ones like title, modified and created date, as well as the author and last editor.

Function Get-ListValues{
<#
.SYNOPSIS
Use to create a PowerShell Object with only the columns you want,
based on the data returned from the Get-PnPListItem command.

.DESCRIPTION
Creates a custom PowerShell object you can use in your script.
It only creates properties for custom properties on the list and
a few common ones. Filters out a lot of junk you don't need.

.PARAMETER ListItems
The value returns from a Get-PnPListItem command

.PARAMETER List
The name of the list in SharePoint. Should be the same value
passed to the -List parameter on the Get-PnPListItem command

.EXAMPLE
$listItems = Get-PnPListItem -List $List 
$ListValues = Get-ListValues -listItems $listItems -List $List


#>
    param(
    [Parameter(Mandatory=$true)]$ListItems,
    [Parameter(Mandatory=$true)]$List
    )
    # begin by gettings the fields that where created for this list and a few other standard field
    begin{
        $standardFields = 'Title','Modified','Created','Author','Editor'
        # get the list from SharePoint
        $listObject = Get-PnPList -Identity $List
        # Get the fields for the list
        $fields = Get-PnPField -List $listObject
        # create variable with only the fields we want to return
        $StandardFields = $fields | Where-Object{$_.FromBaseType -ne $true -or $standardFields -contains $_.InternalName} | 
            Select @{l='Title';e={$_.Title.Replace(' ','')}}, InternalName
    }
    
    process{
        # process through each item returned and create a PS object based on the fields we want
        [System.Collections.Generic.List[PSObject]] $ListValues = @()
        foreach($item in $listItems){
            # add field with the SharePoint object incase you need to use it in a Set-PnPListItem or Remove-PnPListItem
            $properties = @{SPObject = $item}
            foreach($field in $StandardFields){
                $properties.Add($field.Title,$item[$field.InternalName])
            }
            $ListValues.Add([pscustomobject]$properties)
        }
    }
    
    end{
        # return our new object
        $ListValues
    }
}

To run this, all you have to do is pass the name of the list and the returned data from the Get-PnPListItem command.

$listItems = Get-PnPListItem -List $List 
$ListValues = Get-ListValues -listItems $listItems -List $List

 

Leave a Reply