public static string GetPrefix(ScriptSession session, string command) { string lastToken; TruncatedCommand(session, command, out lastToken); return(string.IsNullOrEmpty(lastToken) ? string.Empty : lastToken); }
/// <summary> /// Not implemented by this example class. The call fails with /// a NotImplementedException exception. /// </summary> public override void EnterNestedPrompt() { NestedLevel++; UiNestedLevel++; var resultSig = Guid.NewGuid().ToString(); var str = new UrlString(UIUtil.GetUri("control:PowerShellConsole")); str.Add("sid", resultSig); str.Add("fc", privateData.ForegroundColor.ToString()); str.Add("bc", privateData.BackgroundColor.ToString()); str.Add("id", SessionKey); str.Add("suspend", "true"); var currentNesting = NestedLevel; var jobManager = TypeResolver.ResolveFromCache <IJobManager>(); var job = jobManager.GetContextJob(); job.MessageQueue.PutMessage( new ShowSuspendDialogMessage(SessionKey, str.ToString(), "900", "600", new Hashtable()) { ReceiveResults = true, }); var scriptSession = ScriptSessionManager.GetSession(SessionKey); while (currentNesting <= UiNestedLevel) { if (currentNesting == UiNestedLevel) { if (scriptSession.ImmediateCommand is string commandString) { scriptSession.ImmediateCommand = null; PowerShellLog.Info($"Executing a command in ScriptSession '{SessionKey}'."); PowerShellLog.Debug(commandString); try { var result = scriptSession.InvokeInNewPowerShell(commandString, ScriptSession.OutTarget.OutHost); } catch (Exception ex) { PowerShellLog.Error("Error while executing Debugging command.", ex); UI.WriteErrorLine(ScriptSession.GetExceptionString(ex)); } } else { Thread.Sleep(20); } } } job.MessageQueue.GetResult(); ScriptSessionManager.GetSession(SessionKey).InvokeInNewPowerShell("exit", ScriptSession.OutTarget.OutHost); }
private static string TruncatedCommand(ScriptSession session, string command, out string lastToken) { if (session.TryInvokeInRunningSession(ReplacementIndexHelper)) { var teCmd = new Command("ScPsReplacementIndex"); teCmd.Parameters.Add("inputScript", command); teCmd.Parameters.Add("cursorColumn", command.Length); List <object> psResult; if (session.TryInvokeInRunningSession(teCmd, out psResult)) { var teResult = psResult.Cast <int>().FirstOrDefault(); lastToken = command.Substring(teResult); return(command.Substring(0, teResult)); } } lastToken = string.Empty; return(string.Empty); }
public static ScriptSession GetSession(string persistentId, string applianceType, bool personalizedSettings) { // sessions with no persistent ID, are just created new every time var autoDispose = string.IsNullOrEmpty(persistentId); if (autoDispose) { persistentId = Guid.NewGuid().ToString(); } var sessionKey = GetSessionKey(persistentId); lock (sessions) { if (SessionExists(persistentId)) { return(HttpRuntime.Cache[sessionKey] as ScriptSession); } var session = new ScriptSession(applianceType, personalizedSettings) { ID = persistentId, }; PowerShellLog.Debug($"New Script Session with key '{sessionKey}' created."); if (autoDispose) { // this only should be set if new session has been created - do not change! session.AutoDispose = true; } var expiration = Sitecore.Configuration.Settings.GetIntSetting(expirationSetting, 30); var preventSessionCleanup = Sitecore.Configuration.Settings.GetBoolSetting(preventSessionCleanupSetting, false); HttpRuntime.Cache.Add(sessionKey, session, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, expiration, 0), preventSessionCleanup ? CacheItemPriority.NotRemovable : CacheItemPriority.Normal, CacheItemRemoved); sessions.Add(sessionKey); session.ID = persistentId; session.Key = sessionKey; session.Initialize(); return(session); } }
public static IEnumerable <string> GetHelp(ScriptSession session, string command) { Collection <PSParseError> errors; var tokens = PSParser.Tokenize(command, out errors); var lastPsToken = tokens.LastOrDefault(t => t.Type == PSTokenType.Command); if (lastPsToken != null) { session.Output.Clear(); var lastToken = lastPsToken.Content; session.SetVariable("helpFor", lastToken); var platformmodule = ModuleManager.GetModule("Platform"); var scriptItem = Database.GetDatabase(platformmodule.Database) .GetItem(platformmodule.Path + "/Internal/Context Help/Command Help") ?? Factory.GetDatabase(ApplicationSettings.ScriptLibraryDb) .GetItem(ApplicationSettings.ScriptLibraryPath + "Internal/Context Help/Command Help"); if (!scriptItem.IsPowerShellScript()) { return(new[] { Texts.General_Operation_failed_wrong_data_template }); } session.ExecuteScriptPart(scriptItem[Templates.Script.Fields.ScriptBody], true, true); if (session.Output.Count == 0 || session.Output[0].LineType == OutputLineType.Error) { return(new[] { "<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>" }); } var sb = new StringBuilder(); session.Output.ForEach(l => sb.Append(l.Text)); session.Output.Clear(); var result = new[] { sb.ToString() }; return(result); } return(new[] { "No Command in line found - cannot provide help in this context." }); }
public static IEnumerable <string> FindMatches(ScriptSession session, string command, bool aceResponse) { string lastToken; //command = command.Trim(); var truncatedCommand = TruncatedCommand(session, command, out lastToken) ?? string.Empty; var truncatedLength = truncatedCommand.Length; var options = Completers; lastToken = lastToken.Trim(); if (!string.IsNullOrEmpty(lastToken) && lastToken.Trim().StartsWith("[")) { if (lastToken.IndexOf("]", StringComparison.Ordinal) < 0) { return(CompleteTypes(lastToken, truncatedLength)); } if (staticFuncRegex.IsMatch(lastToken)) { var matches = staticFuncRegex.Matches(lastToken); var className = matches[0].Groups["class"].Value; var methodName = matches[0].Groups["method"].Value; const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy; // look in acceelerators first if (!className.Contains('.') && TypeAccelerators.AllAccelerators.ContainsKey(className)) { return(GetMethodSignatures(TypeAccelerators.AllAccelerators[className], methodName, bindingFlags, truncatedLength)); } // check the loaded assemblies foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) { try { var type = assembly .GetExportedTypes() .FirstOrDefault( aType => aType.FullName.Equals(className, StringComparison.OrdinalIgnoreCase)); if (type != null) { return(GetMethodSignatures(type, methodName, bindingFlags, truncatedLength)); } } catch { // ignore on purpose } } } } if (!string.IsNullOrEmpty(lastToken) && (lastToken.StartsWith("$") || lastToken.StartsWith("["))) { MatchCollection matches = null; var matched = false; if (variableFuncRegex.IsMatch(lastToken)) { matches = variableFuncRegex.Matches(lastToken); matched = true; } else if (staticExpressionRegex.IsMatch(lastToken)) { matches = staticExpressionRegex.Matches(lastToken); matched = true; } if (matched) { //var matches = variableFuncRegex.Matches(lastToken); var expression = matches[0].Groups["expression"].Value; var methodName = matches[0].Groups["method"].Value; Type objectType = null; try { if (session.TryInvokeInRunningSession(expression, out var objectValue, false)) { if (objectValue != null && objectValue.Count > 0) { objectType = objectValue[0].GetType(); } } } catch //(Exception ex) - variable may not be found if session does not exist { var varName = variableRegex.Matches(lastToken)[0].Value; var message = $"Variable {varName} not found in session. Execute script first."; return(new List <string> { $"Signature|{message}|{truncatedLength}|{message}" }); } if (objectType != null) { const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy; return(GetMethodSignatures(objectType, methodName, bindingFlags, truncatedLength)); } } } session.TryInvokeInRunningSession(TabExpansionHelper); var teCmd = new Command("ScPsTabExpansionHelper"); teCmd.Parameters.Add("inputScript", command); teCmd.Parameters.Add("cursorColumn", command.Length); teCmd.Parameters.Add("options", options); var teResult = new string[0]; List <object> results; if (session.TryInvokeInRunningSession(teCmd, out results, true)) { teResult = results.Cast <string>().ToArray(); } var result = new List <string>(); WrapResults(truncatedCommand, teResult, result, aceResponse); return(result); }
public static void RemoveSession(ScriptSession session) { RemoveSession(session.Key); }