コード例 #1
0
 private void ShowError(PSHostUserInterface hostUI)
 {
     if (_error != null)
     {
         hostUI.WriteErrorLine(_error);
     }
 }
コード例 #2
0
ファイル: Tracer.cs プロジェクト: svetek/Profiler
        public static void Patch(int version, EngineIntrinsics context, PSHostUserInterface ui)
        {
            Clear();

            var uiFieldName = version >= 7 ? "_externalUI" : "externalUI";
            // we get InternalHostUserInterface, grab external ui from that and replace it with ours
            var externalUIField = ui.GetType().GetField(uiFieldName, BindingFlags.Instance | BindingFlags.NonPublic);
            var externalUI      = (PSHostUserInterface)externalUIField.GetValue(ui);

            // replace it with out patched up UI that writes to profiler on debug
            externalUIField.SetValue(ui, new ProfilerUI(externalUI));

            ResetUI = () =>
            {
                externalUIField.SetValue(ui, externalUI);
            };

            // getting MethodInfo of context._context.Debugger.TraceLine
            var bf = BindingFlags.NonPublic | BindingFlags.Instance;
            var contextInternal = context.GetType().GetField("_context", bf).GetValue(context);
            var debugger        = contextInternal.GetType().GetProperty("Debugger", bf).GetValue(contextInternal);
            var debuggerType    = debugger.GetType();

            var callStackField = debuggerType.GetField("_callStack", BindingFlags.Instance | BindingFlags.NonPublic);
            var _callStack     = callStackField.GetValue(debugger);

            var callStackType = _callStack.GetType();

            var countProperty = callStackType.GetProperty("Count", BindingFlags.Instance | BindingFlags.NonPublic);
            var getCount      = countProperty.GetMethod;
            var empty         = new object[0];
            var stack         = callStackField.GetValue(debugger);
            var initialLevel  = (int)getCount.Invoke(stack, empty);

            var lastFunctionContextMethod = callStackType.GetMethod("LastFunctionContext", BindingFlags.Instance | BindingFlags.NonPublic);

            object functionContext1        = lastFunctionContextMethod.Invoke(callStackField.GetValue(debugger), empty);
            var    functionContextType     = functionContext1.GetType();
            var    scriptBlockField        = functionContextType.GetField("_scriptBlock", BindingFlags.Instance | BindingFlags.NonPublic);
            var    currentPositionProperty = functionContextType.GetProperty("CurrentPosition", BindingFlags.Instance | BindingFlags.NonPublic);

            var scriptBlock1 = (ScriptBlock)scriptBlockField.GetValue(functionContext1);
            var extent1      = (IScriptExtent)currentPositionProperty.GetValue(functionContext1);

            TraceLine = () =>
            {
                var    callStack       = callStackField.GetValue(debugger);
                var    level           = (int)getCount.Invoke(callStack, empty) - initialLevel;
                object functionContext = lastFunctionContextMethod.Invoke(callStack, empty);
                var    scriptBlock     = (ScriptBlock)scriptBlockField.GetValue(functionContext);
                var    extent          = (IScriptExtent)currentPositionProperty.GetValue(functionContext);

                Trace(extent, scriptBlock, level);
            };

            // Add another event to the top apart from the scriptblock invocation
            // in Trace-ScriptInternal, this makes it more consistently work on first
            // run. Without this, the triggering line sometimes does not show up as 99.9%
            TraceLine();
        }
コード例 #3
0
 internal void ReportEngineStartupError(string resourceString, params object[] arguments)
 {
     try
     {
         Cmdlet cmdlet;
         string str;
         if (this.IsModuleCommandCurrentlyRunning(out cmdlet, out str))
         {
             RuntimeException replaceParentContainsErrorRecordException = InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, str, resourceString, arguments);
             cmdlet.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
         }
         else
         {
             PSHost engineHostInterface = this.EngineHostInterface;
             if (engineHostInterface != null)
             {
                 PSHostUserInterface uI = engineHostInterface.UI;
                 if (uI != null)
                 {
                     uI.WriteErrorLine(StringUtil.Format(resourceString, arguments));
                 }
             }
         }
     }
     catch (Exception exception2)
     {
         CommandProcessorBase.CheckForSevereException(exception2);
     }
 }
