Skip to main content -->

Retreiving Items or Documents

Once you're connected to a web, getting items or documents is a simple matter of using the Get-SPOListItem command.

Essential Get-SPOListItem Parameters

You should specify one of the following parameters from five parameter sets. If you don't provide one, the command will assume that you wanted -All but will issue a warning.

  • -All: Indicates that you want to retrieve every item from the list. Be warned that on large lists, this can take a long time.
  • -Identity: a pipe binder for a List Item. These may include an ID, a Client Object, or a combination of a field name and value to look up against the list. It is expected that the latter would return only a single item.
  • -Where:Xml: A CAML where clause including the <Where> tag that can be used to filter results.
  • -WhereMatch: An object that can assemble a simple CAML query from a hastable.
    • FieldName: Internal field name
    • FieldValue: Value to compare to a field
    • Operator: Defaults to "Eq", but there are lots of options and most common shorthand are understood in parsing.
    • FieldType: Defaults to "TEXT"
  • -QueryRules: A collection of items, usually imported from a CSV file. There are specifiec rules for how they will be interpreted.
    • For example, you can prefixz any column with "MatchOptions." and end the column name with one of the fields below in -WhereMatch to set its value automatically.
    • MatchOptions.WhereXml is also supported.
    • Anything not matching a reserved name would be considered a field update rule (see Set-SPOListItem -QueryRules).

You must also provide a reference to the target List.

  • -ParentList: A pipe dinfer to a SharePoint list that contains the items you want to retrieve. This can be as simple as a string with the list's Title or ID.
  • -Parent: Same as -ParentList and should be ignored.

More Get-SPOListItem Parameters

The following are supplimental parameters that can adjust the query and resulting output.

  • -QueryOptions: A set of options for querying list items, includuing:
    • Mostly useful for -QueryRules, MatchMethod: determines how queries will be executed can be "OneQuerySimpleMatch" or "MultiQueryMatch" (which is the default). MultiQueryMatch performs sequential CAML queries, while OneQuerySimpleMatch performs a single CAML query followed by one or more in memory searches.
    • PageSize: Determines the maximum number of items that will be returned in a single CSOM query. If your command needs to get more items than will fit on a single page request, it will automatically retrieve multiple pages to get them all. Defaults to 4,000.
    • Scope: Specifies the query scope. Valid values are "All", "FilesOnly", "Recursive", and "RecursiveAll". Will also accept "None", but this is invalid and will cause an error.
    • ViewFields: a collection of strings which are the internal names of fields you want the operation to return in the query. There are some reserved terms that can be used; if your collection has only one member, you may specify "all", "default", "defaultdoclib", or "defaultlist" as shorthand.
    • Order: a Hashtable of fields and sort order "Ascending" or "Descending". You can use "Asc" and "Desc" for short.
    • NoQueryMeansAll: tells CloudPower how to behave when you don't provide a query. Default is to trerat it like a request for all items.
    • UsePagination: Defaults to true. Highly suggest you keep it that way, in case you run into any lists over the 5,000 item threshold.
  • -OutputType: Specifies the objects that will be output to the pipeline. You may wish to specify different output types depending on how you plan to use the results of htis command. Valid values are "ClientObject", "FriendlyName", "NameIdentifier", "PipeBinder", "PsObjectDetailed", "PsObjectSummary", "UniqueId", and "UrlPath". Defaults to "PsObjectSummary".
  • -FriendlyNameField: If specified, determines what field the command will treat as teh friendly name for purposes of output and also looking up values from the -Identity pipe binder. Defaults to "Title".
  • -UseRulesEngine: Most times, Unless you provided -QueryRules parameter, logic will flow through -Identity pipe binder or other parameters. If you want to see what the MetadataExporter would make of your query instead, you can specify this switch to foce it to be used - even if there's only a single item being queried.
  • -Flatten: When you pull item properties, you may want to use SharePoint's native methods to represent item field values as text. Use this switch to do that.
  • -PropertiesOnly: When you pull a detailed collection through -OutputType, you may want to supress complex objects that do not parse well into strings. This switch allows you to do that.
  • -EnsureContentTypes: A parameter of all commands that interact with lists, this will check to make sure the specified content types are added to the list before performing any other operations. If any are not present, the command will try to add them to the list before continuing.
  • -RequireContentTypes: A parameter of all commands that interact with lists, this will check to make sure the specified content types are added to the list before performing any other operations. If any are not present, the operation will be aborted.
  • -Verbose: Among other things, you can use this switch when you want to see exactly what fields are being requested and returned from SharePoint.

