SharePoint 2013 – Call Search REST API from PowerShell Script

Add-Type -AssemblyName System.Web

$sServerPath = “http://<Site URL>”
$sQueryOptions = “selectproperties=’ManagedPropertyName’&clienttype=’ContentSearchRegular’&QueryTemplatePropertiesUrl=’spfile://webroot/queryparametertemplate.xml'”
$sUserName = “user name”
$sPassword =”password”
$sDomain=”domain name”
$WebRMethod=[Microsoft.PowerShell.Commands.WebRequestMethod]::Get

function Get-SPSearchResults
{
param ($keyword,$sUserName,$sPassword, $sDomain, $WebRMethod)
try
{
$spCredentials = New-Object System.Net.NetworkCredential($sUserName,$sPassword,$sDomain)
$enckeyword = [System.Web.HttpUtility]::UrlEncode(“‘$keyword'”)
$url = $sServerPath+”/_api/search/query?querytext=$enckeyword”+”&$sQueryOptions”

$spWebRequest = [System.Net.WebRequest]::Create($url)
$spWebRequest.Credentials = $spCredentials
$spWebRequest.Accept = “application/json;odata=verbose”
$spWebRequest.Method=$WebRMethod
$spWebResponse = $spWebRequest.GetResponse()
$spRequestStream = $spWebResponse.GetResponseStream()
$spReadStream = New-Object System.IO.StreamReader $spRequestStream
$spData=$spReadStream.ReadToEnd()
$results = $spData | ConvertFrom-Json
$results = $results.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results

for($i=0; $i -le $results.length-1; $i++)
{

$row = $results[$i]

for ($j=0; $j -le $row.Cells.results.length-1; $j++)
{

if ($row.Cells.results[$j].Key -eq ‘Title’)
{
Write-Host $row.Cells.results[$j].Value -ForegroundColor Green
}
}
}
}
catch
{
Write-Host $_.Exception.Message -ForegroundColor Red
}
}

try
{
Get-SPSearchResults -keyword “ca” -sUserName $sUserName -sPassword $sPassword -sDomain $sDomain -WebRMethod $WebRMethod
}
catch
{
Write-Host “Problem in running the REST API. Failed with error : ” + $_.Exception.Message -ForegroundColor Red
}

Advertisements

Execute C# code from PowerShell Script – SharePoint Online

Are you looking for an example code to exeucte C# code from PS?

Hope you can get started with the below sample. As per your requirement change the DLL path, Site URL, UserName and Password parameters in the below example.

cls

# C# Source Code
$SourceCode = @”
using System;
using System.Management.Automation;
using System.Security;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Utilities;

namespace SPOperations
{
public class SPHelper
{
public static string getWebTitle(string siteUrl, string userName, string sitePassword)
{
using (ClientContext clientContext = new ClientContext(siteUrl))
{
SecureString passWord = new SecureString();
foreach (char c in sitePassword.ToCharArray()) passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(userName, passWord);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
return web.Title;
}
}
}
}
“@

try
{
$scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
Set-Location $scriptBase

$TenantConfig = $scriptBase + “\” + “Configs\settings.xml”
$TenantConfigXML = [xml](Get-Content($TenantConfig));

$url = $TenantConfigXML.ConnectionString.Key.URL
$username = $TenantConfigXML.ConnectionString.Key.UserName
$password = $TenantConfigXML.ConnectionString.Key.Password

$assemblies = @(
“$scriptBase\DLL\Microsoft.SharePoint.Client.dll”,
“$scriptBase\DLL\Microsoft.SharePoint.Client.Runtime.dll”
“System.Core”
)
}
catch
{
Write-host “Error while loading the input parameters ” $_.Exception.Message -ForegroundColor Red
exit 1
}

try
{
#Add the Assembly
Add-Type -ReferencedAssemblies $assemblies -TypeDefinition $SourceCode -Language CSharp
}
catch
{
Write-host “Error while loading the Referenced Assemblies and Type Definition ” $_.Exception.Message -ForegroundColor Red
exit 1
}

try
{
$siteTitle = [SPOperations.SPHelper]::getWebTitle($url, $username, $password)
Write-Host $siteTitle
}
catch
{
Write-host “Error : ” $_.Exception.Message -ForegroundColor Red
exit 1
}

Hide Webpart – SharePoint Online by PowerShell

I came across a scenario where I need to hide the OOTB list form WebPart from the SharePoint List “NewForm.aspx” page by PowerShell. I have written a script to perform the same in SharePoint online.

In the below script, I am getting the list of WebParts in the NewForm.aspx page and setting the hidden property. If you have more than one WebPart in a page, you can find the specific WebPart and set the required properties to that.

Note:

  • Update the url, username and password with your tenant details.
  • Keep the Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime DLLs in the place where you saved the PowerShell script file or change the location as per your location.

Script

cls

$scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
Set-Location $scriptBase

Add-Type -Path $scriptBase”\Microsoft.SharePoint.Client.dll”
Add-Type -Path $scriptBase”\Microsoft.SharePoint.Client.Runtime.dll”

$url = “https://xyz.sharepoint.com/sites/dev&#8221;
$username = “admin@xyz.onmicrosoft.com”
$password = “Password”

$Password = $password |ConvertTo-SecureString -AsPlainText -force
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
$Context.Credentials = $credentials

$List = $Context.Web.Lists.GetByTitle(“Test List”)
$Context.Load($List)
$Context.ExecuteQuery()

$Pages = $List.RootFolder.Files
$Context.Load($Pages)
$Context.ExecuteQuery()

$Page = $List.RootFolder.Files | Where {$_.Name -eq “NewForm.aspx”}
$Context.Load($Page)
$Context.ExecuteQuery()

$WPM = $Page.GetLimitedWebPartManager(“Shared”)
$Context.Load($WPM)
$Context.ExecuteQuery()

$WebParts = $WPM.WebParts
$Context.Load($WebParts)
$Context.ExecuteQuery()

$WebPart = $WebParts[0]
$Context.Load($WebPart)
$Context.ExecuteQuery()

$WebPart.WebPart.Hidden = $true
$WebPart.SaveWebPartChanges()
$Context.ExecuteQuery()

O365 Custom JavaScript Injection using PowerShell

What is Custom Action?

Custom action fetches an external script and includes it in the page. So at run time the script will self execute as an anonymous function.

Following are few scenarios you may need this functionality in your SharePoint Projects:

1) Override the new sub site link (https://<tenant&gt;.sharepoint.com/sites/dev/_layouts/15/newsbweb.aspx) under Site Contents  with your site provisioning app URL

2) Redirect the user to specific page

3) Inject third-party JavaScript libraries such as Jquery, Knockout, AngularJs, etc.,

4) Add dynamic html (global navigation / company copy rights information on the bottom of your page) content on your sharepoint page at run time without even modifying the actual master page.

In the below example, I have explained how to inject Jquery file to one of my web. The source files can be placed in CDN / File Share / Common Location such as App Catalog.

Please feel free to change the logic as per your requirement.

Note: The logic remains same for JSOM code also.

Inject_Action

 

O365 / SharePoint Online – Apply Theme – CSOM & Powershell

As you know, Web.ApplyTheme method applies a theme with the specified components to this site.

For more information refer – https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.web.applytheme.aspx

Here fontSchemeUrl and backgroundImageUrl parameters can accept null values. But when I tried to pass $null or null or Empty String to these two parameters via PowerShell, I got the following error:

“Exception calling “ApplyTheme” with “4” argument(s): “The ‘fontSchemeUrl’ argument is invalid.”.Exception.Message”

Then i tried with Out-Null instead of $null or null or Empty String. Trust me it worked like a charm.

Actually the Out-Null cmdlet deletes output instead of sending it down the pipeline.

This is my final code.

Hope it helps 🙂

Fixed

 

 

O365 / SharePoint Online – Import Term Store Terms using CSOM & PowerShell

Looking for a solution to import Term Store Terms using CSOM & PowerShell in O365 / SharePoint Online?

Here you go….

Note: Modify the XML term attributes and PS script logic as per your requirement

XML Config File Structure

config xml

PowerShell Script

cls