コード例 #4
0
 internal void ReportEngineStartupError(Exception e)
 {
     try
     {
         Cmdlet cmdlet;
         string str;
         if (this.IsModuleCommandCurrentlyRunning(out cmdlet, out str))
         {
             ErrorRecord      errorRecord = null;
             RuntimeException replaceParentContainsErrorRecordException = e as RuntimeException;
             errorRecord = (replaceParentContainsErrorRecordException != null) ? new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException) : new ErrorRecord(e, str, ErrorCategory.OperationStopped, null);
             cmdlet.WriteError(errorRecord);
         }
         else
         {
             PSHost engineHostInterface = this.EngineHostInterface;
             if (engineHostInterface != null)
             {
                 PSHostUserInterface uI = engineHostInterface.UI;
                 if (uI != null)
                 {
                     uI.WriteErrorLine(e.Message);
                 }
             }
         }
     }
     catch (Exception exception2)
     {
         CommandProcessorBase.CheckForSevereException(exception2);
     }
 }
コード例 #5
0
 internal void ReportEngineStartupError(ErrorRecord errorRecord)
 {
     try
     {
         Cmdlet cmdlet;
         string str;
         if (this.IsModuleCommandCurrentlyRunning(out cmdlet, out str))
         {
             cmdlet.WriteError(errorRecord);
         }
         else
         {
             PSHost engineHostInterface = this.EngineHostInterface;
             if (engineHostInterface != null)
             {
                 PSHostUserInterface uI = engineHostInterface.UI;
                 if (uI != null)
                 {
                     uI.WriteErrorLine(errorRecord.ToString());
                 }
             }
         }
     }
     catch (Exception exception)
     {
         CommandProcessorBase.CheckForSevereException(exception);
     }
 }
コード例 #6
0
        public void DetachFromHost()
        {
            if (host == null)
            {
                return;
            }

            const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;

            // When PowerShell went open source, they renamed the private variables to have _underbarPrefixes
            if (host.Version >= new Version(6, 0))
            {
                object    uiRef           = host.GetType().GetField("_internalUIRef", flags)?.GetValue(host);
                object    ui              = uiRef.GetType().GetProperty("Value", flags).GetValue(uiRef, null);
                FieldInfo externalUIField = ui.GetType().GetField("_externalUI", flags);
                if (externalUIField.GetValue(ui) == this)
                {
                    externalUIField.SetValue(ui, externalUI);
                }
            }
            else
            {
                // Try the WindowsPowerShell version:
                object    uiRef           = host.GetType().GetField("internalUIRef", flags).GetValue(host);
                object    ui              = uiRef.GetType().GetProperty("Value", flags).GetValue(uiRef, null);
                FieldInfo externalUIField = ui.GetType().GetField("externalUI", flags);
                if (externalUIField.GetValue(ui) == this)
                {
                    externalUIField.SetValue(ui, externalUI);
                }
            }

            externalUI = null;
            host       = null;
        }
コード例 #7
0
        public void AttachToHost(PSHost host)
        {
            if (this.host != null)
            {
                return;
            }
            if (host == null)
            {
                return;
            }

            const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;

            // When PowerShell went open source, they renamed the private variables to have _underbarPrefixes
            if (host.Version >= new Version(6, 0))
            {
                object    uiRef           = host.GetType().GetField("_internalUIRef", flags)?.GetValue(host);
                object    ui              = uiRef.GetType().GetProperty("Value", flags).GetValue(uiRef, null);
                FieldInfo externalUIField = ui.GetType().GetField("_externalUI", flags);
                externalUI = (PSHostUserInterface)externalUIField.GetValue(ui);
                externalUIField.SetValue(ui, this);
            }
            else
            {
                // Try the WindowsPowerShell version:
                object    uiRef           = host.GetType().GetField("internalUIRef", flags).GetValue(host);
                object    ui              = uiRef.GetType().GetProperty("Value", flags).GetValue(uiRef, null);
                FieldInfo externalUIField = ui.GetType().GetField("externalUI", flags);
                externalUI = (PSHostUserInterface)externalUIField.GetValue(ui);
                externalUIField.SetValue(ui, this);
            }

            this.host = host;
        }