Get-SPOListItem Examples

Here's a basic example:

PS C:\Users\thomas.carpe> Get-SPOListItem -ParentList Documents
WARNING: Neither -All nor -Identity was specified. Was this on purpose? Defaulting to -All
7 total items; page size 4000; iterating through 1 pages.
Processing page number 0.
Returned 7 items.

ClientObject : Microsoft.SharePoint.Client.ListItem
FSOType      : File
PipeBinder   : LiquidMercury.SharePoint.Client.PowerShell.Piping.SPOListItemPipeBind
ID           : 1
Title        : ExampleFile1.txt

As you can see, by default the command returns a collection of objects which has many different representations of a SharePoint list item. This is done to effectively mask "type initializer" issues which are common in CSOM when you attempt to display a ClientObject's properties before they've been loaded.

While CloudPower does pre-populate many properties of the ListItem object, PowerShell will actually try to crawl and display every property, which causes it to blow up when you pipe the output to the screen such as with fl (Format-List) as shown above. Since all command output will be sent to the host unless you assign it to a variable, this was our approach for preventing many common error caused by improper use of the commands.

It's a bit of a nuisence, but better than the alternative. From here, you'd access ClientObjet or PipeBinder properties as needed in order to suit your purposes. You could also assign it to a variable or add a parameter like "-OutputType UniqueID" to your command to prevent it from enumerating these uninitialized properties.

PS C:\Users\thomas.carpe> Get-SPOListItem -ParentList Documents -OutputType UniqueID
WARNING: Neither -All nor -Identity was specified. Was this on purpose? Defaulting to -All
7 total items; page size 4000; iterating through 1 pages.
Processing page number 0.
Returned 7 items.

PS C:\Users\thomas.carpe> $items = Get-SPOListItem -ParentList Documents -OutputType ClientObject
WARNING: Neither -All nor -Identity was specified. Was this on purpose? Defaulting to -All
7 total items; page size 4000; iterating through 1 pages.
Processing page number 0.
Returned 7 items.
PS C:\Users\thomas.carpe>

Returning Some or All Fields for Requested List Items

To include all the fields returned in the primary output hash table, change -OutputType to PsObjectDetailed.

Get-SPOListItem -All -ParentList Documents -OutputType PsObjectDetailed

The ViewFields propety of the -QueryOptions parameter accepts an array of fields. Use it to specify what fields you want returned for each item. If you don't specify a value, the default set will be determined based on whether you are querying a list or document library.

Get-SPOListItem -All -ParentList Documents -QueryOptions @{ "ViewFields" = @("ID","Title") } -OutputType ClientObject

-QueryOptions.ViewFields accepts an array, so you can pass in any number of fields using the @( "field1", "field2" ) syntax. Thanks to the magic of PowerShell, you can also pass in a string and it'll be converted - assuming you only want one field. The most useful application for this is passing in the "all" reserved value, like so:

Get-SPOListItem -All -ParentList Documents -QueryOptions @{ "ViewFields" = @("all") }

These reserved words are not case-sensitive and can be provided in all lowercase letters, uppercase, or mixed. "All", "ALL", and "all" should each be equally valid.

Use the -Verbose switch parameter to see what fields are requested and what's being returned from SharePoint.

