public void ProcessRequest(HttpContext context) { string userName = HttpContext.Current.Request.Params.Get("user"); string password = HttpContext.Current.Request.Params.Get("password"); string scriptParam = HttpContext.Current.Request.Params.Get("script"); string scriptDbParam = HttpContext.Current.Request.Params.Get("scriptDb"); string itemParam = HttpContext.Current.Request.Params.Get("item"); string itemDbParam = HttpContext.Current.Request.Params.Get("itemDb"); bool authenticated = !string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password) && AuthenticationManager.Login(userName, password, false); Database scriptDb = !authenticated || string.IsNullOrEmpty(scriptDbParam) ? Sitecore.Context.Database : Database.GetDatabase(scriptDbParam); Database itemDb = !authenticated || string.IsNullOrEmpty(itemDbParam) ? Sitecore.Context.Database : Database.GetDatabase(itemDbParam); Item scriptItem = scriptDb.GetItem(scriptParam); if (scriptItem == null) { scriptItem = scriptDb.GetItem("/sitecore/system/Modules/PowerShell/Script Library/" + scriptParam); } if (scriptItem == null || scriptItem.Fields[ScriptItemFieldNames.Script] == null) { return; } using (var session = new ScriptSession(ApplicationNames.Default)) { String script = scriptItem.Fields[ScriptItemFieldNames.Script].Value; if (!string.IsNullOrEmpty(itemParam)) { Item item = itemDb.GetItem(itemParam); if (item != null) session.SetItemLocationContext(item); } context.Response.ContentType = "text/plain"; session.ExecuteScriptPart(script, true); context.Response.Write(session.Output.ToString()); if (session.Output.HasErrors) { context.Response.StatusCode = 424; context.Response.StatusDescription = "Method Failure"; } } }
public void Update(Item[] items, CommandItem command, ScheduleItem schedule) { using (var session = new ScriptSession(ApplicationNames.Default)) { foreach (Item item in items) { string script = item["Script"]; if (!String.IsNullOrEmpty(script)) { session.ExecuteScriptPart(script); } } } }
protected static IEnumerable<Item> RunEnumeration(string scriptSource, Item item) { Assert.ArgumentNotNull(scriptSource,"scriptSource"); Assert.ArgumentNotNull(item, "item"); scriptSource = scriptSource.Replace("script:", "").Trim(); Item scriptItem = item.Database.GetItem(scriptSource); using (var session = new ScriptSession(ApplicationNames.Default)) { String script = (scriptItem.Fields[ScriptItemFieldNames.Script] != null) ? scriptItem.Fields[ScriptItemFieldNames.Script].Value : string.Empty; script = String.Format( "cd \"{0}:{1}\"\n", item.Database.Name, item.Paths.Path.Replace("/", "\\").Substring(9)) + script; return session.ExecuteScriptPart(script, false).Cast<Item>(); } }
public static IEnumerable<string> FindMatches(ScriptSession session, string command, bool aceResponse) { if (_powerShellVersionMajor == 0) { _powerShellVersionMajor = (int)session.ExecuteScriptPart("$PSVersionTable.PSVersion.Major", false, true)[0]; } switch (_powerShellVersionMajor) { case (2): return FindMatches2(session, command, aceResponse); case (3): case (4): return FindMatches3(session, command, aceResponse); default: return new string[0]; } }
public static IEnumerable<string> FindMatches3(ScriptSession session, string command, bool aceResponse) { string lastToken; var truncatedCommand = TruncatedCommand(command, out lastToken); string TabExpansionHelper = @"function ScPsTabExpansionHelper( [string] $inputScript, [int]$cursorColumn ){ TabExpansion2 $inputScript $cursorColumn |% { $_.CompletionMatches } |% { ""$($_.ResultType)|$($_.CompletionText)"" } }"; session.ExecuteScriptPart(TabExpansionHelper); var teCmd = new Command("ScPsTabExpansionHelper"); teCmd.Parameters.Add("inputScript", command); teCmd.Parameters.Add("cursorColumn", command.Length); string[] teResult = session.ExecuteCommand(teCmd, false, true).Cast<string>().ToArray(); var result = new List<string>(); WrapResults3(truncatedCommand, teResult, result, aceResponse); return result; }
public NameValue[] ExecuteScript(string userName, string password, string script, string returnVariables) { if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)) { if (!userName.Contains("\\")) { userName = "******" + userName; } bool loggedIn = AuthenticationManager.Login(userName, password, false); if (!loggedIn) { throw new AuthenticationException("Unrecognized user or password mismatch."); } } using (var scriptSession = new ScriptSession(ApplicationNames.RemoteAutomation, false)) { scriptSession.ExecuteScriptPart(scriptSession.Settings.Prescript); scriptSession.ExecuteScriptPart(script); var result = new List<NameValue>(); if (scriptSession.Output.Count > 0) { result.Add(new NameValue { Name = "output", Value = scriptSession.Output.Select(p => p.Terminated ? p.Text + "\n" : p.Text).Aggregate( (current, next) => current + next) }); } foreach (string variable in returnVariables.Split('|')) { result.Add(new NameValue { Name = variable, Value = (scriptSession.GetVariable(variable) ?? string.Empty).ToString() }); } return result.ToArray(); } }
public static IEnumerable<string> FindMatches2(ScriptSession session, string command, bool aceResponse) { string lastToken; var truncatedCommand = TruncatedCommand(command, out lastToken); var teCmd = new Command("TabExpansion"); teCmd.Parameters.Add("line", command); teCmd.Parameters.Add("lastWord", lastToken); IEnumerable<string> teResult = session.ExecuteCommand(teCmd, false, true).Cast<string>(); //IEnumerable<string> teResult = session.ExecuteScriptPart(string.Format("TabExpansion \"{0}\" \"{1}\"", command, lastToken),false,true).Cast<string>(); var result = new List<string>(); WrapResults(truncatedCommand, teResult, result, aceResponse); //int prefixFileNameLength = Path.GetFileName(lastToken).Length; //string pathPrefix = lastToken.Substring(lastToken.Length - prefixFileNameLength); var splitPathResult = (session.ExecuteScriptPart(string.Format("Split-Path \"{0}*\" -IsAbsolute", lastToken), false, true).FirstOrDefault()); var isAbsolute = splitPathResult != null && (bool)splitPathResult; if (isAbsolute) { string commandLine = string.Format("Resolve-Path \"{0}*\"", lastToken); var psResults = session.ExecuteScriptPart(commandLine, false, true); IEnumerable<string> rpResult = psResults.Cast<PathInfo>().Select(p => p.Path); //result.AddRange(rpResult.Select(l => truncatedCommand + l.Path)); WrapResults(truncatedCommand, rpResult, result, aceResponse); } else { string commandLine = string.Format("Resolve-Path \"{0}*\" -Relative", lastToken); IEnumerable<string> rpResult = session.ExecuteScriptPart(commandLine, false, true).Cast<string>(); WrapResults(truncatedCommand, rpResult, result, aceResponse); } return result; }
public void OnEvent(object sender, EventArgs args) { var eventArgs = args as SitecoreEventArgs; if (eventArgs == null) { return; } Item item = eventArgs.Parameters[0] as Item; string eventName = eventArgs.EventName.Replace(':', '/'); Database database = item != null ? item.Database ?? Context.ContentDatabase : Context.ContentDatabase; Item libraryItem = database.GetItem(EventHandlerLibraryPath + eventName); if (libraryItem == null) { return; } using (var session = new ScriptSession(ApplicationNames.Default)) { foreach (Item scriptItem in libraryItem.Children) { if (item != null) { session.SetItemLocationContext(item); } session.SetVariable("eventArgs", eventArgs); string script = scriptItem["Script"]; if (!String.IsNullOrEmpty(script)) { session.ExecuteScriptPart(script); } } } }
public static ScriptSession GetSession(string persistentId, string applicanceType, bool personalizedSettings) { // sessions with no persistent ID, are just created new every time if (string.IsNullOrEmpty(persistentId)) { return new ScriptSession(applicanceType, personalizedSettings); } lock (HttpContext.Current.Session) { if (SessionExists(persistentId)) { return HttpContext.Current.Session[sessionIdPrefix + persistentId] as ScriptSession; } var session = new ScriptSession(applicanceType, personalizedSettings); session.ID = persistentId; HttpContext.Current.Session[sessionIdPrefix + persistentId] = session; session.ID = persistentId; session.Initialize(); session.ExecuteScriptPart(session.Settings.Prescript); return session; } }
public static string GetPrefix(ScriptSession session, string command) { string lastToken; var truncatedCommand = TruncatedCommand(command, out lastToken); return string.IsNullOrEmpty(lastToken) ? string.Empty : lastToken; }
protected void RunJob(ScriptSession session, string command) { try { session.ExecuteScriptPart(command); } catch (Exception ex) { var job = Sitecore.Context.Job; if (job != null) { job.Status.Failed = true; job.Status.Messages.Add("Ooops, something went wrong... Do you need assistance?"); job.Status.Messages.Add("Send an email with the stack trace to [email protected] or contact me on Twitter @AdamNaj"); job.Status.LogException(ex); } else { Log.Error("Script execution failed. Could not find command job.", ex, this); } } }
private void ExportResults(Message message) { Database scriptDb = Database.GetDatabase(message.Arguments["scriptDb"]); Item scriptItem = scriptDb.GetItem(message.Arguments["scriptID"]); using (var session = new ScriptSession(ApplicationNames.Default)) { String script = (scriptItem.Fields[ScriptItemFieldNames.Script] != null) ? scriptItem.Fields[ScriptItemFieldNames.Script].Value : string.Empty; var results = ListViewer.GetFilteredItems().Select(p => p.Original).ToList(); session.SetVariable("resultSet", results); session.SetVariable("formatProperty", ListViewer.Data.Property); var result = session.ExecuteScriptPart(script, false).First().ToString(); SheerResponse.Download(result); } }
protected virtual void JobExecute(ClientPipelineArgs args) { ScriptRunning = true; EnterScriptInfo.Visible = false; UpdateRibbon(); Settings = ApplicationSettings.GetInstance(ApplicationNames.IseConsole); var scriptSession = new ScriptSession(Settings.ApplicationName); string contextScript = ScriptSession.GetDataContextSwitch(DataContext.CurrentItem); var parameters = new object[] { scriptSession, contextScript, ScriptItemId }; var progressBoxRunner = new ScriptRunner(ExecuteInternal, parameters, true); var rnd = new Random(); Context.ClientPage.ClientResponse.SetInnerHtml( "ScriptResult", string.Format( "<div align='Center' style='padding:32px 0px 32px 0px'>Please wait, {0}</br>" + "<img src='../../../../../Console/Assets/working.gif' alt='Working' style='padding:32px 0px 32px 0px'/></div>", ExecutionMessages.PleaseWaitMessages[ rnd.Next(ExecutionMessages.PleaseWaitMessages.Length - 1)])); Monitor.Start("ScriptExecution", "UI", progressBoxRunner.Run); HttpContext.Current.Session[Monitor.JobHandle.ToString()] = scriptSession; if (Settings.SaveLastScript) { Settings.Load(); Settings.LastScript = Editor.Value; Settings.Save(); } }
protected virtual void ClientExecute(ClientPipelineArgs args) { Settings = ApplicationSettings.GetInstance(ApplicationNames.IseConsole); using(var scriptSession = new ScriptSession(Settings.ApplicationName)){ EnterScriptInfo.Visible = false; try { scriptSession.ExecuteScriptPart(Settings.Prescript); scriptSession.SetItemLocationContext(DataContext.CurrentItem); scriptSession.ExecuteScriptPart(Editor.Value); if (scriptSession.Output != null) { Context.ClientPage.ClientResponse.SetInnerHtml("Result", scriptSession.Output.ToHtml()); } } catch (Exception exc) { Context.ClientPage.ClientResponse.SetInnerHtml("Result", string.Format("<pre style='background:red;'>{0}</pre>", scriptSession.GetExceptionString(exc))); } } if (Settings.SaveLastScript) { Settings.Load(); Settings.LastScript = Editor.Value; Settings.Save(); } }
public static IEnumerable<string> GetHelp(ScriptSession session, string command) { Collection<PSParseError> errors; Collection<PSToken> tokens = PSParser.Tokenize(command, out errors); PSToken lastPsToken = tokens.Where(t => t.Type == PSTokenType.Command).LastOrDefault(); if (lastPsToken != null) { session.Output.Clear(); string lastToken = lastPsToken.Content; session.ExecuteScriptPart("Set-HostProperty -HostWidth 1000", false, true); session.ExecuteScriptPart(string.Format("Get-Help {0} -Full", lastToken), true, true); var sb = new StringBuilder(); int headerCount = 0; int lineCount = 0; if (session.Output.Count == 0 || session.Output[0].LineType == OutputLineType.Error) { return new string[] { "<div class='ps-help-command-name'> </div><div class='ps-help-header' align='center'>No Command in line or help information found</div><div class='ps-help-parameter' align='center'>Cannot provide help in this context.</div>" }; } session.Output.ForEach(l => { if (!l.Text.StartsWith(" ")) { headerCount++; } else { lineCount++; } }); bool listVIew = headerCount > lineCount; int lineNo = -1; session.Output.ForEach(l => { if (++lineNo > 0) { var line = System.Web.HttpUtility.HtmlEncode(l.Text.Trim()); line = Regex.Replace(line, @"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)", "<a target='_blank' href='$1' class='ps-link'>$1</a>"); if (listVIew) { if (lineNo < 3) { sb.AppendFormat("<div class='ps-help-firstLine'>{0}</div>", line); } else { sb.AppendFormat("{0}\n", line); } } else if (lineNo > 1) { if (lineNo == 2) { sb.AppendFormat("<div class='ps-help-command-name'>{0}</div>", line); } else if (!l.Text.StartsWith(" ")) { sb.AppendFormat("<div class='ps-help-header'>{0}</div>", line); } else if (l.Text.StartsWith(" --")) // normal line with output or example { sb.AppendFormat("{0}\n", l.Text.Substring(4)); } else if (l.Text.StartsWith(" -")) { sb.AppendFormat("<div class='ps-help-parameter'>{0}</div>", line); } else if (l.Text.StartsWith(" ")) { line = (l.Text.StartsWith(" ") ? l.Text.Substring(4) : l.Text).Replace("<", "<").Replace(">", ">"); line = urlRegex.Replace(line, "<a href='$1' target='_blank'>$1</a>"); sb.AppendFormat("{0}\n", line); } } } }); session.Output.Clear(); //IEnumerable<string> teResult = session.ExecuteScriptPart(string.Format("TabExpansion \"{0}\" \"{1}\"", command, lastToken),false,true).Cast<string>(); //List<string> result = teResult.Select(l => truncatedCommand + l).ToList(); var result = new string[] {sb.ToString()}; return result; } return new string[] {"No Command in line found - cannot provide help in this context."}; }