コード例 #8
0
        /// <summary>
        /// Creates a new instance of the ConsoleServicePSHostUserInterface
        /// class with the given IConsoleHost implementation.
        /// </summary>
        /// <param name="powerShellContext">The PowerShellContext to use for executing commands.</param>
        /// <param name="logger">An ILogger implementation to use for this host.</param>
        /// <param name="internalHost">The InternalHost instance from the origin runspace.</param>
        public TerminalPSHostUserInterface(
            PowerShellContextService powerShellContext,
            ILogger logger,
            PSHost internalHost)
            : base(
                powerShellContext,
                new TerminalPSHostRawUserInterface(logger, internalHost),
                logger)
        {
            this.internalHostUI  = internalHost.UI;
            this.consoleReadLine = new ConsoleReadLine(powerShellContext);

            // Set the output encoding to UTF-8 so that special
            // characters are written to the console correctly
            System.Console.OutputEncoding = System.Text.Encoding.UTF8;

            System.Console.CancelKeyPress +=
                (obj, args) =>
            {
                if (!this.IsNativeApplicationRunning)
                {
                    // We'll handle Ctrl+C
                    args.Cancel = true;
                    this.SendControlC();
                }
            };
        }
コード例 #9
0
        InternalHostUserInterface(PSHostUserInterface externalUI, InternalHost parentHost)
        {
            // externalUI may be null

            _externalUI = externalUI;

            // parent may not be null, however

            Dbg.Assert(parentHost != null, "parent may not be null");
            if (parentHost == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(parentHost));
            }

            _parent = parentHost;

            PSHostRawUserInterface rawui = null;

            if (externalUI != null)
            {
                rawui = externalUI.RawUI;
            }

            _internalRawUI = new InternalHostRawUserInterface(rawui, _parent);
        }
コード例 #10
0
            internal PromptResponse PromptUser(PSHostUserInterface console)
            {
                char ch = char.MinValue;

                for (int i = 0; i < this.actualPrompt.Count; i++)
                {
                    if (i < (this.actualPrompt.Count - 1))
                    {
                        console.WriteLine(this.actualPrompt[i]);
                    }
                    else
                    {
                        console.Write(this.actualPrompt[i]);
                    }
                }
                do
                {
                    this.callingCmdlet.CheckStopProcessing();
                    switch (console.RawUI.ReadKey(ReadKeyOptions.IncludeKeyUp | ReadKeyOptions.NoEcho).Character)
                    {
                    case 'q':
                    case 'Q':
                        console.WriteLine();
                        return(PromptResponse.Quit);

                    case ' ':
                        console.WriteLine();
                        return(PromptResponse.NextPage);
                    }
                }while (ch != '\r');
                console.WriteLine();
                return(PromptResponse.NextLine);
            }
コード例 #11
0
ファイル: OutConsole.cs プロジェクト: 5l1v3r1/PowerShell-7
        /// <summary>
        /// Just hook up the LineOutput interface.
        /// </summary>
        protected override void BeginProcessing()
        {
            PSHostUserInterface console    = this.Host.UI;
            ConsoleLineOutput   lineOutput = new ConsoleLineOutput(console, false, new TerminatingErrorContext(this));

            ((OutputManagerInner)this.implementation).LineOutput = lineOutput;

            MshCommandRuntime mrt = this.CommandRuntime as MshCommandRuntime;

            if (mrt != null)
            {
                mrt.MergeUnclaimedPreviousErrorResults = true;
            }

            if (Transcript)
            {
                _transcribeOnlyCookie = Host.UI.SetTranscribeOnly();
            }

            // This needs to be done directly through the command runtime, as Out-Default
            // doesn't actually write pipeline objects.
            base.BeginProcessing();

            if (Context.CurrentCommandProcessor.CommandRuntime.OutVarList != null)
            {
                _outVarResults = new List <PSObject>();
            }
        }
