Skip to content

Instantly share code, notes, and snippets.

@aflyen
Created December 6, 2022 21:05
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/8aadfc08876051305325a6a98cee5e93 to your computer and use it in GitHub Desktop.
Save aflyen/8aadfc08876051305325a6a98cee5e93 to your computer and use it in GitHub Desktop.
Send POST request to the SharePoint API using interactive login with username and password for use with in example the Site Manager API
function Send-CorpSharePointPostRequest
{
Param(
[Parameter(Mandatory=$true)]
[string]$Url,
[Parameter(Mandatory=$true)]
[string]$UserName,
[Parameter(Mandatory=$true)]
[System.Security.SecureString]$Password,
[Parameter(Mandatory=$true)]
[string]$RequestUrl,
[Parameter(Mandatory=$false)]
[string]$RequestBody
)
$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)
$FormsDigest = $Context.GetFormDigestDirect()
$WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$WebSession.Credentials = $Context.Credentials
$WebSession.Cookies.SetCookies($Url, $AuthenticationCookie)
$Headers = @{
'X-RequestDigest' = $FormsDigest.DigestValue;
'odata-version' = '4.0' }
if ($RequestBody -eq $null)
{
$Result = Invoke-RestMethod -Method Post -WebSession $WebSession -Headers $Headers -ContentType "application/json;odata=verbose;charset=utf-8" -Uri $RequestUrl -UseDefaultCredentials
}
else
{
$Result = Invoke-RestMethod -Method Post -WebSession $WebSession -Headers $Headers -ContentType "application/json;odata=verbose;charset=utf-8" -Body $RequestBody -Uri $RequestUrl -UseDefaultCredentials
}
$Context.Dispose()
}
catch
{
Write-Output "Error when posting data to SharePoint (POST): $($_.Exception.Message)"
}
return $Result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment