MyITGuy
1/24/2019 - 8:10 PM

Get-SharePointList

Retrieves list data from a SharePoint list.

function Get-SharePointList {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [Uri]
        $Uri
        ,
        [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [String]
        $Name
    )
    
    begin {
        Add-Type -Path "$($PSScriptRoot)\Microsoft.SharePoint.Client.dll"
        Add-Type -Path "$($PSScriptRoot)\Microsoft.SharePoint.Client.Runtime.dll"
    }
    
    process {
        $ClientContext = [Microsoft.SharePoint.Client.ClientContext]::new($Uri)
        $Web = $ClientContext.Web
        $Site = $ClientContext.Site
        $ClientContext.Load($Web)
        $Lists = $Web.Lists
        $ClientContext.Load($Lists)
        $List = $Lists.GetByTitle($Name)
        $ClientContext.Load($List)
        $ListItems = $List.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
        $ClientContext.Load($ListItems)
        $Fields = $List.Fields
        $ClientContext.Load($Fields)
        $ClientContext.Load($Site)
        $ClientContext.ExecuteQuery()
        foreach ($ListItem in $ListItems) {
            foreach ($FieldValue In $ListItem.FieldValues) {
                $Properties = [ordered]@{}
                foreach ($Entry In $FieldValue.GetEnumerator()) {
                    $Properties."$([System.Xml.XmlConvert]::DecodeName($Entry.Key))" = $Entry.Value
                }
                $obj = New-Object -TypeName PSObject -Property $Properties
                Write-Output -InputObject $obj
            }
        }
    }
    
    end {
        if ($ClientContext) {
            $ClientContext.Dispose()
        }
    }
}