从代码运行Sitecore Powershell脚本

Ema*_*chi 3 c# powershell sitecore

我已经安装了流行的Powershell控制台 Sitecore插件,到目前为止我很喜欢它.

我希望能够以编程方式在C#中调用特定脚本(因为用户输入的结果),但我找不到任何有效的资源指向我正确的方向.

有没有办法实现这个目标?经典Powershell脚本的规则是否适用于Sitecore版本?

jam*_*kam 8

您可以使用以下代码直接从您自己的代码中调用任何PowerShell脚本

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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

务必Cognifide.PowerShell.dll在项目中添加引用.

如果您的脚本未存储PowerShell Script在Sitecore中的项目上,那么您将传入一个包含您希望运行的SPE命令和脚本的字符串.

您可以在此博客文章中阅读有关在自己的代码中使用PowerShell控制台进行Sitecore的更多信息

更新:

要创建"脚本项",请使用以下模板创建项:

/sitecore/templates/Modules/PowerShell Console/PowerShell Script
Run Code Online (Sandbox Code Playgroud)

这将为您提供Script body放置代码的位置.您可以在"脚本库"模块下找到默认SPE脚本的示例/sitecore/system/Modules/PowerShell/Script Library.

更新2:

从脚本得到返回值,你可以调用传递falsestringOutput对方法的参数:

List<object> results; 
results = scriptSession.ExecuteScriptPart(script, false); 
Run Code Online (Sandbox Code Playgroud)