try
{
Write-Host “Load XML config file” -foregroundcolor black -backgroundcolor yellow Set-Location

$xdoc = [xml] (get-content “C:\Joseph\Code\SPRIDER\PS\TermStore\config.xml”)

$Url = $xdoc.Tenant.Admin.site
$Admin = $xdoc.Tenant.Admin.username
$Pwd = $xdoc.Tenant.Admin.password

$SecurePwd = $Pwd |ConvertTo-SecureString -AsPlainText -force

Write-Host “Global variables loaded succeefully” -foregroundcolor black -backgroundcolor Green
}
catch
{
Write-Host “Error : $_.Exception.Message” -foregroundcolor black -backgroundcolor Red
return
}

try
{
Write-Host “Load CSOM DLLs” -foregroundcolor black -backgroundcolor yellow Set-Location

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”
Add-Type -Path “c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll”

Write-Host “CSOM DLLs loaded succeefully” -foregroundcolor black -backgroundcolor Green
}
catch
{
Write-Host “Error : $_.Exception.Message” -foregroundcolor black -backgroundcolor Red
return
}

function Recursive($inputerm,$inputNode)
{

Foreach ($InnerTermNode in $inputNode.term)
{
$childterms = $inputerm.Terms
$Ctx.Load($childterms)
$Ctx.ExecuteQuery()
$childterm = $childterms | Where-Object {$_.Name -eq $InnerTermNode.name}
if($childterm)
{
Write-Host “Term” $InnerTermNode.name “already exists.” -foregroundcolor black -backgroundcolor yellow
}
else
{
Write-Host “Creating term ” $InnerTermNode.name -foregroundcolor black -backgroundcolor yellow

$childterm = $inputerm.CreateTerm($InnerTermNode.name, 1033, [System.Guid]::NewGuid())
try
{
$Ctx.ExecuteQuery()

Write-Host “Term” $childterm.name “Created successfully” -foregroundcolor black -backgroundcolor Green
}
catch
{
Write-Host “Error while creating Term” $InnerTermNode.name $_.Exception.Message -foregroundcolor black -backgroundcolor Red
return
}
}
if($InnerTermNode.ChildNodes.Count -gt 0)
{
Recursive $childterm $InnerTermNode
}
}
}
try
{
Write-Host “Authenticate tenant site $url and get ClientContext object” -foregroundcolor black -backgroundcolor yellow

$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Admin, $SecurePwd)
$Ctx.Credentials = $Credentials
if (!$Ctx.ServerObjectIsNull.Value)
{
Write-Host “Connected to SharePoint Online site: ” $Ctx.Url “” -foregroundcolor black -backgroundcolor Green

$TaxonomySession = [Microsoft.SharePoint.Client.Taxonomy.TaxonomySession]::GetTaxonomySession($Ctx)
$TaxonomySession.UpdateCache()
$Ctx.Load($TaxonomySession)
$Ctx.ExecuteQuery()

Write-Host “Taxonomy session initiated: ” $TaxonomySession.Path.Identity “” -foregroundcolor black -backgroundcolor Green

$termStore = $TaxonomySession.GetDefaultSiteCollectionTermStore()
$Ctx.Load($termStore)
$Ctx.ExecuteQuery()
Foreach ($GroupName in $xdoc.Tenant.TermStore.group)
{
Write-Host “Getting list of groups from term store” -foregroundcolor black -backgroundcolor yellow

$groups = $termStore.Groups
$Ctx.Load($groups)
$Ctx.ExecuteQuery()

try
{
$Ctx.ExecuteQuery()

Write-Host “List of groups from term store loaded successfully” -foregroundcolor black -backgroundcolor Green
}
catch
{
Write-Host “Error while getting list of groups from term store” $_.Exception.Message -foregroundcolor black -backgroundcolor Red
return
}

Write-Host “Check whether the group is exist in the term store” -foregroundcolor black -backgroundcolor yellow

$group = $groups | Where-Object {$_.Name -eq $GroupName.name}

if ($group)
{
Write-Host “Group” $GroupName.name “already exists.” -foregroundcolor black -backgroundcolor yellow

$group = $termStore.Groups.GetByName($GroupName.name)
$Ctx.Load($group)
$Ctx.ExecuteQuery()
}
else
{
Write-Host “Creating group” $GroupName.name -foregroundcolor black -backgroundcolor yellow

$group = $termStore.CreateGroup($GroupName.name,[System.Guid]::NewGuid().toString())

try
{
$Ctx.ExecuteQuery()

Write-Host “Group” $GroupName.name “Created successfully” -foregroundcolor black -backgroundcolor Green
}
catch
{
Write-Host “Error while creating Group” $GroupName.name $_.Exception.Message -foregroundcolor black -backgroundcolor Red
return
}
}

Foreach ($TermSetNode in $GroupName.termset)
{
$termSets = $group.TermSets
$Ctx.Load($termSets)
$Ctx.ExecuteQuery()

$termSet = $termSets | Where-Object {$_.Name -eq $TermSetNode.name}

if($termSet)
{
Write-Host “Termset” $TermSetNode.name “already exists.” -foregroundcolor black -backgroundcolor yellow

$termSet = $group.TermSets.GetByName($TermSetNode.name)
$Ctx.Load($termSet)
$Ctx.ExecuteQuery()
}
else
{
Write-Host “Creating term set” $TermSetNode.name -foregroundcolor black -backgroundcolor yellow

$termSet = $group.CreateTermSet($TermSetNode.name,[System.Guid]::NewGuid().toString(),1033)

try
{
$Ctx.ExecuteQuery()

Write-Host “Term set ” $TermSetNode.name “Created successfully” -foregroundcolor black -backgroundcolor Green
}
catch
{
Write-Host “Error while creating Term set” $TermSetNode.name $_.Exception.Message -foregroundcolor black -backgroundcolor Red
return
}
}

Foreach ($TermNode in $TermSetNode.term)
{
$terms = $termSet.Terms
$Ctx.Load($terms)
$Ctx.ExecuteQuery()
$term = $terms | Where-Object {$_.Name -eq $TermNode.name}

if($term)
{
Write-Host “Term” $TermNode.name “already exists.” -foregroundcolor black -backgroundcolor yellow
}
else
{
Write-Host “Creating term ” $TermNode.name -foregroundcolor black -backgroundcolor yellow

$term = $termSet.CreateTerm($TermNode.name, 1033, [System.Guid]::NewGuid())

try
{
$Ctx.ExecuteQuery()

Write-Host “Term” $TermNode.name “Created successfully” -foregroundcolor black -backgroundcolor Green
}
catch
{
Write-Host “Error while creating Term” $TermNode.name $_.Exception.Message -foregroundcolor black -backgroundcolor Red
return
}
}

if($TermNode.ChildNodes.Count -gt 0)
{

Recursive $term $TermNode
}
}
}
}
}
}
catch
{
Write-Host “Error : $_.Exception.Message” -foregroundcolor black -backgroundcolor Red
return
}

