/// <summary> /// Provides a set of choices that enable the user to choose a single option /// from a set of options. /// </summary> /// <param name="caption">A title that proceeds the choices.</param> /// <param name="message">An introduction message that describes the /// choices.</param> /// <param name="choices">A collection of ChoiceDescription objects that describ /// each choice.</param> /// <param name="defaultChoice">The index of the label in the Choices parameter /// collection that indicates the default choice used if the user does not specify /// a choice. To indicate no default choice, set to -1.</param> /// <returns>The index of the Choices parameter collection element that corresponds /// to the option that is selected by the user.</returns> public override int PromptForChoice( string caption, string message, Collection <ChoiceDescription> choices, int defaultChoice) { // Write the caption and message strings in Blue. this.WriteLine( ConsoleColor.Blue, ConsoleColor.Black, caption + "\n" + message + "\n"); // Convert the choice collection into something that's a // little easier to work with // See the BuildHotkeysAndPlainLabels method for details. string[,] promptData = BuildHotkeysAndPlainLabels(choices); // Format the overall choice prompt string to display... StringBuilder sb = new StringBuilder(); for (int element = 0; element < choices.Count; element++) { sb.Append(String.Format( CultureInfo.CurrentCulture, "|{0}> {1} ", promptData[0, element], promptData[1, element])); } sb.Append(String.Format( CultureInfo.CurrentCulture, "[Default is ({0}]", promptData[0, defaultChoice])); // loop reading prompts until a match is made, the default is // chosen or the loop is interrupted with ctrl-C. while (true) { this.WriteLine(ConsoleColor.Cyan, ConsoleColor.Black, sb.ToString()); string data = PowerShellConsolePrinter.ReadLine(ConsolePromptDefinator).Trim().ToUpper(CultureInfo.CurrentCulture); // if the choice string was empty, use the default selection if (data.Length == 0) { return(defaultChoice); } // see if the selection matched and return the // corresponding index if it did... for (int i = 0; i < choices.Count; i++) { if (promptData[0, i] == data) { return(i); } } this.WriteErrorLine("Invalid choice: " + data); } }
/// <summary> /// Writes a newline character (carriage return) /// to the output display of the host. /// </summary> public override void WriteLine() { PowerShellConsolePrinter.RemoveLines(new List <string>() { ConsolePromptDefinator }); PowerShellConsolePrinter.WriteDelayedMessage("\n"); }
/// <summary> /// Writes a line of characters to the output display of the host /// and appends a newline character(carriage return). /// </summary> /// <param name="value">The line to be written.</param> public override void WriteLine(string value) { if (!m_SkipRemoveLines) { PowerShellConsolePrinter.RemoveLines(new List <string>() { ConsolePromptDefinator }); } PowerShellConsolePrinter.WriteDelayedMessage(value + "\n"); }
/// <summary> /// Basic script execution routine. Any runtime exceptions are /// caught and passed back to the Windows PowerShell engine to /// display. /// </summary> /// <param name="cmd">Script to run.</param> private void Execute(string cmd) { try { // Execute the command with no input. this.executeHelper(cmd, null); } catch (RuntimeException rte) { this.ReportException(rte); } PowerShellConsolePrinter.WriteDelayedMessage(((MyHostUserInterface)this.myHost.UI).ConsolePromptDefinator); }
/// <summary> /// Writes a progress report to the output display of the host. /// Wrinting a progress report is not required for the cmdlet to /// work so it is better to do nothing instead of throwing an /// exception. /// </summary> /// <param name="sourceId">Unique identifier of the source of the record. </param> /// <param name="record">A ProgressReport object.</param> public override void WriteProgress(long sourceId, ProgressRecord record) { if (PowerShellConsolePrinter.ActivityProgressbar != null) { PowerShellConsolePrinter.SetPanelStatus(record.Activity, PS_Console_Test.Helpers.Status.InProgress); PowerShellConsolePrinter.ActivityProgressbar.StepProgress(record.PercentComplete); PowerShellConsolePrinter.WriteDelayedMessage(record.CurrentOperation); } if (record.PercentComplete >= 99) { PowerShellConsolePrinter.SetPanelStatus(record.Activity + " complete!", PS_Console_Test.Helpers.Status.Success); } }
/// <summary> /// Reads a command when Enter is pressed. /// </summary> /// <param name="sender">sender</param> /// <param name="e">event</param> private void HandleEnterCommand(object sender, KeyEventArgs e) { try { lock (this.instanceLock) { string cmd = PowerShellConsolePrinter.ReadLine(((MyHostUserInterface)this.myHost.UI).ConsolePromptDefinator); if (!String.IsNullOrEmpty(cmd)) { this.Execute(cmd); } } } catch (Exception exception) { this.myHost.UI.WriteErrorLine(exception.ToString()); } }
/// <summary> /// Writes a line of characters to the output display of the host /// with foreground and background colors and appends a newline (carriage return). /// </summary> /// <param name="foregroundColor">The forground color of the display. </param> /// <param name="backgroundColor">The background color of the display. </param> /// <param name="value">The line to be written.</param> public override void WriteLine( ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) { ConsoleColor oldFg = ColorExtension.GetConsoleColor(PowerShellConsolePrinter.TextColor); ConsoleColor oldBg = ColorExtension.GetConsoleColor(PowerShellConsolePrinter.BackgroundColor); PowerShellConsolePrinter.RemoveLines(new List <string>() { ConsolePromptDefinator }); PowerShellConsolePrinter.TextColor = ColorExtension.GetColor(foregroundColor); PowerShellConsolePrinter.BackgroundColor = ColorExtension.GetColor(backgroundColor); PowerShellConsolePrinter.WriteDelayedMessage(value + "\n"); PowerShellConsolePrinter.TextColor = ColorExtension.GetColor(oldFg); PowerShellConsolePrinter.BackgroundColor = ColorExtension.GetColor(oldBg); }
/// <summary> /// Implements the basic listener loop. It sets up the ctrl-C handler, then /// reads a command from the user, executes it and repeats until the ShouldExit /// flag is set. /// </summary> public void Run() { // Set up the control-C handler. PowerShellConsolePrinter.CtrlCHandler += new KeyEventHandler(this.HandleControlC); //PowerShellConsolePrinter.EnterKeyHandler += new KeyEventHandler(this.HandleEnterCommand); //Console.TreatControlCAsInput = false; //this.currentPowerShell.BeginStop //this.currentPowerShell.Runspace = this.myRunSpace; // loop reading commands to execute until ShouldExit is set by // the user calling "exit". string prompt; if (this.myHost.IsRunspacePushed) { prompt = string.Format("[{0}] PS>", this.myRunSpace.ConnectionInfo.ComputerName); } else { prompt = "PS>"; } ((MyHostUserInterface)this.myHost.UI).ConsolePromptDefinator = String.IsNullOrEmpty(prompt) ? "PS>" : prompt; //this.myHost.UI.Write(ConsoleColor.Cyan, ConsoleColor.Black, prompt); while (!this.ShouldExit) { System.Threading.Thread.Sleep(100); string cmd = PowerShellConsolePrinter.ReadLine(prompt); if (!String.IsNullOrEmpty(cmd)) { lock (this.instanceLock) { this.Execute(cmd); } } } // Exit with the desired exit code that was set by exit command. // This is set in the host by the MyHost.SetShouldExit() implementation. //Environment.Exit(this.ExitCode); }
/// <summary> /// Reads a pressed, released, or pressed and released keystroke /// from the keyboard device, blocking processing until a keystroke /// is typed that matches the specified keystroke options. This /// functionality is not implemented. The call fails with an /// exception. /// </summary> /// <param name="options">A bit mask of the options to be used when /// reading from the keyboard. </param> /// <returns>KeyInfo</returns> public override KeyInfo ReadKey(ReadKeyOptions options) { PowerShellConsolePrinter.WaitForKey = true; KeyInfo keyInfo = new KeyInfo(); PowerShellConsolePrinter.KeyPressedHandler += (object sender, System.Windows.Forms.KeyPressEventArgs e) => { if (!options.HasFlag(ReadKeyOptions.NoEcho)) { PowerShellConsolePrinter.WriteDelayedMessage((e.KeyChar).ToString()); } keyInfo.KeyDown = true; keyInfo.Character = e.KeyChar; }; while (!keyInfo.KeyDown) { //Wait for the key } return(keyInfo); //throw new NotImplementedException("The ReadKey() method is not implemented by MyRawUserInterface."); }
/// <summary> /// Prompts the user for input. /// </summary> /// <param name="caption">Text that preceeds the prompt (a title).</param> /// <param name="message">Text of the prompt.</param> /// <param name="descriptions">A collection of FieldDescription objects /// that contains the user input.</param> /// <returns>A dictionary object that contains the results of the user prompts.</returns> public override Dictionary <string, PSObject> Prompt( string caption, string message, Collection <FieldDescription> descriptions) { this.Write(ConsoleColor.Blue, ConsoleColor.Black, caption + "\n" + message + " "); Dictionary <string, PSObject> results = new Dictionary <string, PSObject>(); foreach (FieldDescription fd in descriptions) { string[] label = GetHotkeyAndLabel(fd.Label); SecureString secureStr = new SecureString(); this.WriteLine(label[1]); string userData = null; if (String.IsNullOrEmpty(caption) && String.IsNullOrEmpty(message)) { userData = null; this.Write(ConsoleColor.Blue, ConsoleColor.Black, fd.Name + ":>"); //PowerShellConsolePrinter.WriteDelayedMessage(ConsolePromptDefinator); while (userData == null) { System.Threading.Thread.Sleep(100); userData = PowerShellConsolePrinter.ReadLine(":>"); if (String.IsNullOrEmpty(userData)) { userData = null; } } if (!String.IsNullOrEmpty(userData)) { userData = userData.Trim(Environment.NewLine.ToCharArray()); } PowerShellConsolePrinter.RemoveLines(new List <string>() { ConsolePromptDefinator }); if (fd.ParameterTypeName == "SecureString" && !String.IsNullOrEmpty(userData)) { foreach (char c in userData.ToCharArray()) { secureStr.AppendChar(c); } results[fd.Name] = PSObject.AsPSObject(secureStr); } } if (userData == null) { return(null); } if (fd.ParameterTypeName != "SecureString") { results[fd.Name] = PSObject.AsPSObject(userData); } } return(results); }
/// <summary> /// Reads characters that are entered by the user until a /// newline (carriage return) is encountered. /// </summary> /// <returns>The characters entered by the user.</returns> public override string ReadLine() { return(PowerShellConsolePrinter.ReadLine(ConsolePromptDefinator)); }