Monday, September 27, 2021

Sitecore PowerShell Web API

Hi Folkes,

Few days back we got a requiremnet for access powershell script through browser. I went trough various articles and blogs but not found suffienct details for the same at a single place.

Today I will try to cover how can you setup Sitecore PowerShell Web API from scractch.
These below steps allow you to run powershell script though browser.

First make sure you have Sitecore PowerShell module install in your Sitecore.


  • At first open Sitecore PowerShell ISE
     
  • Click on New->New Module 
      


  • Give the Name of Module and check the 'Web API' checkbox like below:
     

  • After complete above step write custom script for referanc you can use below script:
  • if($length -eq $null){
    
    $length = 30
    
    }
    
    
    
    if($logType -eq $null){
    
    $logType = "log"
    
    }
    
    
    
    Get-ChildItem "$($SitecoreLogFolder)\$LogType*.*" |
    
    Sort-Object -Descending LastWriteTime |
    
    Select-Object -First 1 |
    
    
    
    Get-Content -Tail $length
    




  • Click on Save and save under LogFiles->WebAPI(recently created WebAPI module in 3rd step) in my case name is 'ShowLogs' like below:
         


  • Now you can access this script by entering below URL:
   
    



You also can able to pass parameter through query string as well for exapmle just add below 2 line in PowerShell Script:

write-host "Start Date Time: " $selectedStartDate
write-host "End Date Time: " $selectedEndDate

Now pass below URL:

http://{hostname}/-/script/v2/master/ShowLogs?selectedStartDate=06/23/2020&selectedEndDate=06/24/2020

Output will be like below:

    
Some more sample for parameter passing:
https://{hostname}/-/script/v2/master/ShowLogs
https://{hostname}/-/script/v2/master/ShowLogs?length=30
https://{hostname}/-/script/v2/master/ShowLogs?logType=Publishing
https://{hostname}/-/script/v2/master/ShowLogs?length=30&logType=Publishing


Even I just print the variable nothing else but you can do more customization by passing parameters.

In order for this to work. You need to enable restfulv2 in your Cognifide.PowerShell.config. which is located in Website\App_config\Include\Cognifide.PowerShell.config

<restfulv2 enabled=”true” requireSecureConnection=”false“>

I hope you enjoy this Sitecore blog. Stay tuned for more Sitecore related articles.

Till that happy Sitecoring :)


Please leave your comments or share this article if it’s useful for you.