Call REST API Methods in SharePoint Online from PowerShell

Requirement: Call SharePoint Online REST API from PowerShell

PowerShell to Call a REST API method in SharePoint Online:
Here is how to call SharePoint Online REST API using PowerShell
#Load SharePoint CSOM Assemblies
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"

Function Get-SPOUserProfileProperty ($SiteURL, $UserID)
{
    #Setup Credentials to connect
    $Cred = Get-Credential

    #Connect to Site
    $Context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
    $Context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
    $Context.ExecuteQuery()    

    #Frame REST API URL
    $RequestUrl = "$($SiteUrl)/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor([email protected])[email protected]='i:0%23.f|membership|$($UserID)'"
    $AuthenticationCookie = $Context.Credentials.GetAuthenticationCookie($SiteUrl, $true)
    $WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
    $WebSession.Credentials = $Context.Credentials
    $WebSession.Cookies.SetCookies($SiteUrl, $AuthenticationCookie)
    $WebSession.Headers.Add("Accept", "application/json;odata=verbose")

    #Invoke Rest Method
    $Result = Invoke-RestMethod -Method Get -WebSession $WebSession -Uri $RequestURL
    Return ($Result.d.userprofileproperties.results)
}

#Set Parameters
$SiteURL="https://crescenttech.sharepoint.com" 
$UserID="[email protected]"

#Call the function to get user profile properties
Get-SPOUserProfileProperty -SiteUrl $SiteUrl -UserID $UserID | Select Key, Value

This retrieves all user profile properties of a given user
call sharepoint online rest api from powershell

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.