Category: Items

  • How to Create SharePoint List Items with MS Graph API: A Step-by-Step Guide

    In this article I’ll elaborate how to create SharePoint List Items with MS Graph API. You might have use cases, which require the automatic list item creations – example: Your customer is providing feedback and you want to process it in SharePoint to integrate it to other tools like PowerAutomate.

    In my current engagement, I am populating demo data to our rollout automation tool. Using a programmatic approach ensures that the demo data is provided equally for every new demo.

    Following endpoint is used to create SharePoint List Items:

    POST /sites/{site-id}/lists/{list-id}/items
    

    In this article, I’ll walk you through the approach, which enables you to use the endpoint. To call the provided endpoint, following four steps need to be followed:

    • Obtain bearer token: The bearer token is required to authenticate with Microsoft Graph API.
    • Obtain Site ID: Based on the site name, the site id is getting obtained, which is required for the list item creation with MS Graph
    • Obtain List ID: the List ID is required to specify the list in which the SharePoint list item shall be created. The ID will be fetched by the specification of the list title.

    Prerequisites to Create SharePoint List Items with MS Graph

    In order to create SharePoint List items with MS Graph, following prerequisites are required:


    Your App Registration should look like this in terms of granted permissions:

    Obtain Bearer Token to create SharePoint List Items with MS Graph API

    In order to obtain the bearer token, you need to conduct a POST call for the endpoint /oauth2/v2.0/token.

    You can use the script below, to obtain a bearer token. Make sure to provide your SharePoint tenant name (https://tenantname.sharepoint.com) and the app ID of your app registration in the parameters.

    param (
        [string]$Tenant = "m365x16735261",
        [string]$AppID = "39180af4-ad90-442f-a4ca-028b9221b133"
    )
    
    $AppCredential = Get-Credential ($AppID)
    
    # Define the required scope for accessing the Microsoft Graph API
    $Scope = "https://graph.microsoft.com/.default"
    
    # Prepare the body for the token request with client ID, client secret, and scope
    $Body = @{
        client_id     = $AppCredential.UserName                     # Client ID from app registration
        client_secret = $AppCredential.GetNetworkCredential().password   # Securely retrieve the client secret
        scope         = $Scope                                         # API scope required for MS Graph API access
        grant_type    = 'client_credentials'                      # Grant type for app-only authentication
    }
    
    # Azure AD endpoint to request an OAuth token
    $GraphUrl = "https://login.microsoftonline.com/$($Tenant).onmicrosoft.com/oauth2/v2.0/token"
    
    try
    {
        # Request the access token from Azure AD
        $AuthorizationRequest = Invoke-RestMethod -Uri $GraphUrl -Method "Post" -Body $Body
        # Retrieve the access token from the response
        $Access_token = $AuthorizationRequest.Access_token
        Write-Output $Access_token
    }
    catch
    {
        # Handle authentication errors, if any
        Write-Error "Error during token retrieval: $_"
        return $null
    }

    When running the code, you’ll get prompted for the app secret. Once you have executed the code, you’ll receive following output with the bearer access token:

    Obtain Site ID to create SharePoint List Items with MS Graph API

    With the bearer token, you can obtain the Site ID. You can obtain the Site ID by running the code below – make sure to update the parameters Hostname and ServerRelativePath.

    Param (
        # The API version of MS Graph
        $ApiVersion = "v1.0",
    
        # hostname of the tenant
        $HostName = "m365x16735261.sharepoint.com",
        
        # The relative path of the site, beginning with /sites/, /teams/, or another valid site type path.
        $ServerRelativePath = "sites/GraphSite1"
    
    )
    
    # Set the Authorization header with the bearer token for API requests
    $Header = @{
        Authorization  = "Bearer $Access_token"              # Bearer token for API authorization
        "Content-Type" = "application/json"                 # JSON content type for the request body
    }
    
    #Obtain the SiteID of the Site
    
    $Url = "https://graph.microsoft.com/$ApiVersion/sites/${HostName}:/$ServerRelativePath"
    $Site = Invoke-RestMethod -Uri $Url -Headers $Header
    Write-Output $Site

    Once you execute the script, you should see a similar output:

    Obtain List ID to create SharePoint List Items with MS Graph API

    As we were able to obtain the Site ID, we can now obtain the List ID in which we want to create SharePoint List Items. In the script below, I am obtaining the SharePoint List “Tools2”. Make sure to update Parameters, so that you get the list, in which you want to create the SharePoint List Items.

    Param (
        # The API version of MS Graph
        $ApiVersion = "v1.0",
    
        # The displayname of the List
        $ListTitle = "Tools2"
    )
    
    # Set the Authorization header with the bearer token for API requests
    $Header = @{
        Authorization  = "Bearer $Access_token"              # Bearer token for API authorization
        "Content-Type" = "application/json"                 # JSON content type for the request body
    }
    
    #Obtain the listID of the list
    
    $Url = "https://graph.microsoft.com/$ApiVersion/sites/$($Site.id)/lists/$ListTitle"
    $List = Invoke-RestMethod -Uri $Url -Headers $Header
    Write-Output $List

    Create SharePoint List Items with MS Graph API

    In order to create SharePoint List Items with Graph API, you need to specify how your items shall look like. You can do this by defining a Body as a JSON as per your list. In my List I have two columns in place: Title [string], NumberOfOffices [Integer], Blank Character Attribute [string].

    For that reason the body of my SharePoint List Item looks like this:

    $Body = @{
        fields = @{
            Title = "ListItemTest1"
            NumberOfOffices = 1
            BlankCharacterAttribute = "TEST"
        }
    }

    Note: Make sure that you take the internal name of your columns. You can do it by browsing to the column settings of your SharePoint List column.

    Now as we have all three components: Bearer Token, Site ID and ListID, we can create SharePoint List Items with MS Graph API:

    # The API version of MS Graph
    $ApiVersion = "v1.0"
    
    # The displayname of the List
    $ListTitle = "Tools2"
    
    
    # Set the Authorization header with the bearer token for API requests
    $Header = @{
        Authorization  = "Bearer $Access_token"              # Bearer token for API authorization
        "Content-Type" = "application/json"                 # JSON content type for the request body
    }
    
    
    # Define the list item properties for the new list creation request
    $Body = @{
        fields = @{
            Title = "ListItemTest1"
            NumberOfOffices = 1
            BlankCharacterAttribute = "TEST"
        }
    }
    
    # Set the endpoint URL for creating a list item in Microsoft Graph API
    $Url = "https://graph.microsoft.com/$ApiVersion/sites/$($Site.id)/lists/$($List.id)/items"
    
    # Convert the list item properties to JSON format required for the API request
    $BodyJSON = $Body | ConvertTo-Json -Compress -Depth 3
     
    # Send the HTTP POST request to create the list items with the defined properties
    $Response = Invoke-RestMethod -Uri $Url -Headers $Header -Method Post -Body $BodyJSON
    # Output the ID of the newly created list for confirmation
    Write-Output "List Item $BodyJSON created successfully"
    Write-Output $Response

    Once you run the script, you’ll get a similar output like this:

    Ready-to-Use PowerShell Script: Create SharePoint List Items with MS Graph

    Enclosed you’ll find a ready-to-use PowerShell script to create SharePoint List Items with MS Graph. Make sure to update the parameters of the script as explained before and also to adjust the $ItemBody hashtable, so that the list items are created as per your preference.

    # Define parameters for the tenant, application ID, site name, and mail nickname
    Param (
        # The API version of MS Graph
        $ApiVersion = "v1.0",
    
        # The Azure AD tenant ID for authentication
        $Tenant = "m365x16735261", 
    
        # The Application (client) ID of the registered Entra ID application registration, which is supposed to create SharePoint List (TenantAdminApp)
        $TenantAdminAppID = "3342565c-dca1-4b55-b107-7aa0e2f7bfd6",   
    
        # hostname of the tenant
        $HostName = "m365x16735261.sharepoint.com",
    
        # The relative path of the site, beginning with /sites/, /teams/, or another valid site type path.
        $ServerRelativePath = "sites/GraphSite1",
        
        # The displayname of the List
        $ListTitle = "Tools2"
    )
    
    function Get-GraphToken {
        param (
            [string]$Tenant,
            [PSCredential]$AppCredential
        )
        
        # Define the required scope for accessing the Microsoft Graph API
        $Scope = "https://graph.microsoft.com/.default"
    
        # Prepare the body for the token request with client ID, client secret, and scope
        $Body = @{
            client_id = $AppCredential.UserName                     # Client ID from app registration
            client_secret = $AppCredential.GetNetworkCredential().password   # Securely retrieve the client secret
            scope = $Scope                                         # API scope required for MS Graph API access
            grant_type = 'client_credentials'                      # Grant type for app-only authentication
        }
    
        # Azure AD endpoint to request an OAuth token
        $GraphUrl = "https://login.microsoftonline.com/$($Tenant).onmicrosoft.com/oauth2/v2.0/token"
    
        try {
            # Request the access token from Azure AD
            $AuthorizationRequest = Invoke-RestMethod -Uri $GraphUrl -Method "Post" -Body $Body
            # Retrieve the access token from the response
            return $AuthorizationRequest.Access_token
        } catch {
            # Handle authentication errors, if any
            Write-Error "Error during token retrieval: $_"
            return $null
        }
    }
    
    #region authentication - obtain bearer token
    while ($null -eq $TenantAdminAppCredential)
    {
        $TenantAdminAppCredential = Get-Credential -UserName $TenantAdminAppID -Message "Enter the client secret for the app TenantAdminAppID $TenantAdminAppID"
    }
    
    # Call the Get-GraphToken function and store the result
    $Access_token = Get-GraphToken -Tenant $Tenant -AppCredential $TenantAdminAppCredential
    
    # Check if access token is successfully obtained
    if (-not $Access_token) 
    {
        Write-Error "Failed to retrieve access token. Exiting script."
        return
    }
    
    # Set the Authorization header with the bearer token for API requests
    $Header = @{
        Authorization  = "Bearer $Access_token"              # Bearer token for API authorization
        "Content-Type" = "application/json"                 # JSON content type for the request body
    }
    Write-Output "Access token retrieved successfully."
    #endregion
    
    #Obtain the SiteID of the Site
    
    $Url = "https://graph.microsoft.com/$ApiVersion/sites/${HostName}:/$ServerRelativePath"
    $Site = Invoke-RestMethod -Uri $Url -Headers $Header
    
    #Obtain the listID of the list
    
    $Url = "https://graph.microsoft.com/$ApiVersion/sites/$($Site.id)/lists/$ListTitle"
    $List = Invoke-RestMethod -Uri $Url -Headers $Header
    
    #region create list item
    
    # Define which values your SharePoint List items shall contain
    $ItemBody = @{
        fields = @{
            Title = "ListItemTest"
            NumberOfOffices = 1
            BlankCharacterAttribute = "TEST"
        }
    }
    
    # Set the endpoint URL for creating a list item in Microsoft Graph API
    $Url = "https://graph.microsoft.com/$ApiVersion/sites/$($Site.id)/lists/$($List.id)/items"
    
    # Convert the list item properties to JSON format required for the API request
    $BodyJSON = $ItemBody | ConvertTo-Json -Compress -Depth 3
     
    try
    {
        # Send the HTTP POST request to create the list item with the defined properties
        $response = Invoke-RestMethod -Uri $Url -Headers $Header -Method Post -Body $BodyJSON
        # Output the ID of the newly created list item for confirmation
        Write-Output "List item $BodyJSON created successfully"
        Write-Output $response
    }
    catch
    {
        # Handle errors that may occur during the list creation request
        Write-Error "Failed to create list item: $_"
    }
    #endregion

    I hope this article helped you to create SharePoint List Items with MS Graph. For which use cases are you looking forward to create SharePoint List Items? Let us connect on LinkedIn:
    Serkar Aydin | LinkedIn

    References

    Here you can find the official reference from Microsoft, which elaborates on the POST endpoint to create SharePoint List Items:
    Create a new entry in a SharePoint list – Microsoft Graph v1.0 | Microsoft Learn

  • Create SharePoint list items using Graph API (PNP.PowerShell)

    Create SharePoint list items using Graph API (PNP.PowerShell)

    In this article, I want to show you how you can create SharePoint list items using Graph API.

    Prerequistes

    Step 1: Configure the Azure Enterprise Application

    I am following the least privilege approach and grant only the necessary permission for the app registration to create SharePoint list items using Graph API.

    Hence, I have created an App registration with following permissions:

    Permission NameType
    Sites.Selected Application
    User.ReadDelegated
    Application Registration in Microsoft Azure for reading SharePoint List Items

    If you don’t know how to create it, follow my next steps, otherwise if you are familiar with it, you can also skip to the Step 2 – Grant the Enterprise Application the Permission.

    1. Browse to Azure Portal and Search for Application Registrations and click on New registration

    Create a new Azure App registration Screenshot

    2. Give the App a meaningful name, which follows your organization standards (Different admins should recognize what the purpose for this app is) and Register it

    Registration of new App registration in Azure Portal

    3. Note down the Application ID and go to Certificates & Secrets

    Display of Application Registration in Azure Portal

    4. Create a new client secret or upload a certificate (I will show the secret approach)

    Creation of new client secret in Azure Portal

    5. Also, here a meaningful name is supportive for other colleagues. For the duration, it makes sense to go with a reasonable duration. I would go with the recommendation of Microsoft as you might have lost this application out of sight in 24 months, which is the maximum duration for a client secret.

    Creation of client secret for an App registration


    6. Now you will have ONE chance to note down the client secret. Treat it like a password. Depending on your App Permission your App might be powerful. Hence you should save for instance in a Password Manager.

    Client Secret Exposure for App registration

    7. Now Click on API permissions on the left navigation pane and add a permission for Microsoft Graph

    Adding Permission for Microsoft Graph

    8. Add the Application Permission Sites.Selected if you want the code run in the background without a signed-in user.

    API Permission for Application Permissions
    Sites.Selected Graph Permissions

    9. Once you added that, you will need to consent the permission from a global administrator.

    Not granted permissions for sites.selected

    Granted permissions look like this:

    Granted app registration permissions

    That’s it. You created an Azure App registration with Sites.Selected permission, where you need now to grant the permissions for the specific site.

    Step 2: Grant Enterprise application write permissions for SharePoint site

    For this step, you need to ensure that PNP Module is installed on your client and that you are allowed to use it.

    If both conditions are applying, you can use this code to grant Enterprise App, created in Step 1 the right permission for the site. In this case, I am granting a write role.

    Import-Module PnP.PowerShell
    
    $AppID = "9ea2120f-288c-47b6-8895-31e0fb4d9211"
    
    $DisplayNameofSitePermission = "Enterprise Application SP_Access_SharePoint_List_SalesAndMarketing_Write"
    $SiteURL = "https://m365x323732.sharepoint.com/sites/SalesAndMarketing"
    
    
    Connect-PnPOnline -Url $SiteURL -Interactive
    Grant-PnPAzureADAppSitePermission -AppId $AppID -DisplayName $DisplayNameofSitePermission -Site $SiteURL -Permissions Write

    You will need to log in with an account, which has access to the site.

    After that you will see, that the Enterprise Application has now write access to the Site.

    Screenshot of write permissions for Enterprise Application to create SharePoint list items using Graph API

    Step 3: Create SharePoint list items using Graph API with PowerShell

    As the enterprise application has now the permission to write contents to the designated SharePoint Site, you are able create SharePoint list items using Graph API.

    For this we need the app credentials and the site id of the site in which you want to create SharePoint list items using Graph API.

    Param (
        $AppID = "9ea2120f-288c-47b6-8895-31e0fb4d9211",
        $Scope = "https://graph.microsoft.com/.default",
        $Tenant = "m365x323732",
        $SiteID = "e35cee33-6d10-4e2c-a83b-496a26062ad3",
        $ListTitle = "Product%20List"
    )
    
    Import-Module PnP.PowerShell
    $AppCredential = Get-Credential($AppID)
    
    
    #region authorize
    $Body = @{
        client_id = $AppCredential.UserName
        client_secret = $AppCredential.GetNetworkCredential().password
        scope = $Scope
        grant_type = 'client_credentials'
    }
    $GraphUrl = "https://login.microsoftonline.com/$($Tenant).onmicrosoft.com/oauth2/v2.0/token"
    $AuthorizationRequest = Invoke-RestMethod -Uri $GraphUrl -Method "Post" -Body $Body
    $Access_token = $AuthorizationRequest.Access_token
    
    $Header = @{
        Authorization = $AuthorizationRequest.access_token
        "Content-Type"= "application/json"
    }
    #endregion
    
    
    #region create items
    
    $Body = @{
    	fields = @{
    		Title = "Test"
    	}
    }
    
    
    $GraphUrl = "https://graph.microsoft.com/v1.0/sites/$SiteID/lists/$ListTitle/items"
    
    
    $BodyJSON = $Body | ConvertTo-Json -Compress
    Invoke-RestMethod -Uri $GraphUrl -Method 'POST' -Body $BodyJSON -Headers $Header -ContentType "application/json" 
    
    
    #endregion 

    As you can see the item with the title Test was created in the SharePoint List Product List.

    Screenshot of the result "create SharePoint list items using Graph API"

    Further Reference

    3 of the most important SharePoint PowerShell Modules and Snappins

    Access SharePoint via Graph API in PowerShell

    Add items to SharePoint Online lists with Powershell

    Microsoft Graph overview – Microsoft Graph | Microsoft Learn

    Working with SharePoint sites in Microsoft Graph – Microsoft Graph v1.0 | Microsoft Learn

  • How to get SharePoint List Items with Graph API (PowerShell)

    How to get SharePoint List Items with Graph API (PowerShell)

    In this article, I want to show you how to get SharePoint List Items with Graph API. Sometimes we are limited to the tools we can use, so we need to think about other approaches, to get our aim delivered. In this article, I want to show you how you can get SharePoint List items with the Microsoft Graph API by using PowerShell.

    To get SharePoint List Items with Graph API, you can follow the next three steps:

    1. Configure the Azure Enterprise Application
    2. Grant the Enterprise Application the Permission
    3. Get SharePoint List Items with Graph API in PowerShell

    Prerequistes

    Step 1: Configure the Azure Enterprise Application

    I am following the least privilege approach and grant only the necessary permission for the app registration.

    Hence I have created an App registration with following permissions:

    Permission NameType
    Sites.Selected Application
    User.ReadDelegated
    Application Registration in Microsoft Azure for reading SharePoint List Items

    If you don’t know how to create it, follow my next steps, otherwise if you are familiar with it, you can also skip to the Step 2 – Grant the Enterprise Application the Permission.

    1. Browse to Azure Portal and Search for Application Registrations and click on New registration

    Create a new Azure App registration Screenshot

    2. Give the App a meaningful name, which follows your organization standards (Differnt admins should recognize what the purpose for this app is) and Register it

    Registration of new App registration in Azure Portal

    3. Note down the Application ID and go to Certificates & Secrets

    Display of Application Registration in Azure Portal

    4. Create a new client secret or upload a certificate (I will show the secret approach)

    Creation of new client secret in Azure Portal

    5. Also here a meaningful name is supportive for other colleauges. For the duration it makes sense to go with a reasonable duration. I would go with the recommendation of Microsoft as you might have lost this application out of sight in 24 months, which is the maximum duration for a client secret.
    Creation of client secret for an App registration
    6. Now you will have ONE chance to note down the client secret. Treat it like a password. Depending on your App Permission your App might be powerful. Hence you should save for instance in a Password Manager.
    Client Secret Exposure for App registration

    7. Now Click on API permissions on the left navigation pane and add a permission for Microsoft Graph

    Adding Permission for Microsoft Graph
    8. Add the Application Permission Sites.Selected if you want the code run in the background without a signed-in user.
    API Permission for Application Permissions
    Sites.Selected Graph Permissions
    9. Once you added that, you will need to consent the permission from a global administrator.
    Not granted permissions for sites.selected
    Granted permissions look like this:
    Granted app registration permissions

    That’s it. You created an Azure App registration with Sites.Selected permission, where you need now to grant the permissions for the specific site.

    Step 2: Grant the Enterprise Application the Permission

    For this step you need to ensure that PNP Module is installed on your client and that you are allowed to use it.

    If both conditions are appliying, you can use this code to grant Enterprise App, created in Step 1 the right permission for the site. In this case I am granting a read role.

    Import-Module PnP.PowerShell
    
    $AppID = "9ea2120f-288c-47b6-8895-31e0fb4d9211"
    
    $DisplayNameofSitePermission = "Enterprise Application SP_Access_SharePoint_List_SalesAndMarketing"
    $SiteURL = "https://m365x323732.sharepoint.com/sites/SalesAndMarketing"
    
    
    Connect-PnPOnline -Url $SiteURL -Interactive
    Grant-PnPAzureADAppSitePermission -AppId $AppID -DisplayName $DisplayNameofSitePermission -Site $SiteURL -Permissions Read 

    You will need to log in with an account, which has access to the site.

    After that you will see, that the Enterprise Application has now read access to the Site.

    Screenshot of PowerShell, which indicates that Site Access is now working

    Step 3: Get SharePoint List Items with Graph API in PowerShell

    As the enterprise application has now the permission to read contents from the designated SharePoint Site, you are able to read the contents of the SharePoint Site.

    For this we need the app credentials and the site id of the site for which you want to read out the content.

    <siteurl>/_api/site/id

    For my example it is:

    https://m365x323732.sharepoint.com/sites/SalesAndMarketing/_api/site/id

    Screenshot of the SharePoint site Id

    Once you adjusted the parameters, you can run the script

    Param (
        $AppID = "9ea2120f-288c-47b6-8895-31e0fb4d9211",
        $Scope = "https://graph.microsoft.com/.default",
        $Tenant = "m365x323732",
        $SiteID = "e35cee33-6d10-4e2c-a83b-496a26062ad3",
        $ListTitle = "Product%20List"
    )
    
    Import-Module PnP.PowerShell
    
    
    $AppCredential = Get-Credential($AppID)
    
    #region authorize
    
    $Body = @{
        client_id = $AppCredential.UserName
        client_secret = $AppCredential.GetNetworkCredential().password
        scope = $Scope
        grant_type = 'client_credentials'
    }
    
    $GraphUrl = "https://login.microsoftonline.com/$($Tenant).onmicrosoft.com/oauth2/v2.0/token"
    $AuthorizationRequest = Invoke-RestMethod -Uri $GraphUrl -Method "Post" -Body $Body
    $Access_token = $AuthorizationRequest.Access_token
    
    $Header = @{
    
        Authorization = $AuthorizationRequest.access_token
    }
    
    #endregion
    
    #region get items
    
    $GraphUrl = "https://graph.microsoft.com/v1.0/sites/$SiteID/lists/$ListTitle/items?expand=fields"
    
    $Items  = Invoke-RestMethod -Uri $GraphUrl -Method 'GET' -Body $Body -Headers $Header
    $Items.value.fields
    #endregion 
    get SharePoint List Items with Graph API

    Further reference

    To understand how Microsoft Graph API works, check out this article from Microsoft:
    Use the Microsoft Graph API – Microsoft Graph | Microsoft Learn

    You might also be interested in getting all SharePoint lists with PowerShell
    SharePoint Online: How to get all lists and libraries (workplace-automation.com/)

  • Filtering for SharePoint items with CAML Queries

    Filtering for SharePoint items with CAML Queries

    Most of our times, we just need just a bunch of items, to export them or to change their values. This post should help you to show, how to handle filtering for SharePoint items. Besides filtering for SharePoint items with Where-Object, you can also make use of CAML (Collaborative Application Markup Language), which lets you get only the items, you need. It might increase the performance of your queries, when you are dealing with large amounts of data.

    Where are the items, which I am looking for?

    Preqrequistes

    If we want to achieve filtering for SharePoint items, with a CAML query, we have to fulfill following prerequisites:

    1. Permissions to access the list
    2. Installed Module PNP.Powershell. If you don’t know how to, check the post.
    3. Connection to the site via PNP.PowerShell. If you don’t know how to, check the post.

    Considerations

    1. You should take care of the case sensitivity of operands and column names
    2. You should take care of the <view> part. Sometimes it is needed, sometimes not – so I would rely on the examples.

    Query Schema

    A query is structured like this

     "<View><Query><Where><LOGICAL OPERATOR><FieldRef Name='INTERNAL NAME OF COLUMN'/><Value Type='VALUE TYPE'>VALUE</Value></LOGICAL OPERATOR></Where></Query></View>"

    You can find the internal name of columns in two ways:

    PowerShell or GUI.

    Explanation for PowerShell: Getting FieldValues of Items | SPO Scripts
    Explanation for GUI: Determine internal name of SharePoint Columns with GUI (workplace-automation.com/)

    Value types

    TypeMeaningExamples
    BooleanIt means true or false. You can find this in yes/no checkboxestrue, false
    true reflects 1
    false reflects 0
    ChoiceIt reflects the choices in your sharepoint listapple, banana
    CurrencyIt reflects the amount of an defined currency5$
    DateTimeIt reflects a timestamp23.06.2021 15:30
    GUIDGlobally Unique Identifier (GUID)6154ff96-8209-457b-86dd-ee7dcd80b584
    IntegerIt reflects a number as an integer 10
    LookupLinks to another list: for example an Orders list may have a lookup field that links to customers in a Customer list;Füller AG
    NoteReflects a multi line text field. Not sortable or groupableLorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio.

    Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.
    TextReflects a single line text field. Sortable and groupable. Corresponds to the nvarchar SQL data type and represented by the SPFieldText class.Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
    UserA Lookup field that references the UserInfo database table.Email TypeId LookupId LookupValue
    —– —— ——– ———–
    Serkar@devmodernworkplace.onmicrosoft.com {c956ab54-16bd-4c18-89d2-996f57282a6f} 11 Serkar Aydin
    Source: Field element (Field) | Microsoft Docs

    Logical Comparison Operators

    In this case X means your entry

    OperatorMeaning
    BeginsWithThe existing value begins with X
    ContainsThe existing value contains x
    DateRangesOverlapThe existing date overlaps the date range defined in x
    |---- 01.01.-07.01 ------|
    |---02.01-09.01 -----|
    EqThe existing value equals x
    GeqThe existing value is greater or equal x
    GtThe existing value is greater than x
    InX is one of the existing values
    Includeschecks, whether x is in the defined values
    NotIncluseschecks, whether x is not in the defined values
    IsNotNullChecks wheter the existing value is not null
    IsNullChecks wheter the existing value is null
    LeqThe existing value is lower equal x
    LtThe existing value is lower than x
    Source: Query schema in CAML | Microsoft Docs

    In order to filter by query paramter, you have to define a filter query, depending on your datatype (string, integer, boolean..) you have to choose a different query value type.

    Logical Joins

    OperatorMeaning
    AndBoth query operations have to be fulfilled
    OrOnly one query operation have to be fulfilled
    Source: Query schema in CAML | Microsoft Docs

    Query Examples

    My blog would not keep it’s promise, If you would not find examples, which give you a fast way to adapt the scripts, so here we go!

    In my example, I am using my demo opportunities list. I have marked the names of the columns, the value types, the operands and the actual values bold. Mostly I am using the logical operator “eq”, but I think if you got the basic concept of this, you can adapt it to your solution easily and if not, we will find a way together.

    Example for boolean

    If you want to find items with TRUE values, you have to enter 1. For FALSE values, you have to make use of 0.

    If boolean should be true:

    Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Eq><FieldRef Name='Win'/><Value Type='Boolean'>1</Value></Eq></Where></Query></View>"

    If boolean should be false:

    Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Eq><FieldRef Name='Win'/><Value Type='Boolean'>0</Value></Eq></Where></Query></View>" 

    Example for choice

    If you want to filter for values choice values, you have to make use of a query like this:

    Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Eq><FieldRef Name='Product'/><Value Type='Choice'>SAP</Value></Eq></Where></Query></View>"

    Example for currency

    You have to enter the value of the amount without the currency sign.

    Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Eq><FieldRef Name='DealSize'/><Value Type='Currency'>40000</Value></Eq></Where></Query></View>"

    Example for DateTime

    You have to format date times according to this format (ISO8601).

    yyyy-MM-ddTHH:mm:ssZ

    You can do this by appending -Format s, when creating the variable

    $CreationDate = Get-Date "16.06.2021 20:04" -Format s

    If DateTime should exactly match a specific date

    $CreationDate = Get-Date "16.06.2021 20:04" -Format s
    Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Eq><FieldRef Name='Created'/><Value Type='DateTime' IncludeTimeValue='FALSE'>$CreationDate</Value></Eq></Where></Query></View>"

    If DateTime should be after a specific date

    Example: I want to find all items, created after 15.06.2021.

    $CreationDate = Get-Date "15.06.2021" -Format s
    Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Gt><FieldRef Name='Created'/><Value Type='DateTime' IncludeTimeValue='FALSE'>$CreationDate</Value></Gt></Where></Query></View>"

    If DateTime should be before a specific date

    Example: I want to find all items, created before 15.06.2021.

    Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Lt><FieldRef Name='Created'/><Value Type='DateTime' IncludeTimeValue='FALSE'>$CreationDate</Value></Lt></Where></Query></View>"

    Example for GUID

    [GUID]$UniqueID= "b4ae9e9f-7103-459a-acb2-73573d035b36"
    Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Eq><FieldRef Name='UniqueId'/><Value Type='GUID'>$UniqueID</Value></Eq></Where></Query></View>"

    Example for integer

    In this case I want to find all opportunites with 2 stakeholders.

    Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Eq><FieldRef Name='Stakeholder'/><Value Type='Integer'>2</Value></Eq></Where></Query></View>"

    Example for lookup

    Get-PnPListItem -List "Opportunities" -Query "<Query><Where><Eq><FieldRef Name='Contact'/><Value Type='Lookup'>Sus Spicious</Value></Eq></Where></Query>"

    Example for Note aka multi line text

    Get-PnPListItem -List "Opportunities" -Query "<Query><Where><Eq><FieldRef Name='Notes'/><Value Type='Note'>He was really curious.</Value></Eq></Where></Query>"

    Example for text aka string

    In this Query, I am looking for items, where the title equals Opp 3.

    Get-PnPListItem -List "Opportunities" -Query "<Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>Opp 3</Value></Eq></Where></Query>"

    Example for user

    In this query, I am looking for items, where the authors UPN is Serkar@devmodernworkplace.onmicrosoft.com.

    Get-PnPListItem -List "Opportunities" -Query "<Query><Where><Eq><FieldRef Name='Author' /><Value Type='User'>Serkar@devmodernworkplace.onmicrosoft.com</Value></Eq></Where></Query>"

    Example for OR

    In this query, I am looking for items, where the value for Stakeholder is 1 or the value Win is yes.

    Get-PnPListItem -List $ListName -Query "<View><Query><Where><Or><Eq><FieldRef Name='Stakeholder'/><Value Type='Integer'>1</Value></Eq><Eq><FieldRef Name='Win'/><Value Type='Boolean'>1</Value></Eq></Or></Where></Query></View>"

    Example for AND

    In this query, I am looking for items, where the value for Stakeholder is 1 and the value Win is yes.

    Get-PnPListItem -List $ListName -Query "<View><Query><Where><And><Eq><FieldRef Name='Stakeholder'/><Value Type='Integer'>1</Value></Eq><Eq><FieldRef Name='Win'/><Value Type='Boolean'>1</Value></Eq></And></Where></Query></View>"

    Complete example

    $Url = "https://devmodernworkplace.sharepoint.com/sites/Sales" 
    $ListName = "Opportunities"
    
    Connect-PnPOnline -Url $Url -Interactive
    
    $AmountOfStakeholders = 2
    $ColumName = "Stakeholder"
    
    Get-PnPListItem -List $ListName -Query "<View><Query><Where><Eq><FieldRef Name='$ColumName'/><Value Type='Integer'>$AmountOfStakeholders</Value></Eq></Where></Query></View>"

    Troubleshooting

    I am getting to many items

    Error

    You get nearly every item in the list, but you are filtering for specific SharePoint items

    Cause

    Maybe you forgot the <View> part?

    Resolution

    Without view:

    With view:

    Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Eq><FieldRef Name='Stakeholder'/><Value Type='Integer'>2</Value></Eq></Where></Query></View>"

    Exception from HRESULT: 0x80131904

    Error message:

    Get-PnPListItem : Exception from HRESULT: 0x80131904
    In Zeile:1 Zeichen:1
    + Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><gt ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : WriteError: (:) [Get-PnPListItem], ServerException
        + FullyQualifiedErrorId : EXCEPTION,PnP.PowerShell.Commands.Lists.GetListItem

    Cause:

    You did not care about the case sensitivity of the logical operands

    Resolution:

    Wrong:

    Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><gt><FieldRef Name='Created'/><Value Type='DateTime' IncludeTimeValue='FALSE'>$CreationDate</Value></gt></Where></Query></View>"

    Right:

    Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Gt><FieldRef Name='Created'/><Value Type='DateTime' IncludeTimeValue='FALSE'>$CreationDate</Value></Gt></Where></Query></View>"

    Field types are not installed properly

    Error message in german

    Get-PnPListItem : Mindestens ein Feld ist nicht richtig installiert. Wechseln Sie zur Listeneinstellungsseite, um diese Felder zu löschen.
    In Zeile:1 Zeichen:1
    + Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Gt ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : WriteError: (:) [Get-PnPListItem], ServerException
        + FullyQualifiedErrorId : EXCEPTION,PnP.PowerShell.Commands.Lists.GetListItem

    Error message in english

    Get-PnPListItem : One or more field types are not installed properly. Go to the list settings page to delete these fields.
    In Zeile:1 Zeichen:1
    + Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Gt ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : WriteError: (:) [Get-PnPListItem], ServerException
        + FullyQualifiedErrorId : EXCEPTION,PnP.PowerShell.Commands.Lists.GetListItem

    Cause

    You did not care of the case sensitivity of the column name

    Resolution

    Wrong:

    Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Gt><FieldRef Name='created'/><Value Type='DateTime' IncludeTimeValue='FALSE'>$CreationDate</Value></Gt></Where></Query></View>"

    Right:

    Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Gt><FieldRef Name='Created'/><Value Type='DateTime' IncludeTimeValue='FALSE'>$CreationDate</Value></Gt></Where></Query></View>"

    Bild von Deedee86 auf Pixabay

  • Getting Fieldvalues of Items

    Getting Fieldvalues of Items

    Getting all values of all items

    If you want to retrieve all fieldvalues of an item, you can use following steps. I am getting the opportunities of the sales department

    Screenshot of SharePoint List with values of items
    • Connect to SharePoint Online with PNP. If you don’t know how to, check the post. I am connecting with the sales site

      Connect-PnPOnline -Url "https://devmodernworkplace.sharepoint.com/sites/Sales" -Interactive
    • After connecting, get the list.

      $Items =Get-PnPListItem -List "YourList"

      I am using the list opportunities:

      $Items =Get-PnPListItem -List "Opportunities"

      If you don’t know what the internal name of your list is, you can make use of the cmdlet

      $Items = Get-PNPListItem | Out-Gridview -Passthru
    out grid view with lists

    After getting the items, you can get all fieldvalues like this:
    $Items.Fieldvalues

    Screenshot of all values of items

    Filter items by specific value

    You can filter items like this. You have to use the key, which you get with $Items. FieldValues

    Filter by Where Object

    $Item = $Items | Where-Object {$_.Fieldvalues["KEY"] -eq "VALUE"}

    I filter for items with the title Opp 2

    $Item = $Items | Where-Object {$_.Fieldvalues["Title"] -eq "Opp 2"}

    Filter by -Query Parameter

    I have created a separate post for this. Check it out.

    Getting only specific amount of Items

    It might happen, that your list contains many items. In order to get only 1000 Items, make use of the parameter -PageSize

    Get-PnPListItem -List "Opportunities" -PageSize 1000

    Getting a specific value for specific item

    First get one single item, either by filtering, or by using the index

    You can use indexing with following method

    $Item= $Items[INDEX]

    For the first Item: $Item = $Items[0]

    For the second Item: $Item = $Items[1] etc,

    If you got a single item, you can get the fieldvalues like this:

    $item.FieldValues.KEY

    In my case I use the key “Product”

    $item.FieldValues.Product

    screenshot of specific value

    Or “Contact”

    screenshot of specific contact value

    Example script to get all fieldvalues for all items

    $Url = "https://devmodernworkplace.sharepoint.com/sites/Sales" 
    $ListName = "Opportunities"
    
    Connect-PnPOnline -Url $Url -Interactive
    $Items = Get-PnPListItem -List $ListName
    
    $Items.Fieldvalues

    Example script to get all fieldvalues for a specific item

    $Url = "https://devmodernworkplace.sharepoint.com/sites/Sales" 
    $ListName = "Opportunities"
    
    Connect-PnPOnline -Url $Url -Interactive
    $Items = Get-PnPListItem -List $ListName
    
    $Item =  $Items | Where-Object {$_.Fieldvalues["Title"] -eq "Opp 2"}
    
    $item.FieldValues