I have a Sharepoint Online site and I am trying to get the grip of Powershell.
I used Powershell with CSOM to create a list from the 'custom list' template. Then I Got the 'City' and 'Company' fields from the Available fields and added them to the list. I also added the fields to appear in the default view, and finally I simply added an item to the list.
I created (or actually re-used a sample I found online) another method which retrieves the list by name, traverses the list, retrieves each item and appends it to an array.
Code here:
$mQueryRowLimit = 200
#Specify tenant admin and site URL
$User = "[email protected]"
$SiteURL = "https://t.sharepoint.com"
$ListTitle = "Demo"
#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
Add-Type -Path "C:\SPServerDLLs\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\SPServerDLLs\Microsoft.SharePoint.Client.Runtime.dll"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds
getAllListItems -_ctx $Context -_listName $ListTitle -_rowLimit $mQueryRowLimit
$Context.Dispose()
function getAllListItems($_ctx, $_listName, $_rowLimit)
{
# Load the up list
$lookupList = $_ctx.Web.Lists.GetByTitle($_listName)
$_ctx.Load($lookupList)
# Prepare the query
$query = New-Object Microsoft.SharePoint.Client.CamlQuery
$query.ViewXml = "<View>
<RowLimit>$_rowLimit</RowLimit>
</View>"
# An array to hold all of the ListItems
$items = @()
# Get Items from the List until we reach the end
do
{
$listItems = $lookupList.getItems($query)
$_ctx.Load($listItems)
$_ctx.ExecuteQuery()
$query.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
foreach($item in $listItems)
{
Try
{
# Add each item
WriteHost $item['Company']
$items += $item
}
Catch [System.Exception]
{
# This shouldn't happen, but just in case
Write-Host $_.Exception.Message
}
}
}
While($query.ListItemCollectionPosition -ne $null)
#return $items
$_ctx.Dispose()
}
I am experiencing some issues with the above code.
WriteHost $item['Company']
This retrieves the content as supposed to.
WriteHost $item['City']
This returns an empty result, when in reality there is a value and I can view it from the list in the Sharepoint site.
Apart from that, when I change the syntax (for e.g. from Company to City), why does it require 2 runs before it actually gives a different result? (I am working in Windows Powershell ISE.)