Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a Sitecore Powershell script from code

I have installed the popular Powershell Console Sitecore plugin, and so far I'm loving it.

I would like to be able to invoke a specific script programmatically in C# (as in, as a consequence of user input), but I could not find any valid resource pointing me in the right direction.

Is there any way of achieving this? Do the rules for classic Powershell scripts apply to the Sitecore version?

like image 674
Emanuele Ciriachi Avatar asked Mar 05 '26 17:03

Emanuele Ciriachi


1 Answers

You can directly call any PowerShell script from your own code using the following

using Cognifide.PowerShell.Core.Host;
using Sitecore.Data.Items;

namespace MyProject
{
    public class TestSPE
    {
        public void Invoke()
        {
            using (ScriptSession scriptSession = ScriptSessionManager.NewSession("Default", true))
            {
                Item speScriptItem = Sitecore.Context.Database.GetItem("/path-or-id/to-spe-item");
                string script = speScriptItem["Script"];
                if (!string.IsNullOrEmpty(script))
                    scriptSession.ExecuteScriptPart(script);
            }
        }
    }
}

Be sure to add a reference to Cognifide.PowerShell.dll in your project.

If your script is not stored on a PowerShell Script item in Sitecore then you pass in a string with the SPE commands and script you wish to run.

You can read more in this blog post about Using PowerShell Console for Sitecore in Your Own Code

Update:

To create a "script item", create an item using Template from:

/sitecore/templates/Modules/PowerShell Console/PowerShell Script

This will provide you Script body where you can put your code. You can find examples of the default SPE scripts in the modules Script Library under /sitecore/system/Modules/PowerShell/Script Library.

Update 2:

To get return values from the script, you call to pass false for the stringOutput parameter on the method:

List<object> results; 
results = scriptSession.ExecuteScriptPart(script, false); 
like image 164
jammykam Avatar answered Mar 08 '26 05:03

jammykam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!