So I've been trying for the past 4 days now to write a full automated Powershell script that will connect to SharePoint Online, automatically login with credentials (with password located in a file), locate a List Title, and export all fields (Name, Description, Owner, etc.) and items in each field.
I believe it's just about there, but I'm having a problem with the foreach loop returning everything. This is making me pull my hair out and any help would be more than greatly appreciated.
Here's the full code (some parts found online and some parts hand coded):
#Load SharePoint CSOM Assemblie
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"
#Defining Variables
$SiteUrl = "https://site.sharepoint.com"
$ListName = "ListTitle"
$Path = "C:\Users\Username\Desktop\filename.csv"
$UserName = "[email protected]"
$Password = Get-Content "C:\Users\Username\Desktop\password.txt" | ConvertTo-SecureString -Force
#Automated Login Credentials
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $password)
$Context.Credentials = $credentials
#Retrive the List
$List = $Context.web.Lists.GetByTitle($ListName)
#Get All List Items
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery
$ListItems = $List.GetItems($Query)
$context.Load($ListItems)
$context.ExecuteQuery()
# Turn item into a catch array
$ListItemCollection = @()
#Fetch each list item value to export to excel
$ListItems | foreach {
$ExportItem = New-Object PSObject
$ExportItem | Add-Member -MemberType NoteProperty -name "Title" -value $_["Title"]
#Add the object with above properties to the Array
$ListItemCollection += $ExportItem
}
#Export the result Array to CSV file
$ListItemCollection | Export-CSV $Path -NoTypeInformation
Write-host "Deed has been done!"
So I can name all fields manually in the foreach loop, but is there a way to just pull everything instead?
Thanks so much!
List.Fields
into your context and iterate over that. Article and sample code is here.