Posted on:
Categories: PowerShell;SharePoint
Description:
Lately it has become the norm for us to provision SharePoint structures using CSOM-oriented PowerShell scripts. This provides good agility because the provisioning can be run from pretty-much any machine against remote farms, both on-premise and in the cloud.

There are plenty of PowerShell-CSOM examples posted around the web, but I'm starting to wonder whether we should rather take a REST-oriented approach, and I don't see much being said about that.

PowerShell-CSOM, although liberating, is still dependent on the SharePoint Client runtime being installed and kept up-to-date locallyJust as there is a strong case for app development to shift to JQuery-and-REST, one can also make a case to shift our PowerShell provisioning scripts to REST. For one thing, doing so means our code will be more portable amongst technologies. We might choose, for example, to rip out some provisioning code from a PowerShell-REST script and transpose it into JQuery-REST so that users can self-provision things. We could, of course, transpose ​into any technology that has the HTTP capabilities.

I'm not yet decided on whether relinquishing the CSOM encapsulation layer ​will prove good or bad, but I do plan to favour REST for the next while and see where it takes us.

Here is a bare-bones pure REST example using PowerShell 3's Invoke-RestMethod. Some examples that use REST do so via SharePoint DLLs, which seems pointless. Let's abandon local SharePoint dependencies and go pure HTTP.  

The sample creates a view in the specified list. It was written for use in an on-premise enviroment.
param
(
    [Parameter(Mandatory = $true)][string]$url,
    [Parameter(Mandatory = $true)][string]$listTitle
)

$cred = Get-Credential

# Get form digest (required for POST operations)

$digestUrl = "{0}/_api/contextinfo" -f $url
$response = Invoke-RestMethod -Uri $digestUrl -Method POST  -Credential $cred
$formDigestVal = $([XML] $response).GetContextWebInformation.FormDigestValue

# Create the new view

$dataUrl = "{0}/_api/lists/getByTitle('{1}')/Views" -f $url, $listTitle

$headers = @{ "X-RequestDigest" = $formDigestVal }

$contentTypeHeader = "application/json;odata=verbose"

$body = @{
    __metadata = @{ type = "SP​.View" };
    Title = "A test view";
}

$jsonBody = ConvertTo-Json $body -Compress

Invoke-RestMethod -Uri $dataUrl -Method Post -Credential $cred -Headers $headers -Body $jsonBody.ToString() -ContentType $contentTypeHeader
MSDN​ has some good documentation on the properties and methods available via REST, including which properties​ are writeable.