Skip to content

Instantly share code, notes, and snippets.

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/f9bfde59ea095653c92305d555b9e35c to your computer and use it in GitHub Desktop.
Save aflyen/f9bfde59ea095653c92305d555b9e35c to your computer and use it in GitHub Desktop.
Access the SharePoint API using a delegated context (username and password) for those functions not supported with application based authentication in PowerShell
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