How to execute ANY SharePoint powershell command programmatically using C#

2 min read

In one of my projects my team faced following challenges:

  • How to add query rules programmatically using C#
  • How to update thesaurus programmatically using C#

I tried to find information in official documentation but it was not very helpful neither was googling.

Powershell cmdlets to c# assembly mapping

In my team we were thinking what to do in this situation and one of my colleagues came with brilliant idea – he searched for PowerShell cmdlet in file explorer with searching in files content option turned on.

Result? What he found was exactly what we were looking for.

In location “C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\CONFIG\PowerShell\Registration” there is file named OSSSearchCmdlets.xml.

What it contains is xml structure with following structure:

       <ps:Cmdlet>

            <ps:VerbName>Get-SPEnterpriseSearchCrawlContentSource</ps:VerbName>

            <ps:ClassName>Microsoft.Office.Server.Search.Cmdlet.GetSearchCrawlContentSource</ps:ClassName>

            <ps:HelpFile>Microsoft.Office.Server.Search.dll-help.xml</ps:HelpFile>

        </ps:Cmdlet>

 

My eyes see this just as below:

       <PowershellToAssembllyMapping>

            <PowerShellCmdName>What-I-Have</PowerShellCmdName>

            <C#NameAndLocation>What-I-Am-Looking-For</C#NameAndLocation>

            <Whatever>Whatever.xml</Whatever>

        </PowershellToAssembllyMapping>

Maps for Search, WSS and many more

OSSSearchCmdlets.xml file contains ps cmdlets to .NET assemblies mapping only for SharePoint Search.

But in the same location there is also another file called WSSCmdlet.xml that contains all kind of cmdlets mapping like

  • Enable-SPFeature
  • New-SPContentDatabase
  • Get-SPFarm
  • Etc.

Shortly everything that you can do with SharePoint Application using PowerShell.

 

If you just want to quickly check what those files contains I’ve uploaded them to my github. I put there also more files like for Reporting Services, Workflows etc. You can check it here.

Have you found useful this tip? Maybe you know alternative way? Share it in comments!

Thanks & Have a great day! 🙂