当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 从 PowerShell 调用 SharePoint Online 中的 REST API 方法

作者:精品下载站 日期:2024-12-14 14:59:51 浏览:15 分类:玩电脑

从 PowerShell 调用 SharePoint Online 中的 REST API 方法


要求:从 PowerShell 调用 SharePoint Online REST API。

PowerShell 在 SharePoint Online 中调用 REST API 方法

对于那些不熟悉这个概念的人来说,REST 代表表述性状态传输 (Representational State Transfer),它是一种可以通过 Internet 等网络提供计算机系统之间的互操作性的体系结构。 REST API 是一种提供 SharePoint 数据和功能访问的 Web 服务。它可用于许多不同的目的,例如构建自定义应用程序、创建用于自动化任务的一次性脚本或与其他系统集成。您可以使用任何支持 HTTP 请求和响应的编程语言。本博文将向您展示如何从 PowerShell 调用 SharePoint Online REST API 并以 JSON 格式返回结果。

以下是使用 PowerShell 调用 SharePoint Online REST API 的方法:


#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\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(accountName=@v)?@v='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://Crescent.sharepoint.com" 
$UserID="[email protected]"

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

这将检索给定用户的所有用户配置文件属性

[玩转系统] 从 PowerShell 调用 SharePoint Online 中的 REST API 方法

SharePoint Online:PnP PowerShell 调用 REST API

我们可以使用 Invoke-PnPSPRestMethod 从 PnP PowerShell 调用 REST API 方法:


#Parameters
$SiteURL= "https://crescent.sharepoint.com/sites/Marketing"

#Connect to the Site
Connect-PnPOnline -Url $SiteURL -Interactive 

#Define the Rest Method
$RestMethodURL = $SiteURL+'/_api/web/lists?$select=Title' 

#Invoke Rest Call to Get All Lists
$Lists = Invoke-PnPSPRestMethod -Url $RestMethodURL
$Lists.value

请注意,REST API 方法区分大小写! ($Lists.value 和 $Lists.Value 不同。)

调用 REST API 并将数据导入 SharePoint 列表

在另一种情况下,我必须从 Crowdstrike REST API 中提取数据并将数据添加到 SharePoint Online 列表。


#Set connection parameters
$client_id = "076f1qed3b4249e9b15cc1bf3ca11ff2"
$client_secret = "S19s5P3Zq7riLw22236TH3cxXXVeNhzdQ4bnalj0x"
$OAuthTokenEndpoint = "https://api.eu-1.crowdstrike.com/oauth2/token"
$RESTEndPoint = "https://api.eu-1.crowdstrike.com/devices/entities/devices/v2?offset=0&limit=5000&sort=status.desc"

#Config Variables for List
$SiteURL = "https://Crescent.sharepoint.com/sites/Monitoring"
$ListName = "CrowdStrike Hosts Report"

$AuthBody = @{
    client_id     = $client_id
    client_secret = $client_secret
    grant_type    = "client_credentials"
}

#Get the Bearer Token
Try { 
    $TokenRequest = Invoke-WebRequest -Method Post -Uri $OAuthTokenEndpoint -ContentType "application/x-www-form-urlencoded" -Body $AuthBody -UseBasicParsing -ErrorAction Stop 
}
Catch { 
    Write-Host "Unable to get the access token, aborting..."; Return 
}

#The Token endpoint returns a JSON containing the bearer token
$Token = ($tokenRequest.Content | ConvertFrom-Json).access_token

#Frame Authentication header
$AuthHeader = @{
   'Authorization'="bearer $Token"
   'accept' = "application/json"
}

#Call a REST API with the bearer token in the header
$Hosts = Invoke-WebRequest -Headers $AuthHeader -Uri $RESTEndPoint -UseBasicParsing

#Get the "Resources" from the JSON
$Resources = ($Hosts.Content | ConvertFrom-Json).Resources

#Frame Authentication header
$Header = @{
   'Authorization'="bearer $Token"
   'accept' = "application/json"
   'Content-Type'= 'application/json'
}

$Body = @{'ids' = $Resources} | ConvertTo-Json

$RESTEndPoint = "https://api.eu-1.crowdstrike.com/devices/entities/devices/v2"

$Response = Invoke-WebRequest -Method POST -Uri $RESTEndPoint -Headers $Header -Body $Body

#Get Hosts Data
$HostsDataCollection = ($Response.Content | ConvertFrom-Json).Resources

Try {
    #Connect to the Site
    Connect-PnPOnline -URL $SiteURL -Interactive

    #Clear all items in the list
    Get-PnPList -Identity $ListName | Get-PnPListItem -PageSize 100 -ScriptBlock { Param($items) Invoke-PnPQuery } | ForEach-Object {$_.Recycle() }

    #Loop through each Row in the REST Response Add Item to SharePoint List
    ForEach($HostData in $HostsDataCollection)
    {
        #Frame the List Item to update
        $ItemValue = @{}           
        $AllFields = $HostData.PSObject.Properties | Select -ExpandProperty Name
        ForEach($Row in $HostData.PSObject.Properties)
        {
            #Get Source Field Value and add to Hashtable
            If($Row.TypeNameOfValue -eq "System.Object[]")
            {
                $ItemValue.Add($Row.Name,$Row.Value -join ",")
            }
            Else
            {
                $ItemValue.Add($Row.Name,$Row.Value)
            }
        }
        Write-host "Adding List item with values:"

        #Add New List Item
        Add-PnPListItem -List $ListName -Values $ItemValue | Out-Null
     }

}
Catch {
    write-host -f Red "Error:" $_.Exception.Message
}

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