How to update taxonomy hidden field using PowerShell?

Continuation to How to use taxonomy hidden field? – (http://sprider.org/2014/09/18/894/) Article

Example PowerShell script to update taxonomy(MMD) hidden field

Add-PSSnapin Microsoft.Sharepoint.Powershell

$sourceWebURL = “http://<Site URL>
$sourceListName = “<List Name>“

[Microsoft.SharePoint.SPSecurity]::RunWithElevatedPrivileges({

$spSourceWeb = Get-SPWeb $sourceWebURL
$spSourceList = $spSourceWeb.Lists[$sourceListName]

$spQuery = New-Object Microsoft.SharePoint.SPQuery
$caml = ‘<Where><Geq><FieldRef Name=”ID” /><Value Type=”Text”>0</Value></Geq></Where>’
$spQuery.Query = $caml
$spSourceItems = $spSourceList.GetItems($spQuery)

$spSourceWeb.AllowUnsafeUpdates = “true”;

foreach($item in $spSourceItems)
{
$item[taxonomyFieldObject.TextField] = “Term Value1|GUID1”; # Based on how you have configured the MMD column, supply the input here. To check the hidden value, we can use sharepoint manager complex tool
$item.Update()
}
$spSourceWeb.AllowUnsafeUpdates = “false”;
$spSourceWeb.Dispose();

});