コード例 #12
0
ファイル: SecurityUtils.cs プロジェクト: modulexcite/pash-1
        internal static SecureString PromptForSecureString(PSHostUserInterface hostUI, string prompt)
        {
            hostUI.Write(prompt);
            SecureString secureString = hostUI.ReadLineAsSecureString();

            hostUI.WriteLine("");
            return(secureString);
        }
コード例 #13
0
 private HostIOInterceptor()
 {
     externalUI  = null;
     subscribers = new List <WeakReference>();
     writeCache  = new StringBuilder();
     paused      = false;
     host        = null;
 }
コード例 #14
0
        internal Host(PoshConsole control, Options options)
        {
            PoshConsole = control;
            _options    = options;
            _UI         = new HostUI(PoshConsole);

            MakeConsole();
        }
コード例 #15
0
ファイル: OutConsole.cs プロジェクト: 5l1v3r1/PowerShell-7
        /// <summary>
        /// Just hook up the LineOutput interface.
        /// </summary>
        protected override void BeginProcessing()
        {
            PSHostUserInterface console    = this.Host.UI;
            ConsoleLineOutput   lineOutput = new ConsoleLineOutput(console, _paging, new TerminatingErrorContext(this));

            ((OutputManagerInner)this.implementation).LineOutput = lineOutput;
            base.BeginProcessing();
        }
コード例 #16
0
        internal Host(PoshConsole control, Panel progress, Options options)
        {
            PoshConsole = control;
            _options    = options;
            _UI         = new HostUI(PoshConsole, progress);

            MakeConsole();
        }
コード例 #17
0
 public PsEntrypointPSHost()
 {
     m_InstanceId       = Guid.NewGuid();
     m_Name             = "PSDockerHost";
     m_CurrentCulture   = System.Threading.Thread.CurrentThread.CurrentCulture;
     m_CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
     m_UI = new HostUI();
 }
コード例 #18
0
ファイル: CmdletNotify.cs プロジェクト: neolithos/neocmd
        /// <summary></summary>
        /// <param name="ui"></param>
        /// <param name="activity"></param>
        /// <param name="text"></param>
        public CmdletProgress(PSHostUserInterface ui, string activity, string statusDescription)
        {
            this.sourceId = Environment.TickCount;
            this.ui       = ui;
            this.progress = new ProgressRecord(Math.Abs(activity.GetHashCode()), activity, statusDescription);

            ui.WriteProgress(sourceId, progress);
        }         // ctor
コード例 #19
0
ファイル: TaskHostUI.cs プロジェクト: sharpjs/PSConcurrent
        private string _header;                         // Header to print when at BOL

        internal TaskHostUI(PSHostUserInterface ui, ConsoleState console, int taskId)
        {
            _ui      = ui ?? throw new ArgumentNullException(nameof(ui));
            _console = console ?? throw new ArgumentNullException(nameof(console));
            _taskId  = taskId;
            _taskBol = true;
            _header  = $"Task {taskId}";
        }
コード例 #20
0
 public AEMHelper(Action <ErrorRecord> errorAction, Action <string> verboseAction, Action <string> warningAction,
                  PSHostUserInterface ui, StorageManagementClient storageClient, AzureSubscription subscription)
 {
     this._ErrorAction   = errorAction;
     this._VerboseAction = verboseAction;
     this._WarningAction = warningAction;
     this._UI            = ui;
     this._StorageClient = storageClient;
     this._Subscription  = subscription;
 }
コード例 #21
0
ファイル: InternalHost.cs プロジェクト: modulexcite/pash-1
        internal InternalHost(PSHost externalHost, ExecutionContext executionContext)
        {
            this.externalHostRef  = new ObjectRef <PSHost>(externalHost);
            this.executionContext = executionContext;
            PSHostUserInterface uI = externalHost.UI;

            this.internalUIRef = new ObjectRef <InternalHostUserInterface>(new InternalHostUserInterface(uI, this));
            this.zeroGuid      = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
            this.idResult      = this.zeroGuid;
        }