Finding a Single List Item by Identifier

Of coure, you don't have to get all items in the List. You can retrieve just one by using the -Identity parameter. This is a pipe binder, which means it can take multiple kinds of input. For example, you can set -ID 3 to get the List Item with ID equal to 3.

Like other PowerShell commands that accept a pipe binder, -Identity can be used to retrieve a single List Item. In this case -Identity accepts any input that would allow you to uniquely identify the List Item within a List. Like the example above, that would most commonly be the ID for the List Item. -Identity also recognizes an instance of a ListItem object, a Unique ID (guid), Url, and matching criteria to lookup the item based on a field value.

# Gets the list item with ID == 18 and saves it's ClientObject to a variable
$item = Get-SPOListItem -ParentList Categories -Identity 18 -OutputType ClientObject

Finding a Single List Item by Field Value

-Identity can also work a lot like -WhereMatch, except that it can only return a single Item from the List. You should be sure that the values you provide will result in only a single item being found, because you'll get an error if multiple items match your query. For this reason, only "Eq" operations are allowed; the other operations are much too likely to pull multiple items.

Here's an example where we'll look up an Item with a specific value for the Title field:

# An example pipe binder constructed from a simple hash table of properties
$find = @{
    "FieldName" = "Title";
    "FieldValue" = "Test Category's Boss";
    ## "FieldType" = "TEXT"; # default
# Gets the list item and saves it's ClientObject to a variable
$item = Get-SPOListItem -ParentList Categories -Identity $find -OutputType ClientObject

Get Multiple Items Using -WhereMatch

-WhereMatch is a lot like -Identity, except that you have more choices about what criteria to use, since multiple items are allowed.

You can populate -WhereMatch with a very simple CAML query by providing a Hashtable with 4 values as shown above under the section on essential parameters.

# An example of how to use -WhereMatch
$where = @{
    "FieldName" = "Title";
    "Operator" = "!=";
    "FieldValue" = "Not a title that we want.";
    ## default "FieldType" = "TEXT";
$item = Get-SPOListItem -ParentList Documents -WhereMatch $where

Working with an Item Query Rule Set

You can return multiple items, each with their own complex criteria for matching, using a Query Rule set. These are provided in the -QueryRules parameter and are generally imported from a CSV file.

See this example CSV file:

Title,Old Title 1,,Foo,Bar,New Title 1
Title,Old Title 2,,Bar,Foo,New Title 2
Title,PowerPoint Template,Contains,[KEEP],[KEEP],[KEEP]
FileRef,/Sample Folder/,Contains,[KEEP],[KEEP],[KEEP]

The above file was generated easily using Microsoft Excel.

And here is script that makes use of the above data file. Note that using -Verbose will let us see how the multiple rules are applies and concatinated.

#Example command to import and use the above CSV file.
$data = Import-Csv .\Content\Set-SPOListItem-TestData1.csv
Get-SPOListItem -ParentList Documents -QueryRules $data -Verbose

Ordering Returned Results

The order of the query can be specified using the -QueryOptions parameter. This parameter accepts a hashtable with some nested collections. The Order option is a nested Hashtable under -QueryOptions, and each item in the hashtable should have a field name as its key and either "Ascending" or "Descending" as its value. You can substitue "asc" and "desc" as needed, and you can provide CAML.SortType values instead of strings if you want. Anything that isn't properly parsed, including nulls and empty strings, will be interpreted as "Ascending".

2016-11-27: as of the most recent build, this was known to not be working correctly, and results were coming back in no particular order. We've investigated this and determined that the issue is caused by a two-part design flw. The first cause of the problem is that the hashtable/dictionary doesn't add its items in the same order they were added to it; the second issue is that the results returned are stored in an unordered generic List. We'll need to create multiple sorted collections to make this work as intended, so bear with us while we work things out.

# Added here in reverse order from how we expect them to appear in CAML XML, due to the known issue described above. Doesn't help enough, because results collection is unsorted too.
$options = @{
  "Order" = @{
    "ID" = "Desc";
    "FileLeafRef" = "Asc"
Get-SPOListItem -ParentList Documents -Verbose -QueryOptions $options

Custom CAML Queries

You aren't limited to getting either 1 item or all of them. You can use the -WhereXml parameter to specify acustom query. Of course, you'll have to understand CAML to create the right syntax. In the future we plan to create some helper commandlets to make this a bit easier.

Retrieve ALL THE THINGS!!!!

Here's an example that will pull all documents and all fields.

$options = @{
  "ViewFields" = @( "all" );
Get-SPOListItem -All -ParentList Documents -OutputType PsObjectDetailed -QueryOptions $options -Verbose

"all", "default", "defaultdoclib", and "defaultlist" are special values that CloudPower understands to be shorthand for a list of certain fields. In this case "all" tells the command to return every field, which is the equivalent to not providing any <ViewFields> clause in the underlying CAML query.

Here's just one item in the collection returned by the above query. You can see we get a lot of useful information to work with.

ContentTypeId              : 0x0101002C05E86F81416D47B5AEB32B8587B1F0
_ModerationComments        :
FileLeafRef                : LMS Double-sided Print Proposal Template 1.docx
Modified_x0020_By          : i:0#.f|membership|
Created_x0020_By           : i:0#.f|membership|
File_x0020_Type            : docx
HTML_x0020_File_x0020_Type :
_SourceUrl                 :
_SharedFileIndex           :
Title                      :
TemplateUrl                :
xd_ProgID                  :
xd_Signature               :
PublishingStartDate        :
PublishingExpirationDate   :
_ShortcutUrl               :
_ShortcutSiteId            :
_ShortcutWebId             :
_ShortcutUniqueId          :
SharedWithUsers            :
SharedWithDetails          :
ID                         : 26
Created                    : 10/6/2016 9:29:00 AM
Author                     : Microsoft.SharePoint.Client.FieldUserValue
Modified                   : 10/7/2016 8:42:45 AM
Editor                     : Microsoft.SharePoint.Client.FieldUserValue
_HasCopyDestinations       :
_CopySource                :
_ModerationStatus          : 0
FileRef                    : /Documents/Sample Folder/LMS Double-sided Print Proposal Template 1.docx
FileDirRef                 : /Documents/Sample Folder
Last_x0020_Modified        : 2016-10-07T08:42:45Z
Created_x0020_Date         : 2016-10-06T09:29:00Z
File_x0020_Size            : 437956
FSObjType                  : 0
SortBehavior               : Microsoft.SharePoint.Client.FieldLookupValue
CheckedOutUserId           : Microsoft.SharePoint.Client.FieldLookupValue
IsCheckedoutToLocal        : 0
CheckoutUser               :
UniqueId                   : f3a655d4-18f1-432d-ae00-2e215b70c269
SyncClientId               : Microsoft.SharePoint.Client.FieldLookupValue
ProgId                     :
ScopeId                    : {4C52C31F-4F94-44A0-B810-26CA6266A362}
VirusStatus                : Microsoft.SharePoint.Client.FieldLookupValue
CheckedOutTitle            : Microsoft.SharePoint.Client.FieldLookupValue
_CheckinComment            :
MetaInfo                   : vti_thumbnailexists:BW|false
                             vti_stickycachedpluggableparserprops:VX|Subject Keywords _Status PublishingExpirationDate
                             PublishingStartDate vti_title _Author _Category ContentType ContentTypeId _dlc_DocId
                             _Comments _dlc_DocIdItemGuid _dlc_DocIdUrl
                             _Author:SW|Thomas Carpe
                             s/DocIdRedir.aspx?ID=37J4DJEDPX5C-170-132, 37J4DJEDPX5C-170-132