Skip to content

Instantly share code, notes, and snippets.

@crshnbrn66
Forked from vgrem/Invoke-RestSPO.ps1
Last active July 3, 2018 19:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save crshnbrn66/da144a90a4d601012d2c to your computer and use it in GitHub Desktop.
Save crshnbrn66/da144a90a4d601012d2c to your computer and use it in GitHub Desktop.
SharePoint Online REST request
Add-Type –Path 'C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll'
Add-Type –Path 'C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'
#http://www.codeproject.com/Articles/990131/CRUD-Operation-to-List-Using-SharePoint-Rest-API
#https://msdn.microsoft.com/en-us/library/office/fp142380.
#http://paulryan.com.au/2013/odata-in-sharepoint/
#https://wmostafaw.wordpress.com/2012/11/17/odata-in-sharepoint-2013-lists-and-items/
#http://blogs.msdn.com/b/uksharepoint/archive/2013/02/22/manipulating-list-items-in-sharepoint-hosted-apps-using-the-rest-api.aspx
#http://www.odata.org/getting-started/basic-tutorial/
Function Invoke-RestSPO()
{
<#
.SYNOPSIS
Invoke-RestSPO
.DESCRIPTION
Sends an HTTP or HTTPS request to a SharePoint Online REST-compliant web service.
This function sends an HTTP or HTTPS request to a Representational State
Transfer (REST)-compliant ("RESTful") SharePoint Online web service.
Invoke-RestSPO
.EXAMPLE
Invoke-SPORestMethod -Url "https://contoso.sharepoint.com/_api/web"
.EXAMPLE
Invoke-SPORestMethod -Url "https://contoso.sharepoint.com/_api/contextinfo" -Method "Post"
#>
Param(
[Parameter(Mandatory=$True)]
[uri]$Url,
[Parameter(Mandatory=$False)]
[Microsoft.PowerShell.Commands.WebRequestMethod]$Method = [Microsoft.PowerShell.Commands.WebRequestMethod]::Get,
[Parameter(Mandatory=$True)]
[Microsoft.SharePoint.Client.SharePointOnlineCredentials]$spCredentials,
[Parameter(Mandatory=$False)]
[String]$Metadata,
[Parameter(Mandatory=$False)]
[System.Byte[]]$Body,
[Parameter(Mandatory=$False)]
[String]$RequestDigest,
[Parameter(Mandatory=$False)]
[String]$ETag,
[Parameter(Mandatory=$False)]
[String]$XHTTPMethod,
[Parameter(Mandatory=$False)]
[System.String]$Accept = 'application/json;odata=verbose',
[Parameter(Mandatory=$False)]
[String]$ContentType = 'application/json;odata=verbose',
[Parameter(Mandatory=$False)]
[Boolean]$BinaryStringResponseBody = $False
)
if($spCredentials)
{$credentials = $spCredentials}
else
{
}
$request = [System.Net.WebRequest]::Create($Url)
$request.Credentials = $credentials
$request.Headers.Add('X-FORMS_BASED_AUTH_ACCEPTED', 'f')
$request.ContentType = $ContentType
$request.Accept = $Accept
$request.Method=$Method
if($RequestDigest) {
$request.Headers.Add('X-RequestDigest', $RequestDigest)
}
if($ETag) {
$request.Headers.Add('If-Match', $ETag)
}
if($XHTTPMethod) {
$request.Headers.Add('X-HTTP-Method', $XHTTPMethod)
}
if($Metadata -or $Body) {
if($Metadata) {
$Body = [byte[]][char[]]$Metadata
}
$request.ContentLength = $Body.Length
$stream = $request.GetRequestStream()
$stream.Write($Body, 0, $Body.Length)
}
else {
$request.ContentLength = 0
}
#Process Response
$response = $request.GetResponse()
try {
if($BinaryStringResponseBody -eq $False) {
$streamReader = New-Object System.IO.StreamReader $response.GetResponseStream()
try {
$data=$streamReader.ReadToEnd()
#fix for ConvertFrom-Json : Cannot convert the JSON string because a dictionary that was converted from the string contains the duplicated keys 'Id' and 'ID
#http://stackoverflow.com/questions/22080350/convertfrom-json-cannot-convert-the-json-string-because-a-dictionary-that-was
$data = $data.ToString().Replace('ID', '_ID')
#################
$results = $data | ConvertFrom-Json
$results.d
}
finally {
$streamReader.Dispose()
}
}
else {
$dataStream = New-Object System.IO.MemoryStream
try {
Stream-CopyTo -Source $response.GetResponseStream() -Destination $dataStream
$dataStream.ToArray()
}
finally {
$dataStream.Dispose()
}
}
}
finally {
$response.Dispose()
}
}
# Get Context Info
Function Get-SPOContextInfo
{
<#
.SYNOPSIS
Get-SPOContextInfo
.DESCRIPTION
Gets context info for the weburl passed.
.EXAMPLE
Get-SPOContextInfo
.EXAMPLE
Get-Something
another example
can have as many examples as you like
#>
Param(
[Parameter(Mandatory=$True)]
[uri]$WebUrl,
[Parameter(Mandatory=$True)]
[Microsoft.SharePoint.Client.SharePointOnlineCredentials]$spCredentials
)
$Url = $WebUrl.OriginalString + '/_api/contextinfo'
if($spCredentials)
{
try
{
Invoke-RestSPO $url Post -spCredentials $spCredentials
}
catch
{
"Error was $_"
$line = $_.InvocationInfo.ScriptLineNumber
"Error was in Line $line"
}
}
else
{
throw 'Sharepoint Credentials Object is required (spCredentials)'
}
}
#----------------------------------------------------------------------------------------------
# List CRUD operations via SharePoint REST API
#----------------------------------------------------------------------------------------------
# Update a List
Function New-SPOList
{
<#
.SYNOPSIS
New-SPOList
.DESCRIPTION
Creates a new sharepoint online list based on the parameters passed.
.EXAMPLE
New-SPOList -weburl 'http://somesharepointsitename' -SpCredentials $yourCredentials -listid Listid -Title 'yourtitle' -description 'yourdescription
#>
Param(
[Parameter(Mandatory=$True)]
[uri]$WebUrl,
[Parameter(Mandatory=$true)]
[Microsoft.SharePoint.Client.SharePointOnlineCredentials]$spCredentials,
[Parameter(Mandatory=$True)]
[String]$ListId,
[Parameter(Mandatory=$False)]
[String]$Title,
[Parameter(Mandatory=$False)]
[String]$Description
)
$listMetadata = @{
__metadata = @{'type' = 'SP.List' };
}
if($Title) {
$listMetadata['Title'] = $Title
}
if($Description) {
$listMetadata['Description'] = $Description
}
$listMetadata = $listMetadata | ConvertTo-Json
$Url = $WebUrl.OriginalString + "/_api/lists/getbytitle('" + $ListId + "')"
$contextInfo = Get-SPOContextInfo $WebUrl -spCredentials $spCredentials
try
{
Invoke-RestSPO -Url $Url -Method Post -spCredentials $spCredentials -RequestDigest $contextInfo.GetContextWebInformation.FormDigestValue -Metadata $listMetadata -ETag '*' -XHTTPMethod 'MERGE'
}
catch
{
"Error was $_"
$line = $_.InvocationInfo.ScriptLineNumber
"Error was in Line $line"
}
}
function New-SPOListItem
{
<#
.SYNOPSIS
New-SPOListItem
.DESCRIPTION
Creates a new SharepointOnline List item
returns a formatted object based on the paramters passed.
.EXAMPLE
New-SPOListItem
#>
Param(
[Parameter(Mandatory=$True)]
[uri]$WebUrl,
[Parameter(Mandatory=$true)]
[Microsoft.SharePoint.Client.SharePointOnlineCredentials]$spCredentials,
[Parameter(Mandatory=$True)]
[String]$ListTitle,
[Parameter(Mandatory=$False)]
[String]$columnTitle,
[Parameter(Mandatory=$False)]
[String]$columnvalue
)
$listMetadata = @{ __metadata = @{'type' = "SP.$ListNameListItem"},{$columntitle= $columnvalue}}
}
#Get List(s)
Function Get-SPOList
{
Param(
[Parameter(Mandatory=$True)]
[uri]$WebUrl,
[Parameter(Mandatory=$True)]
[Microsoft.SharePoint.Client.SharePointOnlineCredentials]$spCredentials
)
<#
.SYNOPSIS
Get-SPOList
.DESCRIPTION
Gets a specific sharepoint online list
.EXAMPLE
Get-SPOList -weburl 'http://somesharepointsitename' -SpCredentials $yourCredentials
#>
$Url = $WebUrl.OriginalString + '/_api/lists'
Try
{
$data = Invoke-RestSPO $Url Get -spCredentials $spCredentials
}
catch
{
"Error was $_"
$line = $_.InvocationInfo.ScriptLineNumber
"Error was in Line $line"
}
$data.results
}
function Get-SPOSpecificList
{
<#
.SYNOPSIS
Get-SPOSpecificList
.DESCRIPTION
Gets a specific sharepoint online list based on the listname specified in the listname param
.EXAMPLE
Get-SPOSpecificList -weburl 'http://somesharepointsitename' -SpCredentials $yourCredentials -listname 'mylist'
#>
Param(
[Parameter(Mandatory=$True)]
[uri]$WebUrl,
[Parameter(Mandatory=$True)]
[Microsoft.SharePoint.Client.SharePointOnlineCredentials]$spCredentials,
[Parameter(Mandatory=$True)]
[string]$listName
)
$WebUrl = $WebUrl.OriginalString
try
{
$lists = get-spolist -weburl $WebUrl -spCredentials $spCredentials | Where-Object{$_.title -eq $listname}
}
catch
{
"Error was $_"
$line = $_.InvocationInfo.ScriptLineNumber
"Error was in Line $line"
}
return $lists
}
function Get-SPOSpecificListItems
{
<#
.SYNOPSIS
Get-SPOSpecificListItems
.DESCRIPTION
gets specfic list items based on the list name specified will retrieve the number specified by numberToRetrieve. Default number for this is 999
.EXAMPLE
Get-SPOSpecificListItems -weburl 'http://somesharepointsitename' -SpCredentials $yourCredentials -listname 'mylist' -numbertoRetrieve '999'
#>
Param(
[Parameter(Mandatory=$True)]
[uri]$WebUrl,
[Parameter(Mandatory=$True)]
[Microsoft.SharePoint.Client.SharePointOnlineCredentials]$spCredentials,
[Parameter(Mandatory=$True)]
[string]$listName,
[Parameter(Mandatory=$false)]
[int]$numberToRetrieve = 999
)
#$lists = get-spolist -weburl $WebUrl -spCredentials $spCredentials | Where-Object{$_.title -eq $listname}
#$listId = $lists.id
$Url = $WebUrl.OriginalString + "/_api/Web/Lists/GetByTitle('" + $listName + "')/Items/?`$top=$numberToRetrieve"
try
{
$listItems = Invoke-RestSPO $Url Get -spCredentials $spCredentials
}
catch
{
"Error was $_"
$line = $_.InvocationInfo.ScriptLineNumber
"Error was in Line $line"
}
return $listItems.results
}
function Get-SPOSpecificListItemFields
{
<#
.SYNOPSIS
Get-SPOSpecificListItemFields
.DESCRIPTION
Detailed Description
.EXAMPLE
Get-SPOSpecificListItemFields -weburl 'http://somesharepointsitename' -SpCredentials $yourCredentials -listname 'mylist' -numbertoRetrieve '999'
#>
Param(
[Parameter(Mandatory=$True)]
[uri]$WebUrl,
[Parameter(Mandatory=$True)]
[Microsoft.SharePoint.Client.SharePointOnlineCredentials]$spCredentials,
[Parameter(Mandatory=$True)]
[string]$listName,
[Parameter(Mandatory=$false)]
[int]$numberToRetrieve = 999
)
#$lists = get-spolist -weburl $WebUrl -spCredentials $spCredentials | Where-Object{$_.title -eq $listname}
#$listId = $lists.id
$Url = $WebUrl.OriginalString + "/_api/Web/Lists/GetByTitle('" + $listName + "')/Fields/?`$top=$numberToRetrieve"
try
{
$listItems = Invoke-RestSPO $Url Get -spCredentials $spCredentials
}
catch
{
"Error was $_"
$line = $_.InvocationInfo.ScriptLineNumber
"Error was in Line $line"
}
return $listItems.results
}
#Delete a List
Function Remove-SPOList
{
<#
.SYNOPSIS
Remove-SPOList
.DESCRIPTION
Detailed Description
.EXAMPLE
Remove-SPOList -uri 'http://somesharepointsitename' -SpCredentials $yourCredentials -listId $listId
.EXAMPLE
Get-Something
another example
can have as many examples as you like
#>
Param(
[Parameter(Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[uri]$WebUrl,
[Parameter(Mandatory=$True)]
[Microsoft.SharePoint.Client.SharePointOnlineCredentials]$spCredentials,
[Parameter(Mandatory=$True)]
[String]$ListId
)
$Url = $WebUrl.OriginalString + "/_api/lists/getbytitle('" + $ListId + "')"
$contextInfo = Get-SPOContextInfo $WebUrl -spCredentials $spCredentials
try
{
Invoke-RestSPO -Url $Url -Method Post -spCredentials $spCredentials -RequestDigest $contextInfo.GetContextWebInformation.FormDigestValue -ETag '*' -XHTTPMethod 'DELETE'
}
catch
{
"Error was $_"
$line = $_.InvocationInfo.ScriptLineNumber
"Error was in Line $line"
}
}
function New-SPOCredentials
{
param
(
[Parameter(Mandatory=$false)]
[String]$UserName,
[Parameter(Mandatory=$false)]
[String]$Password
)
<#
.SYNOPSIS
New-SPOCredentials
.DESCRIPTION
Creates a credential object for Sharepoint Online
.EXAMPLE
Invoke-RestSPO -username 'myuser' -password 'password'
#>
if([string]::IsNullOrEmpty($UserName))
{
$UserName = Read-host -Prompt 'Enter the userName'
}
if([string]::IsNullOrEmpty($Password))
{
$SecurePassword = Read-Host -Prompt 'Enter the password' -AsSecureString
}
else
{
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
}
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
return $credentials
}
@crshnbrn66
Copy link
Author

Add more functions for specific list and for specific list fields.

@crshnbrn66
Copy link
Author

since passing [uri] needed to update functions to allow for that. in addition the help text was in the wrong position

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment