运行 来自代码的 Sitecore Powershell 脚本

Running a Sitecore Powershell script from code

我已经安装了流行的 Powershell Console Sitecore 插件,到目前为止我很喜欢它。

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

有什么办法可以实现吗?经典 Powershell 脚本的规则是否适用于 Sitecore 版本?

您可以使用以下代码从您自己的代码中直接调用任何 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);
            }
        }
    }
}

请务必在您的项目中添加对 Cognifide.PowerShell.dll 的引用。

如果您的脚本未存储在 Sitecore 中的 PowerShell Script 项目中,则您可以传入一个包含 SPE 命令和脚本的字符串 运行。

您可以在此博客 post 中阅读有关 Using PowerShell Console for Sitecore in Your Own Code

的更多信息

更新:

要创建 "script item",请使用以下模板创建项目:

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

这将为您提供 Script body 您可以放置​​代码的位置。您可以在 /sitecore/system/Modules/PowerShell/Script Library.

下的模块脚本库中找到默认 SPE 脚本的示例

更新二:

要从脚本中获取 return 值,您调用方法为 stringOutput 参数传递 false

List<object> results; 
results = scriptSession.ExecuteScriptPart(script, false);