Skip to content

Instantly share code, notes, and snippets.

@aflyen
Created December 6, 2022 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aflyen/b1dfa65e3c892fd54e3ed3a31084cd21 to your computer and use it in GitHub Desktop.
Save aflyen/b1dfa65e3c892fd54e3ed3a31084cd21 to your computer and use it in GitHub Desktop.
Send GET request to the SharePoint API using interactive login with username and password for use with in example the Site Manager API
function Send-CorpSharePointGetRequest
{
Param(
[Parameter(Mandatory=$true)]
[string]$Url,
[Parameter(Mandatory=$true)]
[string]$UserName,
[Parameter(Mandatory=$true)]
[System.Security.SecureString]$Password,
[Parameter(Mandatory=$true)]
[string]$RequestUrl
)
$Result = $null
try
{
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
$Context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username, $Password)
$Context.ExecuteQuery()
$RequestUrl = "$($Url)$($RequestUrl)"
$AuthenticationCookie = $Context.Credentials.GetAuthenticationCookie($Url, $true)
$WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$WebSession.Cookies.SetCookies($Url, $AuthenticationCookie)
$WebSession.Headers.Add("Accept", "application/json;odata=verbose")
$Result = Invoke-RestMethod -Method Get -WebSession $WebSession -Uri $RequestUrl
$Context.Dispose()
}
catch
{
Write-Output "Error when getting data from SharePoint (GET): $($_.Exception.Message)"
}
return $Result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment