简体   繁体   中英

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?

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM