private static void ProcessScript(HttpContext context, Item scriptItem, Dictionary <string, Stream> streams) { if (!scriptItem.IsPowerShellScript() || scriptItem?.Fields[Templates.Script.Fields.ScriptBody] == null) { HttpContext.Current.Response.StatusCode = 404; return; } using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true)) { var script = scriptItem[Templates.Script.Fields.ScriptBody]; if (Context.Database != null) { var item = Context.Database.GetRootItem(); if (item != null) { session.SetItemLocationContext(item); } } session.SetExecutedScript(scriptItem); context.Response.ContentType = "text/plain"; var scriptArguments = new Hashtable(); foreach (var param in HttpContext.Current.Request.QueryString.AllKeys) { var paramValue = HttpContext.Current.Request.QueryString[param]; if (string.IsNullOrEmpty(param)) { continue; } if (string.IsNullOrEmpty(paramValue)) { continue; } scriptArguments[param] = paramValue; } foreach (var param in HttpContext.Current.Request.Params.AllKeys) { var paramValue = HttpContext.Current.Request.Params[param]; if (string.IsNullOrEmpty(param)) { continue; } if (string.IsNullOrEmpty(paramValue)) { continue; } if (session.GetVariable(param) == null) { session.SetVariable(param, paramValue); } } session.SetVariable("requestStreams", streams); session.SetVariable("scriptArguments", scriptArguments); session.ExecuteScriptPart(script, true); context.Response.Write(session.Output.ToString()); if (session.Output.HasErrors) { context.Response.StatusCode = 424; context.Response.StatusDescription = "Method Failure"; } } }
protected override void ProcessRecord() { if (Interactive && !HostData.ScriptingHost.Interactive) { RecoverHttpContext(); WriteError(typeof(CmdletInvocationException), "An interactive script session cannot be started from non-interactive script session.", ErrorIds.OriginatingScriptSessionNotInteractive, ErrorCategory.InvalidOperation, HostData.ScriptingHost.SessionId); return; } var script = string.Empty; scriptItem = Item; if (Item != null) { scriptItem = Item; if (!IsPowerShellScriptItem(scriptItem)) { return; } script = Item[Templates.Script.Fields.ScriptBody]; } else if (Path != null) { var drive = IsCurrentDriveSitecore ? CurrentDrive : ApplicationSettings.ScriptLibraryDb; scriptItem = PathUtilities.GetItem(Path, drive, ApplicationSettings.ScriptLibraryPath); if (scriptItem == null) { WriteError(typeof(ItemNotFoundException), $"The script '{Path}' cannot be found.", ErrorIds.ItemNotFound, ErrorCategory.ObjectNotFound, Path); return; } if (!IsPowerShellScriptItem(scriptItem)) { return; } script = scriptItem[Templates.Script.Fields.ScriptBody]; } if (!ShouldProcess(scriptItem?.GetProviderPath() ?? string.Empty, "Start new script session")) { return; } scriptBlock = ScriptBlock ?? InvokeCommand.NewScriptBlock(script); // sessions from IDs if (Id != null && Id.Length > 0) { foreach (var id in Id) { // is id defined? if (string.IsNullOrEmpty(id)) { WriteError(typeof(ObjectNotFoundException), "The script session Id cannot be null or empty.", ErrorIds.ScriptSessionNotFound, ErrorCategory.ResourceUnavailable, Id); break; } // is it a wildcard search for session? if (id.Contains("*") || id.Contains("?")) { if (ScriptSessionManager.SessionExistsForAnyUserSession(id)) { ScriptSessionManager.GetMatchingSessionsForAnyUserSession(id).ForEach(ProcessSession); } else { WriteError(typeof(ObjectNotFoundException), $"The script session with Id '{Id}' cannot be found.", ErrorIds.ScriptSessionNotFound, ErrorCategory.ResourceUnavailable, Id); } break; } // does session exist? if (ScriptSessionManager.SessionExistsForAnyUserSession(id)) { ScriptSessionManager.GetMatchingSessionsForAnyUserSession(id).ForEach(ProcessSession); } else // OK... fine... execute in a new persistent session! { ProcessSession(ScriptSessionManager.GetSession(id, ApplicationNames.BackgroundJob, false)); } } return; } if (Session != null) { if (Session.Length == 0) { WriteError(typeof(ObjectNotFoundException), "Script session cannot be found.", ErrorIds.ScriptSessionNotFound, ErrorCategory.ResourceUnavailable, string.Empty); return; } foreach (var session in Session) { ProcessSession(session); } } ProcessSession(ScriptSessionManager.GetSession(string.Empty, ApplicationNames.BackgroundJob, false)); }
private static void ProcessScript(HttpContext context, string script, Dictionary <string, Stream> streams, string cliXmlArgs = null, bool rawOutput = false, string sessionId = null, bool persistentSession = false) { if (string.IsNullOrEmpty(script)) { context.Response.StatusCode = 404; context.Response.StatusDescription = "The specified script is invalid."; return; } var session = ScriptSessionManager.GetSession(sessionId, ApplicationNames.RemoteAutomation, false); if (Context.Database != null) { var item = Context.Database.GetRootItem(); if (item != null) { session.SetItemLocationContext(item); } } context.Response.ContentType = "text/plain"; if (streams != null) { var scriptArguments = new Hashtable(); foreach (var param in context.Request.QueryString.AllKeys) { var paramValue = HttpContext.Current.Request.QueryString[param]; if (string.IsNullOrEmpty(param)) { continue; } if (string.IsNullOrEmpty(paramValue)) { continue; } scriptArguments[param] = paramValue; } foreach (var param in context.Request.Params.AllKeys) { var paramValue = context.Request.Params[param]; if (string.IsNullOrEmpty(param)) { continue; } if (string.IsNullOrEmpty(paramValue)) { continue; } if (session.GetVariable(param) == null) { session.SetVariable(param, paramValue); } } session.SetVariable("requestStreams", streams); session.SetVariable("scriptArguments", scriptArguments); session.ExecuteScriptPart(script, true); context.Response.Write(session.Output.ToString()); } else { // Duplicate the behaviors of the original RemoteAutomation service. var requestUri = WebUtil.GetRequestUri(); var site = SiteContextFactory.GetSiteContext(requestUri.Host, Context.Request.FilePath, requestUri.Port); Context.SetActiveSite(site.Name); if (!string.IsNullOrEmpty(cliXmlArgs)) { session.SetVariable("cliXmlArgs", cliXmlArgs); session.ExecuteScriptPart("$params = ConvertFrom-CliXml -InputObject $cliXmlArgs", false, true); script = script.TrimEnd(' ', '\t', '\n'); } var outObjects = session.ExecuteScriptPart(script, false, false, false) ?? new List <object>(); var response = context.Response; if (rawOutput) { // In this output we want to give raw output data. No type information is needed. Error streams are lost. if (outObjects.Any()) { foreach (var outObject in outObjects) { response.Write(outObject.ToString()); } } if (session.LastErrors != null && session.LastErrors.Any()) { var convertedObjects = new List <object>(); convertedObjects.AddRange(session.LastErrors); session.SetVariable("results", convertedObjects); session.Output.Clear(); session.ExecuteScriptPart("ConvertTo-CliXml -InputObject $results"); response.Write("<#messages#>"); foreach (var outputBuffer in session.Output) { response.Write(outputBuffer.Text); } } } else { // In this output we want to preserve type information. Ideal for objects with a small output content. if (session.LastErrors != null && session.LastErrors.Any()) { outObjects.AddRange(session.LastErrors); } if (outObjects.Any()) { session.SetVariable("results", outObjects); session.Output.Clear(); session.ExecuteScriptPart("ConvertTo-CliXml -InputObject $results"); foreach (var outputBuffer in session.Output) { response.Write(outputBuffer.Text); } } } } if (session.Output.HasErrors) { context.Response.StatusCode = 424; context.Response.StatusDescription = "Method Failure"; } if (string.IsNullOrEmpty(sessionId) || !persistentSession) { ScriptSessionManager.RemoveSession(session); } }