コード例 #22
0
 public Host(string name, Version version, PSHostUserInterface hostUI,
             RunspaceConfiguration runspaceConfiguration)
 {
     _pushedRunspaces       = new Stack <Runspace>();
     _name                  = name;
     _version               = version;
     _hostUI                = hostUI;
     _runspaceConfiguration = runspaceConfiguration;
     _exitEvent             = new ManualResetEvent(false);
 }
コード例 #23
0
        /// <summary>
        /// present a prompt for a SecureString data
        /// </summary>
        ///
        /// <param name="hostUI"> ref to host ui interface </param>
        ///
        /// <param name="prompt"> prompt text </param>
        ///
        /// <returns> user input as secure string </returns>
        ///
        /// <remarks>  </remarks>
        ///
        internal static SecureString PromptForSecureString(PSHostUserInterface hostUI,
                                                           string prompt)
        {
            SecureString ss = null;

            hostUI.Write(prompt);
            ss = hostUI.ReadLineAsSecureString();
            hostUI.WriteLine(string.Empty);

            return(ss);
        }
コード例 #24
0
        internal CommandLineParameterParser(PSHostUserInterface hostUI, string bannerText, string helpText)
        {
            if (hostUI == null)
            {
                throw new PSArgumentNullException("hostUI");
            }
            _hostUI = hostUI;

            _bannerText = bannerText;
            _helpText   = helpText;
        }
コード例 #25
0
        public ScriptHost(IUpgradeLog logger)
        {
            _hostUI = new ScriptHostUI(logger);
            _id     = Guid.NewGuid();
            _originalCultureInfo   = Thread.CurrentThread.CurrentCulture;
            _originalUICultureInfo = Thread.CurrentThread.CurrentUICulture;

            var assembly = System.Reflection.Assembly.GetExecutingAssembly();
            var fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);

            _version = new Version(fvi.FileMajorPart, fvi.FileMinorPart, fvi.FileBuildPart, fvi.FilePrivatePart);
        }
コード例 #26
0
        // Maybe we shouldn't do update check and show notification when it's from a mini-shell, meaning when
        // 'ConsoleShell.Start' is not called by 'ManagedEntrance.Start'.
        // But it seems so unusual that it's probably not worth bothering. Also, a mini-shell probably should
        // just disable the update notification feature by setting the opt-out environment variable.

        internal static void ShowUpdateNotification(PSHostUserInterface hostUI)
        {
            if (!Directory.Exists(s_cacheDirectory))
            {
                return;
            }

            if (TryParseUpdateFile(
                    updateFilePath: out _,
                    out SemanticVersion lastUpdateVersion,
                    lastUpdateDate: out _) &&
                lastUpdateVersion != null)
            {
                string releaseTag = lastUpdateVersion.ToString();
                string notificationMsgTemplate = s_notificationType == NotificationType.LTS
                    ? ManagedEntranceStrings.LTSUpdateNotificationMessage
                    : string.IsNullOrEmpty(lastUpdateVersion.PreReleaseLabel)
                        ? ManagedEntranceStrings.StableUpdateNotificationMessage
                        : ManagedEntranceStrings.PreviewUpdateNotificationMessage;

                string notificationColor = string.Empty;
                string resetColor        = string.Empty;

                string line2Padding = string.Empty;
                string line3Padding = string.Empty;

                // We calculate how much whitespace we need to make it look nice
                if (hostUI.SupportsVirtualTerminal)
                {
                    // Swaps foreground and background colors.
                    notificationColor = "\x1B[7m";
                    resetColor        = "\x1B[0m";

                    // The first line is longest, if the message changes, this needs to be updated
                    int line1Length = notificationMsgTemplate.IndexOf('\n');
                    int line2Length = notificationMsgTemplate.IndexOf('\n', line1Length + 1);
                    int line3Length = notificationMsgTemplate.IndexOf('\n', line2Length + 1);
                    line3Length -= line2Length + 1;
                    line2Length -= line1Length + 1;

                    line2Padding = line2Padding.PadRight(line1Length - line2Length + releaseTag.Length);
                    // 3 represents the extra placeholder in the template
                    line3Padding = line3Padding.PadRight(line1Length - line3Length + 3);
                }

                string notificationMsg = string.Format(CultureInfo.CurrentCulture, notificationMsgTemplate, releaseTag, notificationColor, resetColor, line2Padding, line3Padding);

                hostUI.WriteLine();
                hostUI.WriteLine(notificationMsg);
            }
        }
コード例 #27
0
ファイル: ConsoleLineOutput.cs プロジェクト: x1m0/PowerShell
        /// <summary>
        /// constructor for the ConsoleLineOutput
        /// </summary>
        /// <param name="hostConsole">PSHostUserInterface to wrap</param>
        /// <param name="paging">true if we require prompting for page breaks</param>
        /// <param name="errorContext">error context to throw exceptions</param>
        internal ConsoleLineOutput(PSHostUserInterface hostConsole, bool paging, TerminatingErrorContext errorContext)
        {
            if (hostConsole == null)
            {
                throw PSTraceSource.NewArgumentNullException("hostConsole");
            }
            if (errorContext == null)
            {
                throw PSTraceSource.NewArgumentNullException("errorContext");
            }

            _console      = hostConsole;
            _errorContext = errorContext;

            if (paging)
            {
                tracer.WriteLine("paging is needed");
                // if we need to do paging, instantiate a prompt handler
                // that will take care of the screen interaction
                string promptString = StringUtil.Format(FormatAndOut_out_xxx.ConsoleLineOutput_PagingPrompt);
                _prompt = new PromptHandler(promptString, this);
            }


            PSHostRawUserInterface raw = _console.RawUI;

            if (raw != null)
            {
                tracer.WriteLine("there is a valid raw interface");
#if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE
                // create a test instance with fake behavior
                this._displayCellsPSHost = new DisplayCellsTest();
#else
                // set only if we have a valid raw interface
                _displayCellsPSHost = new DisplayCellsPSHost(raw);
#endif
            }

            // instantiate the helper to do the line processing when ILineOutput.WriteXXX() is called
            WriteLineHelper.WriteCallback wl = new WriteLineHelper.WriteCallback(this.OnWriteLine);
            WriteLineHelper.WriteCallback w  = new WriteLineHelper.WriteCallback(this.OnWrite);

            if (_forceNewLine)
            {
                _writeLineHelper = new WriteLineHelper(/*lineWrap*/ false, wl, null, this.DisplayCells);
            }
            else
            {
                _writeLineHelper = new WriteLineHelper(/*lineWrap*/ false, wl, w, this.DisplayCells);
            }
        }
コード例 #28
0
 public Host(WpfTerminalControl uicontrol)
 {
     if (uicontrol == null)
     {
         throw new ArgumentNullException(nameof(uicontrol));
     }
     this.InstanceId = Guid.NewGuid();
     this.HostUI     = new HostUI(uicontrol);
     _uI             = this.HostUI;
     this.Name       = "Host1";
     this.Version    = Version.Parse("0.1");
     _CurrentCulture = System.Threading.Thread.CurrentThread.CurrentCulture ??
                       System.Threading.Thread.CurrentThread.CurrentUICulture ?? CultureInfo.InstalledUICulture;
     _CurrentUICulture = _CurrentCulture;
 }
コード例 #29
0
        /// <summary>
        /// Write a line by delegating to the writer underneath.
        /// </summary>
        /// <param name="s"></param>
        internal override void WriteLine(string s)
        {
            CheckStopProcessing();

            s = PSHostUserInterface.GetOutputString(s, isHost: false);

            if (_suppressNewline)
            {
                _writer.Write(s);
            }
            else
            {
                _writer.WriteLine(s);
            }
        }
コード例 #30
0
    public Poco()
    {
        var      runspace             = Runspace.DefaultRunspace;
        Pipeline pipeline             = runspace.CreateNestedPipeline("Get-Variable host -ValueOnly", false);
        Collection <PSObject> results = pipeline.Invoke();

        if (results.Count > 0)
        {
            var host = results[0].BaseObject as PSHost;
            if (host != null)
            {
                _ui = host.UI;
            }
        }
    }
コード例 #31
0
ファイル: PSHost.cs プロジェクト: nagyist/PlatformInstaller
 public PSHost(PSHostUserInterface hostUserInterface)
 {
     this.hostUserInterface = hostUserInterface;
 }