-1

I'm trying to run a PS script I made via custom buttons. The scripts must be loaded from Sitecore Script Library (/sitecore/system/Modules/PowerShell/Script Library)

The script runs perfectly if I run it from Powershell ISE, but ran from the backend, it doesn't.

public override void Execute(CommandContext context)
    {
        System.Threading.Tasks.Task.Run(() =>
        {
            try
            {
                Item scriptItem = _master.GetItem("{52B2BFF3-7B9B-4137-83AD-EFA6FD7ABAEC}");
                string scriptContents = scriptItem["Script"];

                using (Process process = new Process())
                {
                    process.StartInfo.FileName = "powershell.exe";
                    process.StartInfo.Arguments = "-NoProfile";
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardInput = true;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError = true;
                    process.Start();
                    using (var sw = process.StandardInput)
                    {
                        if (sw.BaseStream.CanWrite)
                        {
                            sw.WriteLine(scriptContents);
                        }
                    }
                    process.WaitForExit();
                }
            }
            catch (Exception ex)
            {
                Sitecore.Context.ClientPage.ClientResponse.Alert($"An error occured: {ex.Message}");
                Log.Error(ex.Message, this);

                return;
            }
        });
    }

Any help on my code or alternatives is welcome.

2

1 Answer 1

0

Try this code to run your script from backend.

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

And if you want to extend it further, you can go with the second implementation described in this article.

https://hishaamn.wordpress.com/2021/08/15/sitecore-powershell-reload-item/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.