簡體   English   中英

從代碼運行Sitecore Powershell腳本

[英]Running a Sitecore Powershell script from code

我已經安裝了流行的Powershell控制台 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命令和腳本的字符串。

您可以在此博客文章中閱讀有關在自己的代碼中使用PowerShell控制台進行Sitecore的更多信息

更新:

要創建“腳本項”,請使用以下模板創建項:

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

這將為您提供Script body ,您可以在其中放置代碼。 您可以在/sitecore/system/Modules/PowerShell/Script Library下的模塊腳本庫中找到默認SPE腳本的示例。

更新2:

要從腳本中獲取返回值,請調用以對方法的stringOutput參數傳遞false

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM