From b8dced8e80f255e0a609364e6ae8703f3e9d0248 Mon Sep 17 00:00:00 2001 From: PowerShell Team Date: Thu, 28 Apr 2016 13:41:25 -0700 Subject: [PATCH] Update files from Source Depot changeset [SD:706766] Corresponds to e2ce37c87c0ab9795bfac2389edc1aff934bdb9e in psl-monad. --- .../host/msh/CommandLineParameterParser.cs | 25 +- .../host/msh/ConsoleControl.cs | 60 +-- .../host/msh/ConsoleHost.cs | 21 +- .../host/msh/ConsoleHostRawUserInterface.cs | 6 +- .../host/msh/ConsoleHostUserInterface.cs | 59 +-- .../security/SignatureCommands.cs | 197 +++++++--- .../Microsoft.PowerShell.Management.psd1 | 6 +- src/Modules/PSGet/PSModule.psm1 | 51 +++ .../engine/GetCommandCommand.cs | 2 +- .../engine/Modules/ModuleCmdletBase.cs | 38 +- .../remoting/commands/PSRemotingCmdlet.cs | 171 +++++++++ .../remoting/commands/PushRunspaceCommand.cs | 18 +- .../remoting/commands/newrunspacecommand.cs | 16 + .../common/RemoteSessionHyperVSocket.cs | 10 +- .../remoting/common/remotingexceptions.cs | 1 + .../help/HelpFileHelpProvider.cs | 97 ++++- .../resources/RemotingErrorIdStrings.resx | 3 + .../security/Authenticode.cs | 19 +- .../security/wldpNativeMethods.cs | 6 +- .../utils/PInvokeDllNames.cs | 2 +- .../nativemsh/pwrshexe/MainEntry.cpp | 351 +----------------- 21 files changed, 621 insertions(+), 538 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index 2f9a374e60..01290ae7c5 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -100,14 +100,6 @@ namespace Microsoft.PowerShell } } - internal bool ShowInitialPrompt - { - get - { - return showInitialPrompt; - } - } - internal uint ExitCode { get @@ -240,15 +232,11 @@ namespace Microsoft.PowerShell private void DisplayBanner() { - // We need to show the banner only if it has not been already shown in native layer - if (!showInitialPrompt) + // If banner text is not supplied do nothing. + if (!String.IsNullOrEmpty(bannerText)) { - // If banner text is not supplied do nothing. - if (!String.IsNullOrEmpty(bannerText)) - { - ui.WriteLine(bannerText); - ui.WriteLine(); - } + ui.WriteLine(bannerText); + ui.WriteLine(); } } @@ -385,10 +373,6 @@ namespace Microsoft.PowerShell { importSystemModules = true; } - else if (MatchSwitch(switchKey, "showinitialprompt", "show")) - { - showInitialPrompt = true; - } else if (MatchSwitch(switchKey, "noprofile", "nop")) { skipUserInit = true; @@ -960,7 +944,6 @@ namespace Microsoft.PowerShell private ConsoleHostUserInterface ui; private bool showHelp; private bool showBanner = true; - private bool showInitialPrompt; private bool noInteractive; private string bannerText; private string helpText; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index cc385c1ee7..1943a91b20 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -513,7 +513,6 @@ namespace Microsoft.PowerShell /// If Win32's SetConsoleCtrlHandler fails /// - [ArchitectureSensitive] internal static void AddBreakHandler(BreakHandler handlerDelegate) { bool result = NativeMethods.SetConsoleCtrlHandler(handlerDelegate, true); @@ -553,7 +552,7 @@ namespace Microsoft.PowerShell #region Win32Handles - static readonly Lazy _inputHandle = new Lazy(() => + static readonly Lazy _keyboardInputHandle = new Lazy(() => { var handle = NativeMethods.CreateFile( "CONIN$", @@ -580,19 +579,11 @@ namespace Microsoft.PowerShell ); /// - /// - /// Returns a ConsoleHandle to the console input device, even if stdin has been redirected. - /// + /// Returns a ConsoleHandle to the console (keyboard device) /// - /// - /// - /// If Win32's CreateFile fails - /// - - [ArchitectureSensitive] - internal static ConsoleHandle GetInputHandle() + internal static ConsoleHandle GetConioDeviceHandle() { - return _inputHandle.Value; + return _keyboardInputHandle.Value; } static readonly Lazy _outputHandle = new Lazy(() => @@ -627,7 +618,6 @@ namespace Microsoft.PowerShell /// /// If Win32's CreateFile fails /// - [ArchitectureSensitive] internal static ConsoleHandle GetActiveScreenBufferHandle() { return _outputHandle.Value; @@ -645,7 +635,6 @@ namespace Microsoft.PowerShell Error = 0xFFFFFFF4 } - [ArchitectureSensitive] internal static NakedWin32Handle GetStdHandle(StandardHandleId handleId) { unchecked @@ -657,8 +646,6 @@ namespace Microsoft.PowerShell } } - - #endregion #region Mode @@ -697,7 +684,6 @@ namespace Microsoft.PowerShell /// If Win32's GetConsoleMode fails /// - [ArchitectureSensitive] internal static ConsoleModes GetMode(ConsoleHandle consoleHandle) { Dbg.Assert(!consoleHandle.IsInvalid, "consoleHandle is not valid"); @@ -739,7 +725,6 @@ namespace Microsoft.PowerShell /// /// - [ArchitectureSensitive] internal static void SetMode(ConsoleHandle consoleHandle, ConsoleModes mode) { Dbg.Assert(!consoleHandle.IsInvalid, "consoleHandle is not valid"); @@ -800,7 +785,6 @@ namespace Microsoft.PowerShell /// /// - [ArchitectureSensitive] internal static string ReadConsole(ConsoleHandle consoleHandle, string initialContent, int charactersToRead, bool endOnTab, out uint keyState) { @@ -867,7 +851,6 @@ namespace Microsoft.PowerShell /// If Win32's ReadConsoleInput fails /// - [ArchitectureSensitive] internal static int ReadConsoleInput(ConsoleHandle consoleHandle, ref INPUT_RECORD[] buffer) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -913,7 +896,6 @@ namespace Microsoft.PowerShell /// If Win32's PeekConsoleInput fails /// - [ArchitectureSensitive] internal static int PeekConsoleInput ( ConsoleHandle consoleHandle, @@ -960,7 +942,6 @@ namespace Microsoft.PowerShell /// If Win32's GetNumberOfConsoleInputEvents fails /// - [ArchitectureSensitive] internal static int GetNumberOfConsoleInputEvents(ConsoleHandle consoleHandle) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -992,7 +973,6 @@ namespace Microsoft.PowerShell /// /// If Win32's FlushConsoleInputBuffer fails /// - [ArchitectureSensitive] internal static void FlushConsoleInputBuffer(ConsoleHandle consoleHandle) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -1033,7 +1013,6 @@ namespace Microsoft.PowerShell /// /// If Win32's GetConsoleScreenBufferInfo fails /// - [ArchitectureSensitive] internal static CONSOLE_SCREEN_BUFFER_INFO GetConsoleScreenBufferInfo(ConsoleHandle consoleHandle) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -1063,7 +1042,6 @@ namespace Microsoft.PowerShell /// If Win32's SetConsoleScreenBufferSize fails /// - [ArchitectureSensitive] internal static void SetConsoleScreenBufferSize(ConsoleHandle consoleHandle, Size newSize) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -1086,7 +1064,6 @@ namespace Microsoft.PowerShell } } - [ArchitectureSensitive] internal static bool IsConsoleColor(ConsoleColor c) { switch (c) @@ -1112,7 +1089,6 @@ namespace Microsoft.PowerShell return false; } - [ArchitectureSensitive] internal static void WORDToColor(WORD attribute, out ConsoleColor foreground, out ConsoleColor background) { // foreground color is the low-byte in the word, background color is the hi-byte. @@ -1122,7 +1098,6 @@ namespace Microsoft.PowerShell Dbg.Assert(IsConsoleColor(background), "unknown color"); } - [ArchitectureSensitive] internal static WORD ColorToWORD(ConsoleColor foreground, ConsoleColor background) { WORD result = (WORD)(((int)background << 4) | (int)foreground); @@ -1161,7 +1136,6 @@ namespace Microsoft.PowerShell /// If it is illegal to write to the output buffer /// - [ArchitectureSensitive] internal static void WriteConsoleOutput(ConsoleHandle consoleHandle, Coordinates origin, BufferCell[,] contents) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -1235,7 +1209,6 @@ namespace Microsoft.PowerShell } - [ArchitectureSensitive] private static void BuildEdgeTypeInfo( Rectangle contentsRegion, BufferCell[,] contents, @@ -1281,7 +1254,6 @@ namespace Microsoft.PowerShell } } - [ArchitectureSensitive] private static BufferCellArrayRowType GetEdgeType(BufferCell left, BufferCell right) { BufferCellArrayRowType edgeType = 0; @@ -1327,7 +1299,6 @@ namespace Microsoft.PowerShell /// /// If there is not enough memory to complete calls to Win32's ReadConsoleOutput /// - [ArchitectureSensitive] [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called in CHK builds")] internal static void CheckWriteEdges( ConsoleHandle consoleHandle, @@ -1393,7 +1364,6 @@ namespace Microsoft.PowerShell } - [ArchitectureSensitive] [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called in CHK builds")] private static void CheckWriteConsoleOutputContents(BufferCell[,] contents, Rectangle contentsRegion) { @@ -1429,7 +1399,6 @@ namespace Microsoft.PowerShell } } - [ArchitectureSensitive] private static void WriteConsoleOutputCJK(ConsoleHandle consoleHandle, Coordinates origin, Rectangle contentsRegion, BufferCell[,] contents, BufferCellArrayRowType rowType) { Dbg.Assert(origin.X >= 0 && origin.Y >= 0, @@ -1635,7 +1604,6 @@ namespace Microsoft.PowerShell } // row iteration } - [ArchitectureSensitive] private static void WriteConsoleOutputPlain(ConsoleHandle consoleHandle, Coordinates origin, BufferCell[,] contents) { int rows = contents.GetLength(0); @@ -1792,7 +1760,6 @@ namespace Microsoft.PowerShell /// If there is not enough memory to complete calls to Win32's ReadConsoleOutput /// - [ArchitectureSensitive] internal static void ReadConsoleOutput ( ConsoleHandle consoleHandle, @@ -1877,7 +1844,6 @@ namespace Microsoft.PowerShell return false; } - [ArchitectureSensitive] private static bool ReadConsoleOutputCJKSmall ( ConsoleHandle consoleHandle, @@ -1979,7 +1945,6 @@ namespace Microsoft.PowerShell /// /// If there is not enough memory to complete calls to Win32's ReadConsoleOutput /// - [ArchitectureSensitive] internal static void ReadConsoleOutputCJK ( ConsoleHandle consoleHandle, @@ -2153,7 +2118,6 @@ namespace Microsoft.PowerShell #endregion ReadConsoleOutput CJK - [ArchitectureSensitive] private static void ReadConsoleOutputPlain ( ConsoleHandle consoleHandle, @@ -2360,7 +2324,6 @@ namespace Microsoft.PowerShell /// /// If Win32's FillConsoleOutputCharacter fails /// - [ArchitectureSensitive] internal static void FillConsoleOutputCharacter ( ConsoleHandle consoleHandle, @@ -2423,7 +2386,6 @@ namespace Microsoft.PowerShell /// /// If Win32's FillConsoleOutputAttribute fails /// - [ArchitectureSensitive] internal static void FillConsoleOutputAttribute ( ConsoleHandle consoleHandle, @@ -2491,7 +2453,6 @@ namespace Microsoft.PowerShell /// If Win32's ScrollConsoleScreenBuffer fails /// - [ArchitectureSensitive] internal static void ScrollConsoleScreenBuffer ( ConsoleHandle consoleHandle, @@ -2549,7 +2510,6 @@ namespace Microsoft.PowerShell /// If Win32's SetConsoleWindowInfo fails /// - [ArchitectureSensitive] internal static void SetConsoleWindowInfo(ConsoleHandle consoleHandle, bool absolute, SMALL_RECT windowInfo) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -2584,7 +2544,6 @@ namespace Microsoft.PowerShell /// If Win32's GetLargestConsoleWindowSize fails /// - [ArchitectureSensitive] internal static Size GetLargestConsoleWindowSize(ConsoleHandle consoleHandle) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -2619,7 +2578,6 @@ namespace Microsoft.PowerShell /// If Win32's GetConsoleTitle fails /// - [ArchitectureSensitive] internal static string GetConsoleWindowTitle() { const int MaxWindowTitleLength = 1024; @@ -2654,7 +2612,6 @@ namespace Microsoft.PowerShell /// If Win32's SetConsoleTitle fails /// - [ArchitectureSensitive] internal static void SetConsoleWindowTitle(string consoleTitle) { bool result = NativeMethods.SetConsoleTitle(consoleTitle); @@ -2795,7 +2752,6 @@ namespace Microsoft.PowerShell /// /// - [ArchitectureSensitive] internal static void WriteConsole(ConsoleHandle consoleHandle, string output) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -2864,7 +2820,6 @@ namespace Microsoft.PowerShell /// /// - [ArchitectureSensitive] internal static void SetConsoleTextAttribute(ConsoleHandle consoleHandle, WORD attribute) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -3080,7 +3035,6 @@ namespace Microsoft.PowerShell /// /// /// - [ArchitectureSensitive] [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.PowerShell.ConsoleControl+NativeMethods.ReleaseDC(System.IntPtr,System.IntPtr)")] private static int LengthInBufferCells(char c, uint codePage) @@ -3148,7 +3102,6 @@ namespace Microsoft.PowerShell /// From IsConsoleFullWidth in \windows\core\ntcon\server\dbcs.c /// /// - [ArchitectureSensitive] [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.PowerShell.ConsoleControl+NativeMethods.ReleaseDC(System.IntPtr,System.IntPtr)")] internal static int LengthInBufferCells(string str, int offset, bool checkEscapeSequences) @@ -3209,7 +3162,6 @@ namespace Microsoft.PowerShell /// /// /// - [ArchitectureSensitive] internal static bool IsCJKOutputCodePage(out uint codePage) { codePage = NativeMethods.GetConsoleOutputCP(); @@ -3241,7 +3193,6 @@ namespace Microsoft.PowerShell /// If Win32's SetConsoleCursorPosition fails /// - [ArchitectureSensitive] internal static void SetConsoleCursorPosition(ConsoleHandle consoleHandle, Coordinates cursorPosition) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -3283,7 +3234,6 @@ namespace Microsoft.PowerShell /// If Win32's GetConsoleCursorInfo fails /// - [ArchitectureSensitive] internal static CONSOLE_CURSOR_INFO GetConsoleCursorInfo(ConsoleHandle consoleHandle) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -3304,7 +3254,6 @@ namespace Microsoft.PowerShell return cursorInfo; } - [ArchitectureSensitive] internal static CONSOLE_FONT_INFO_EX GetConsoleFontInfo(ConsoleHandle consoleHandle) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -3342,7 +3291,6 @@ namespace Microsoft.PowerShell /// If Win32's SetConsoleCursorInfo fails /// - [ArchitectureSensitive] internal static void SetConsoleCursorInfo(ConsoleHandle consoleHandle, CONSOLE_CURSOR_INFO cursorInfo) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 3b7f69e662..2ca039ee30 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -168,6 +168,16 @@ namespace Microsoft.PowerShell string preStartWarning, string[] args) { +#if DEBUG + if (Environment.GetEnvironmentVariable("POWERSHELL_DEBUG_STARTUP") != null) + { + while (!System.Diagnostics.Debugger.IsAttached) + { + Thread.Sleep(1000); + } + } +#endif + try { string profileDir; @@ -437,7 +447,7 @@ namespace Microsoft.PowerShell // already if this thread is lagging behind the main thread. #if !PORTABLE - ConsoleHandle handle = ConsoleControl.GetInputHandle(); + ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle(); ConsoleControl.FlushConsoleInputBuffer(handle); #endif @@ -1348,7 +1358,7 @@ namespace Microsoft.PowerShell // NTRAID#Windows Out Of Band Releases-915506-2005/09/09 // Removed HandleUnexpectedExceptions infrastructure - exitCode = DoRunspaceLoop(cpp.InitialCommand, cpp.SkipProfiles, cpp.Args, cpp.StaMode, cpp.ImportSystemModules, cpp.ShowInitialPrompt, cpp.ConfigurationName); + exitCode = DoRunspaceLoop(cpp.InitialCommand, cpp.SkipProfiles, cpp.Args, cpp.StaMode, cpp.ImportSystemModules, cpp.ConfigurationName); } while (false); @@ -1383,14 +1393,12 @@ namespace Microsoft.PowerShell /// /// private uint DoRunspaceLoop(string initialCommand, bool skipProfiles, Collection initialCommandArgs, bool staMode, - bool importSystemModules, bool showInitialPrompt, string configurationName) + bool importSystemModules, string configurationName) { ExitCode = ExitCodeSuccess; while (!ShouldEndSession) { - this.promptDisplayedInNativeCode = showInitialPrompt; - RunspaceCreationEventArgs args = new RunspaceCreationEventArgs(initialCommand, skipProfiles, staMode, importSystemModules, configurationName, initialCommandArgs); CreateRunspace(args); @@ -2154,8 +2162,6 @@ namespace Microsoft.PowerShell } } - internal bool promptDisplayedInNativeCode = false; - /// /// True when debugger command is user and available /// for stopping. @@ -2372,6 +2378,7 @@ namespace Microsoft.PowerShell string prompt = null; string line = null; + if (!ui.NoPrompt) { if (inBlockMode) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs index 79b390d045..04cc4436f9 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs @@ -720,7 +720,7 @@ namespace Microsoft.PowerShell } else { - ConsoleHandle handle = ConsoleControl.GetInputHandle(); + ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle(); ConsoleControl.INPUT_RECORD[] inputRecords = new ConsoleControl.INPUT_RECORD[1]; ConsoleControl.ConsoleModes originalMode = ConsoleControl.GetMode(handle); @@ -826,7 +826,7 @@ namespace Microsoft.PowerShell void FlushInputBuffer() { - ConsoleHandle handle = ConsoleControl.GetInputHandle(); + ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle(); ConsoleControl.FlushConsoleInputBuffer(handle); cachedKeyEvent.RepeatCount = 0; @@ -861,7 +861,7 @@ namespace Microsoft.PowerShell return true; } - ConsoleHandle handle = ConsoleControl.GetInputHandle(); + ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle(); ConsoleControl.INPUT_RECORD[] inputRecords = new ConsoleControl.INPUT_RECORD[ConsoleControl.GetNumberOfConsoleInputEvents(handle)]; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index 9e11aebf2a..1898ebf343 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -60,24 +60,31 @@ namespace Microsoft.PowerShell this.parent = parent; this.rawui = new ConsoleHostRawUserInterface(this); - isInteractiveTestToolListening = false; #if PORTABLE this._supportsVirtualTerminal = true; #else - // Turn on virtual terminal if possible. - var handle = ConsoleControl.GetActiveScreenBufferHandle(); - var m = ConsoleControl.GetMode(handle); + try + { + // Turn on virtual terminal if possible. - // We don't call ConsoleControl.SetMode because we want to ignore the return value as it doesn't tell us reliably if conhost - // supports a virtual terminal. - ConsoleControl.NativeMethods.SetConsoleMode(handle.DangerousGetHandle(), (uint)(m | ConsoleControl.ConsoleModes.VirtualTerminal)); - - // We only know if vt100 is supported if the previous call actually set the new flag, older - // systems ignore the setting. - m = ConsoleControl.GetMode(handle); - this._supportsVirtualTerminal = (m & ConsoleControl.ConsoleModes.VirtualTerminal) != 0; + // This might throw - not sure how exactly (no console), but if it does, we shouldn't fail to start. + var handle = ConsoleControl.GetActiveScreenBufferHandle(); + var m = ConsoleControl.GetMode(handle); + if (ConsoleControl.NativeMethods.SetConsoleMode(handle.DangerousGetHandle(), (uint) (m | ConsoleControl.ConsoleModes.VirtualTerminal))) + { + // We only know if vt100 is supported if the previous call actually set the new flag, older + // systems ignore the setting. + m = ConsoleControl.GetMode(handle); + this._supportsVirtualTerminal = (m & ConsoleControl.ConsoleModes.VirtualTerminal) != 0; + } + } + catch + { + } #endif + + isInteractiveTestToolListening = false; } /// @@ -289,7 +296,7 @@ namespace Microsoft.PowerShell null; SecureString secureResult = new SecureString(); StringBuilder result = new StringBuilder(); - ConsoleHandle handle = ConsoleControl.GetInputHandle(); + ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle(); ConsoleControl.ConsoleModes originalMode = ConsoleControl.GetMode(handle); bool isModeChanged = true; // assume ConsoleMode is changed so that if ReadLineSetMode // fails to return the value correctly, the original mode is @@ -1364,8 +1371,7 @@ namespace Microsoft.PowerShell return; } - TextWriter writer = - (!Console.IsErrorRedirected || parent.IsInteractive) + TextWriter writer = (!Console.IsErrorRedirected || parent.IsInteractive) ? parent.ConsoleTextWriter : Console.Error; @@ -1380,7 +1386,6 @@ namespace Microsoft.PowerShell if (writer == parent.ConsoleTextWriter) WriteLine(errorForegroundColor, errorBackgroundColor, value); else - Console.Error.Write(value + Crlf); } } @@ -1611,7 +1616,15 @@ namespace Microsoft.PowerShell break; } - sb.Append(c); + if (c == '\b') + { + sb.Remove(sb.Length - 1, 1); + } + else + { + sb.Append(c); + } + if (c == '\n') { @@ -1627,8 +1640,7 @@ namespace Microsoft.PowerShell #if PORTABLE return ReadLineFromFile(initialContent); #else - - ConsoleHandle handle = ConsoleControl.GetInputHandle(); + ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle(); PreRead(); // Ensure that we're in the proper line-input mode. @@ -1813,6 +1825,8 @@ namespace Microsoft.PowerShell /// /// The Executor instance on which to run any pipelines that are needed to find matches /// + /// + /// /// /// /// null on a break event @@ -1843,7 +1857,7 @@ namespace Microsoft.PowerShell do { - if (!ReadFromStdin && TryInvokeUserDefinedReadLine(out input)) + if (TryInvokeUserDefinedReadLine(out input)) { break; } @@ -2065,9 +2079,8 @@ namespace Microsoft.PowerShell var runspace = this.parent.LocalRunspace; if (runspace != null && - runspace.Engine.Context.EngineIntrinsics.InvokeCommand. - GetCommands(CustomReadlineCommand, - CommandTypes.Function | CommandTypes.Cmdlet, nameIsPattern: false).Any()) + runspace.Engine.Context.EngineIntrinsics.InvokeCommand.GetCommands(CustomReadlineCommand, + CommandTypes.Function | CommandTypes.Cmdlet, nameIsPattern: false).Any()) { try { diff --git a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs index 3dc6648495..750457fdf5 100644 --- a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs @@ -78,6 +78,41 @@ namespace Microsoft.PowerShell.Commands } private Signature signature; + /// + /// Gets or sets the file type of the byte array containing the content with + /// digital signature. + /// + [Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByContent")] + public string[] SourcePathOrExtension + { + get + { + return _sourcePathOrExtension; + } + + set + { + _sourcePathOrExtension = value; + } + } + private string[] _sourcePathOrExtension; + + /// + /// File contents as a byte array + /// + [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByContent")] + [ValidateNotNullOrEmpty] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + public byte[] Content + { + get { return _content; } + set + { + _content = value; + } + } + private byte[] _content; + // // name of this command // @@ -109,75 +144,88 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - // - // this cannot happen as we have specified the Path - // property to be mandatory parameter - // - Dbg.Assert((FilePath != null) && (FilePath.Length > 0), - "GetSignatureCommand: Param binder did not bind path"); - - foreach (string p in FilePath) + if (Content == null) { - Collection paths = new Collection(); + // + // this cannot happen as we have specified the Path + // property to be mandatory parameter + // + Dbg.Assert((FilePath != null) && (FilePath.Length > 0), + "GetSignatureCommand: Param binder did not bind path"); - // Expand wildcard characters - if (isLiteralPath) + foreach (string p in FilePath) { - paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p)); - } - else - { - try + Collection paths = new Collection(); + + // Expand wildcard characters + if (isLiteralPath) { - foreach (PathInfo tempPath in SessionState.Path.GetResolvedPSPathFromPSPath(p)) - { - paths.Add(tempPath.ProviderPath); - } + paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p)); } - catch (ItemNotFoundException) + else { - WriteError( - SecurityUtils.CreateFileNotFoundErrorRecord( - SignatureCommands.FileNotFound, - "SignatureCommandsBaseFileNotFound", p)); - } - } - - if (paths.Count == 0) - continue; - - bool foundFile = false; - - foreach (string path in paths) - { - if (! System.IO.Directory.Exists(path)) - { - foundFile = true; - - string resolvedFilePath = SecurityUtils.GetFilePathOfExistingFile(this, path); - - if (resolvedFilePath == null) + try { - WriteError(SecurityUtils.CreateFileNotFoundErrorRecord( - SignatureCommands.FileNotFound, - "SignatureCommandsBaseFileNotFound", - path)); - } - else - { - if ((Signature = PerformAction(resolvedFilePath)) != null) + foreach (PathInfo tempPath in SessionState.Path.GetResolvedPSPathFromPSPath(p)) { - WriteObject(Signature); + paths.Add(tempPath.ProviderPath); } } + catch (ItemNotFoundException) + { + WriteError( + SecurityUtils.CreateFileNotFoundErrorRecord( + SignatureCommands.FileNotFound, + "SignatureCommandsBaseFileNotFound", p)); + } } - } - if (!foundFile) + if (paths.Count == 0) + continue; + + bool foundFile = false; + + foreach (string path in paths) + { + if (!System.IO.Directory.Exists(path)) + { + foundFile = true; + + string resolvedFilePath = SecurityUtils.GetFilePathOfExistingFile(this, path); + + if (resolvedFilePath == null) + { + WriteError(SecurityUtils.CreateFileNotFoundErrorRecord( + SignatureCommands.FileNotFound, + "SignatureCommandsBaseFileNotFound", + path)); + } + else + { + if ((Signature = PerformAction(resolvedFilePath)) != null) + { + WriteObject(Signature); + } + } + } + } + + if (!foundFile) + { + WriteError(SecurityUtils.CreateFileNotFoundErrorRecord( + SignatureCommands.CannotRetrieveFromContainer, + "SignatureCommandsBaseCannotRetrieveFromContainer")); + } + } + } + else + { + foreach (string sourcePathOrExtension in SourcePathOrExtension) { - WriteError(SecurityUtils.CreateFileNotFoundErrorRecord( - SignatureCommands.CannotRetrieveFromContainer, - "SignatureCommandsBaseCannotRetrieveFromContainer")); + if ((Signature = PerformAction(sourcePathOrExtension, Content)) != null) + { + WriteObject(Signature); + } } } } @@ -190,6 +238,18 @@ namespace Microsoft.PowerShell.Commands /// The name of the file on which to perform the action. /// protected abstract Signature PerformAction(string filePath); + + /// + /// Performs the action (ie: get signature, or set signature) + /// on the specified contents. + /// + /// + /// The filename used for type if content is specified. + /// + /// + /// The file contents on which to perform the action. + /// + protected abstract Signature PerformAction(string fileName, byte[] content); } /// @@ -218,6 +278,21 @@ namespace Microsoft.PowerShell.Commands { return SignatureHelper.GetSignature(filePath, null); } + + /// + /// Gets the signature from the specified file contents. + /// + /// The file type associated with the contents + /// + /// The contents of the file on which to perform the action. + /// + /// + /// The signature on the specified file contents. + /// + protected override Signature PerformAction(string sourcePathOrExtension, byte[] content) + { + return SignatureHelper.GetSignature(sourcePathOrExtension, System.Text.Encoding.Unicode.GetString(content)); + } } /// @@ -494,6 +569,14 @@ namespace Microsoft.PowerShell.Commands } } + /// + /// Not implemented + /// + protected override Signature PerformAction(string sourcePathOrExtension, byte[] content) + { + throw new NotImplementedException(); + } + private struct SigningOptionInfo { internal SigningOption option; @@ -510,7 +593,7 @@ namespace Microsoft.PowerShell.Commands /// association between SigningOption.* values and the /// corresponding string names. /// - static readonly SigningOptionInfo[] sigOptionInfo = + private static readonly SigningOptionInfo[] sigOptionInfo = { new SigningOptionInfo(SigningOption.AddOnlyCertificate, "signer"), new SigningOptionInfo(SigningOption.AddFullCertificateChainExceptRoot, "notroot"), diff --git a/src/Modules/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 b/src/Modules/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 index cfe1a89e6d..f9c517f440 100644 --- a/src/Modules/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 +++ b/src/Modules/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 @@ -8,7 +8,7 @@ PowerShellVersion="3.0" CLRVersion="4.0" NestedModules="Microsoft.PowerShell.Commands.Management.dll" HelpInfoURI = 'http://go.microsoft.com/fwlink/?linkid=390785' -AliasesToExport = @("gcb", "scb","gin") +AliasesToExport = @("gcb", "scb", "gin", "gtz", "stz") FunctionsToExport = @() CmdletsToExport=@("Add-Content", "Clear-Content", @@ -96,5 +96,7 @@ CmdletsToExport=@("Add-Content", "Clear-Recyclebin", "Get-Clipboard", "Set-Clipboard", - "Get-ComputerInfo") + "Get-ComputerInfo", + "Get-TimeZone", + "Set-TimeZone") } diff --git a/src/Modules/PSGet/PSModule.psm1 b/src/Modules/PSGet/PSModule.psm1 index 060456bb9e..86f863c30b 100644 --- a/src/Modules/PSGet/PSModule.psm1 +++ b/src/Modules/PSGet/PSModule.psm1 @@ -9845,6 +9845,7 @@ function Install-PackageUtility Write-Debug ($LocalizedData.FastPackageReference -f $fastPackageReference) $Force = $false + $Debug = $false $MinimumVersion = $null $RequiredVersion = $null $IsSavePackage = $false @@ -9950,6 +9951,23 @@ function Install-PackageUtility } } + if($options.ContainsKey('Debug')) + { + $Debug = $options['Debug'] + + if($Debug.GetType().ToString() -eq 'System.String') + { + if($Debug -eq 'false') + { + $Debug = $false + } + elseif($Debug -eq 'true') + { + $Debug = $true + } + } + } + if($options.ContainsKey('NoPathUpdate')) { $NoPathUpdate = $options['NoPathUpdate'] @@ -10155,12 +10173,45 @@ function Install-PackageUtility } Write-Verbose ($LocalizedData.SpecifiedLocationAndOGP -f ($provider.ProviderName, $providerName)) + + $InstalledItemsList = $null + $pkg = $script:FastPackRefHastable[$fastPackageReference] + + # If an item has dependencies, prepare the list of installed items and + # pass it to the NuGet provider to not download the already installed items. + if($pkg.Dependencies.count -and + -not $IsSavePackage -and + -not $Force) + { + $InstalledItemsList = Microsoft.PowerShell.Core\Get-Module -ListAvailable | + Microsoft.PowerShell.Core\ForEach-Object {"$($_.Name)!#!$($_.Version)".ToLower()} + + if($artfactType -eq $script:PSArtifactTypeScript) + { + $InstalledItemsList += $script:PSGetInstalledScripts.GetEnumerator() | + Microsoft.PowerShell.Core\ForEach-Object { + "$($_.Value.PSGetItemInfo.Name)!#!$($_.Value.PSGetItemInfo.Version)".ToLower() + } + } + + $InstalledItemsList | Select-Object -Unique + + if($Debug) + { + $InstalledItemsList | Microsoft.PowerShell.Core\ForEach-Object { Write-Debug -Message "Locally available Item: $_"} + } + } $ProviderOptions = @{ Destination=$tempDestination; ExcludeVersion=$true } + if($InstalledItemsList) + { + $ProviderOptions['InstalledPackages'] = $InstalledItemsList + } + $newRequest = $request.CloneRequest( $ProviderOptions, @($SourceLocation), $request.Credential ) if($artfactType -eq $script:PSArtifactTypeModule) diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 885df395ac..a0cd85d6f0 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -568,7 +568,7 @@ namespace Microsoft.PowerShell.Commands // what sort of commands people expect but either don't exist, or maybe should be installed by default. // The StartsWith is to avoid logging telemetry when suggestion mode checks the // current directory for scripts/exes in the current directory and '.' is not in the path. - if (count == 0 && Name != null && Name.Length > 0 && !Name[0].StartsWith(".\\")) + if (count == 0 && Name != null && Name.Length > 0 && !Name[0].StartsWith(".\\", StringComparison.OrdinalIgnoreCase)) { Telemetry.Internal.TelemetryAPI.ReportGetCommandFailed(Name, _timer.ElapsedMilliseconds); } diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index fb6c1c372b..2a19bec90f 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -2145,6 +2145,7 @@ namespace Microsoft.PowerShell.Commands { foreach (ModuleSpecification s in tmpNestedModules) { + s.Name = GetAbsolutePath(moduleBase, s.Name); if (WildcardPattern.ContainsWildcardCharacters(s.Name)) { PSInvalidOperationException invalidOperation = PSTraceSource.NewInvalidOperationException( @@ -2617,13 +2618,15 @@ namespace Microsoft.PowerShell.Commands { foreach (var f in fileList) { - manifestInfo.AddToFileList(f); + string absuluteFilePath = GetAbsolutePath(moduleBase, f); + manifestInfo.AddToFileList(absuluteFilePath); } } if (moduleList != null) { foreach (var m in moduleList) { + m.Name = GetAbsolutePath(moduleBase, m.Name); manifestInfo.AddToModuleList(m); } } @@ -4925,8 +4928,18 @@ namespace Microsoft.PowerShell.Commands internal string FixupFileName(string moduleBase, string name, string extension) { // First check for full-qualified paths - either absolute or relative - string resolvedName = ResolveRootedFilePath(name, this.Context); - if (String.IsNullOrEmpty(resolvedName)) + string resolvedName; + if (!IsRooted(name)) + { + // The manifest file should only be related to moduleBase path. + resolvedName = ResolveRootedFilePath(Path.Combine(moduleBase, name), this.Context); + } + else + { + resolvedName = ResolveRootedFilePath(name, this.Context); + } + + if (string.IsNullOrEmpty(resolvedName)) { resolvedName = Path.Combine(moduleBase, name); } @@ -4958,6 +4971,25 @@ namespace Microsoft.PowerShell.Commands return result; } + /// + /// A utility routine to fix up a file name, if it is relative path convert it to absolute path combining moduleBase, if it is not a relative path, leave as it is. + /// + /// The base path to use if the file is not rooted + /// The file name to resolve. + /// + /// + internal string GetAbsolutePath(string moduleBase, string path) + { + if (!IsRooted(path) && (path.Contains('/') || path.Contains('\\')) && !path.Contains('$')) + { + return Path.Combine(moduleBase, path); + } + else + { + return path; + } + } + static internal bool IsRooted(string filePath) { return (Path.IsPathRooted(filePath) || diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index b495931920..85d8de9253 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -285,6 +285,148 @@ namespace Microsoft.PowerShell.Commands /// public abstract partial class PSRemotingBaseCmdlet : PSRemotingCmdlet { + /// + /// State of virtual machine. This is the same as VMState in + /// \vm\ux\powershell\objects\common\Types.cs + /// + internal enum VMState + { + /// + /// Other. Corresponds to CIM_EnabledLogicalElement.EnabledState = Other. + /// + Other = 1, + + /// + /// Running. Corresponds to CIM_EnabledLogicalElement.EnabledState = Enabled. + /// + Running = 2, + + /// + /// Off. Corresponds to CIM_EnabledLogicalElement.EnabledState = Disabled. + /// + Off = 3, + + /// + /// Stopping. Corresponds to CIM_EnabledLogicalElement.EnabledState = ShuttingDown. + /// + Stopping = 4, + + /// + /// Saved. Corresponds to CIM_EnabledLogicalElement.EnabledState = Enabled but offline. + /// + Saved = 6, + + /// + /// Paused. Corresponds to CIM_EnabledLogicalElement.EnabledState = Quiesce. + /// + Paused = 9, + + /// + /// Starting. EnabledStateStarting. State transition from PowerOff or Saved to Running. + /// + Starting = 10, + + /// + /// Reset. Corresponds to CIM_EnabledLogicalElement.EnabledState = Reset. + /// + Reset = 11, + + /// + /// Saving. Corresponds to EnabledStateSaving. + /// + Saving = 32773, + + /// + /// Pausing. Corresponds to EnabledStatePausing. + /// + Pausing = 32776, + + /// + /// Resuming. Corresponds to EnabledStateResuming. + /// + Resuming = 32777, + + /// + /// FastSaved. EnabledStateFastSuspend. + /// + FastSaved = 32779, + + /// + /// FastSaving. EnabledStateFastSuspending. + /// + FastSaving = 32780, + + /// + /// ForceShutdown. Used to force a graceful shutdown of the virtual machine. + /// + ForceShutdown = 32781, + + /// + /// ForceReboot. Used to force a graceful reboot of the virtual machine. + /// + ForceReboot = 32782, + + /// + /// RunningCritical. Critical states. + /// + RunningCritical, + + /// + /// OffCritical. Critical states. + /// + OffCritical, + + /// + /// StoppingCritical. Critical states. + /// + StoppingCritical, + + /// + /// SavedCritical. Critical states. + /// + SavedCritical, + + /// + /// PausedCritical. Critical states. + /// + PausedCritical, + + /// + /// StartingCritical. Critical states. + /// + StartingCritical, + + /// + /// ResetCritical. Critical states. + /// + ResetCritical, + + /// + /// SavingCritical. Critical states. + /// + SavingCritical, + + /// + /// PausingCritical. Critical states. + /// + PausingCritical, + + /// + /// ResumingCritical. Critical states. + /// + ResumingCritical, + + /// + /// FastSavedCritical. Critical states. + /// + FastSavedCritical, + + /// + /// FastSavingCritical. Critical states. + /// + FastSavingCritical, + } + #region Tracer //PSETWTracer tracer = PSETWTracer.GetETWTracer(PSKeyword.Runspace); @@ -1331,6 +1473,7 @@ namespace Microsoft.PowerShell.Commands int inputArraySize; int index; string command; + bool[] vmIsRunning; Collection results; if ((ParameterSetName == PSExecutionCmdlet.VMIdParameterSet) || @@ -1338,9 +1481,12 @@ namespace Microsoft.PowerShell.Commands { inputArraySize = this.VMId.Length; this.VMName = new string[inputArraySize]; + vmIsRunning = new bool[inputArraySize]; for (index = 0; index < inputArraySize; index++) { + vmIsRunning[index] = false; + command = "Get-VM -Id $args[0]"; try @@ -1367,6 +1513,11 @@ namespace Microsoft.PowerShell.Commands else { this.VMName[index] = (string)results[0].Properties["VMName"].Value; + + if ((VMState)results[0].Properties["State"].Value == VMState.Running) + { + vmIsRunning[index] = true; + } } } } @@ -1378,9 +1529,12 @@ namespace Microsoft.PowerShell.Commands inputArraySize = this.VMName.Length; this.VMId = new Guid[inputArraySize]; + vmIsRunning = new bool[inputArraySize]; for (index = 0; index < inputArraySize; index++) { + vmIsRunning[index] = false; + command = "Get-VM -Name $args"; try @@ -1408,6 +1562,11 @@ namespace Microsoft.PowerShell.Commands { this.VMId[index] = (Guid)results[0].Properties["VMId"].Value; this.VMName[index] = (string)results[0].Properties["VMName"].Value; + + if ((VMState)results[0].Properties["State"].Value == VMState.Running) + { + vmIsRunning[index] = true; + } } } } @@ -1444,6 +1603,18 @@ namespace Microsoft.PowerShell.Commands continue; } + else if (!vmIsRunning[index]) + { + WriteError( + new ErrorRecord( + new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState, + this.VMName[index])), + PSRemotingErrorId.InvalidVMState.ToString(), + ErrorCategory.InvalidArgument, + null)); + + continue; + } // create helper objects for VM GUIDs or names RemoteRunspace remoteRunspace = null; diff --git a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs index 8354b6fdf8..b6364959d7 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs @@ -1014,7 +1014,7 @@ namespace Microsoft.PowerShell.Commands return null; } - + this.VMName = (string)results[0].Properties["VMName"].Value; } else @@ -1066,6 +1066,22 @@ namespace Microsoft.PowerShell.Commands this.VMId = (Guid)results[0].Properties["VMId"].Value; this.VMName = (string)results[0].Properties["VMName"].Value; } + + // + // VM should be in running state. + // + if ((VMState)results[0].Properties["State"].Value != VMState.Running) + { + WriteError( + new ErrorRecord( + new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState, + this.VMName)), + PSRemotingErrorId.InvalidVMState.ToString(), + ErrorCategory.InvalidArgument, + null)); + + return null; + } try { diff --git a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs index 87106f6ede..f3f1627ed5 100644 --- a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs @@ -958,6 +958,22 @@ namespace Microsoft.PowerShell.Commands { this.VMId[index] = (Guid)results[0].Properties["VMId"].Value; this.VMName[index] = (string)results[0].Properties["VMName"].Value; + + // + // VM should be in running state. + // + if ((VMState)results[0].Properties["State"].Value != VMState.Running) + { + WriteError( + new ErrorRecord( + new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState, + this.VMName[index])), + PSRemotingErrorId.InvalidVMState.ToString(), + ErrorCategory.InvalidArgument, + null)); + + continue; + } } // create helper objects for VM GUIDs or names diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs index 202bc4304e..2819e8c993 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs @@ -548,11 +548,15 @@ namespace System.Management.Automation.Remoting // // Check invalid input and throw exception before setting up socket connection. + // This check is done only in VM case. // - if (String.IsNullOrEmpty(networkCredential.UserName)) + if (isFirstConnection) { - throw new PSDirectException( - PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidUsername)); + if (String.IsNullOrEmpty(networkCredential.UserName)) + { + throw new PSDirectException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidUsername)); + } } _socket.Connect(_endPoint); diff --git a/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs b/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs index fbb37fb8eb..d083fa8d18 100644 --- a/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs +++ b/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs @@ -232,6 +232,7 @@ namespace System.Management.Automation.Remoting InvalidContainerNameNotExist = 972, ContainerSessionConnectFailed = 973, RemoteSessionHyperVSocketClientConstructorSetSocketOptionFailure = 974, + InvalidVMState = 975, // Invoke-Command related error codes. InvalidVMIdNotSingle = 981, diff --git a/src/System.Management.Automation/help/HelpFileHelpProvider.cs b/src/System.Management.Automation/help/HelpFileHelpProvider.cs index 191b0ab81c..e3d39d661a 100644 --- a/src/System.Management.Automation/help/HelpFileHelpProvider.cs +++ b/src/System.Management.Automation/help/HelpFileHelpProvider.cs @@ -64,11 +64,15 @@ namespace System.Management.Automation int countHelpInfosFound = 0; string helpFileName = helpRequest.Target + ".help.txt"; Collection filesMatched = MUIFileSearcher.SearchFiles(helpFileName, GetExtendedSearchPaths()); - + Diagnostics.Assert(filesMatched != null, "Files collection should not be null."); + var matchedFilesToRemove = FilterToLatestModuleVersion(filesMatched); foreach (string file in filesMatched) { + if (matchedFilesToRemove.Contains(file)) + continue; + // Check whether the file is already loaded if (!_helpFiles.ContainsKey(file)) { @@ -99,6 +103,70 @@ namespace System.Management.Automation } } + private Collection FilterToLatestModuleVersion(Collection filesMatched) + { + Collection matchedFilesToRemove = new Collection(); + + if (filesMatched.Count > 1) + { + //Dictionary<, > + Dictionary, Tuple> modulesAndVersion = new Dictionary, Tuple>(); + HashSet filesProcessed = new HashSet(); + + var allPSModulePaths = ModuleIntrinsics.GetModulePath(false, this.HelpSystem.ExecutionContext); + + foreach (string fileFullName in filesMatched) + { + // Use the filename as a check if we need to process further. + // Single module can have multiple .help.txt files. + var fileName = Path.GetFileName(fileFullName); + + foreach (string psModulePath in allPSModulePaths) + { + Version moduleVersionFromPath = null; + string moduleName = null; + GetModuleNameAndVersion(psModulePath, fileFullName, out moduleName, out moduleVersionFromPath); + + //Skip modules whose root we cannot determine or which do not have versions. + if (moduleVersionFromPath != null && moduleName != null) + { + Tuple moduleVersion = null; + Tuple key = new Tuple(moduleName, fileName); + if (modulesAndVersion.TryGetValue(key, out moduleVersion)) + { + //Consider for further processing only if the help file name is same. + if (filesProcessed.Contains(fileName)) + { + if (moduleVersionFromPath > moduleVersion.Item2) + { + modulesAndVersion[key] = new Tuple(fileFullName, moduleVersionFromPath); + + //Remove the old file since we found a newer version. + matchedFilesToRemove.Add(moduleVersion.Item1); + } + else + { + //Remove the new file as higher version item is already in dictionary. + matchedFilesToRemove.Add(fileFullName); + } + } + } + else + { + //Add the module to the dictionary as it was not processes earlier. + modulesAndVersion.Add(new Tuple(moduleName,fileName), + new Tuple(fileFullName, moduleVersionFromPath)); + } + } + } + + filesProcessed.Add(fileName); + } + } + + return matchedFilesToRemove; + } + internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool searchOnlyContent) { string target = helpRequest.Target; @@ -132,11 +200,16 @@ namespace System.Management.Automation Collection files = MUIFileSearcher.SearchFiles(pattern, GetExtendedSearchPaths()); + var matchedFilesToRemove = FilterToLatestModuleVersion(files); + if (files == null) yield break; foreach (string file in files) { + if (matchedFilesToRemove.Contains(file)) + continue; + // Check whether the file is already loaded if (!_helpFiles.ContainsKey(file)) { @@ -175,6 +248,26 @@ namespace System.Management.Automation } } + private void GetModuleNameAndVersion(string psmodulePathRoot, string filePath, out string moduleName, out Version moduleVersion) + { + Version returnVersion = null; + string returnModuleName = null; + + if (filePath.StartsWith(psmodulePathRoot)) + { + var moduleRootSubPath = filePath.Remove(0, psmodulePathRoot.Length).TrimStart(Utils.Separators.Directory); + var pathParts = moduleRootSubPath.Split(Utils.Separators.Directory, StringSplitOptions.RemoveEmptyEntries); + + //returnModuleRootPath = Path.Combine(psmodulePathRoot, pathParts[0]); + returnModuleName = pathParts[0]; + var potentialVersion = pathParts[1]; + Version.TryParse(potentialVersion, out returnVersion); + } + + moduleVersion = returnVersion; + moduleName = returnModuleName; + } + /// /// Load help file based on the file path. /// @@ -227,7 +320,7 @@ namespace System.Management.Automation internal Collection GetExtendedSearchPaths() { Collection searchPaths = GetSearchPaths(); - + // Add $pshome at the top of the list String defaultShellSearchPath = GetDefaultShellSearchPath(); int index = searchPaths.IndexOf(defaultShellSearchPath); diff --git a/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx b/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx index c097913b9e..ac45d36d28 100644 --- a/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx +++ b/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx @@ -1225,6 +1225,9 @@ All WinRM sessions connected to Windows PowerShell session configurations, such The input VMName {0} does not resolve to a single virtual machine. + + The virtual machine {0} is not in running state. + The credential is invalid. diff --git a/src/System.Management.Automation/security/Authenticode.cs b/src/System.Management.Automation/security/Authenticode.cs index d7387c456a..e93270e6cb 100644 --- a/src/System.Management.Automation/security/Authenticode.cs +++ b/src/System.Management.Automation/security/Authenticode.cs @@ -318,15 +318,18 @@ namespace System.Management.Automation { Signature signature = null; - // First, try to get the signature from the catalog signature APIs. - signature = GetSignatureFromCatalog(fileName); + if (fileContent == null) + { + // First, try to get the signature from the catalog signature APIs. + signature = GetSignatureFromCatalog(fileName); + } // If there is no signature or it is invalid, go by the file content // with the older WinVerifyTrust APIs if ((signature == null) || (signature.Status != SignatureStatus.Valid)) { signature = GetSignatureFromWinVerifyTrust(fileName, fileContent); - } + } return signature; } @@ -469,13 +472,17 @@ namespace System.Management.Automation NativeMethods.WINTRUST_DATA wtd; DWORD error = Win32Errors.E_FAIL; - Utils.CheckArgForNullOrEmpty(fileName, "fileName"); - SecuritySupport.CheckIfFileExists(fileName); - //SecurityUtils.CheckIfFileSmallerThan4Bytes(fileName); + if (fileContent == null) + { + Utils.CheckArgForNullOrEmpty(fileName, "fileName"); + SecuritySupport.CheckIfFileExists(fileName); + //SecurityUtils.CheckIfFileSmallerThan4Bytes(fileName); + } try { error = GetWinTrustData(fileName, fileContent, out wtd); + if (error != Win32Errors.NO_ERROR) { tracer.WriteLine("GetWinTrustData failed: {0:x}", error); diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index 801498709b..4d1a438124 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -108,11 +108,11 @@ namespace System.Management.Automation.Security MessageId = "System.Runtime.InteropServices.SafeHandle.DangerousGetHandle")] private static SystemEnforcementMode GetWldpPolicy(string path, SafeHandle handle) { - // If the WLDP assembly is missing, look up the debug lockdown policy + // If the WLDP assembly is missing (such as windows 7 or down OS), return default/None to skip WLDP valification if (hadMissingWldpAssembly || !IO.File.Exists(IO.Path.Combine(Environment.SystemDirectory, "wldp.dll"))) { hadMissingWldpAssembly = true; - return GetDebugLockdownPolicy(path); + return cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None); } // If path is NULL, see if we have the cached system-wide lockdown policy. @@ -165,7 +165,7 @@ namespace System.Management.Automation.Security catch (DllNotFoundException) { hadMissingWldpAssembly = true; - return GetDebugLockdownPolicy(path); + return cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None); } } private static SystemEnforcementMode? cachedWldpSystemPolicy = null; diff --git a/src/System.Management.Automation/utils/PInvokeDllNames.cs b/src/System.Management.Automation/utils/PInvokeDllNames.cs index 2ba503b6a4..5e431d5825 100644 --- a/src/System.Management.Automation/utils/PInvokeDllNames.cs +++ b/src/System.Management.Automation/utils/PInvokeDllNames.cs @@ -126,7 +126,7 @@ namespace System.Management.Automation internal const string WriteConsoleOutputDllName = "api-ms-win-core-console-l2-1-0.dll"; /*111*/ internal const string ReadConsoleOutputDllName = "api-ms-win-core-console-l2-1-0.dll"; /*112*/ internal const string ScrollConsoleScreenBufferDllName = "api-ms-win-core-console-l2-1-0.dll"; /*113*/ - internal const string SendInputDllName = "ext-ms-win-ntuser-keyboard-l1-2-1.dll"; /*114*/ + internal const string SendInputDllName = "ext-ms-win-ntuser-keyboard-l1-3-0.dll"; /*114*/ internal const string GetConsoleCursorInfoDllName = "api-ms-win-core-console-l2-1-0.dll"; /*115*/ internal const string SetConsoleCursorInfoDllName = "api-ms-win-core-console-l2-1-0.dll"; /*116*/ internal const string ReadConsoleInputDllName = "api-ms-win-core-console-l1-1-0.dll"; /*117*/ diff --git a/src/powershell-native/nativemsh/pwrshexe/MainEntry.cpp b/src/powershell-native/nativemsh/pwrshexe/MainEntry.cpp index 0383286c58..5c9b5ea81b 100644 --- a/src/powershell-native/nativemsh/pwrshexe/MainEntry.cpp +++ b/src/powershell-native/nativemsh/pwrshexe/MainEntry.cpp @@ -28,8 +28,6 @@ #include "OutputWriter.h" #include "WinSystemCallFacade.h" -#define PSREADLINE_SUPPORTED 1 - // include the tlb for mscorlib for access to the default AppDomain through COM Interop #import raw_interfaces_only high_property_prefixes("_get","_put","_putref")\ rename("ReportEvent", "CLRReportEvent") @@ -53,18 +51,12 @@ WCHAR g_IconApp[MAX_PATH+1]; PwrshExeOutput* pwrshExeOutput = new PwrshExeOutput(); PwrshCommon pwrshCommon(pwrshExeOutput, new ConfigFileReader(), new WinSystemCallFacade()); -/********************************************************************++ -Copyright (c) Microsoft Corporation. All rights reserved. ---********************************************************************/ bool ConvertArgvToSafeArray( IN int argc, __in_ecount(argc) LPWSTR * argv, IN int skipIndex, - __deref_out_opt SAFEARRAY ** ppSafeArray, - bool showInitialPrompt) + __deref_out_opt SAFEARRAY ** ppSafeArray) { - - LPWSTR showInitialPromptParameter = L"-showinitialprompt"; // Collect the command line arguments to the managed exe SAFEARRAY *psa = NULL; SAFEARRAYBOUND rgsabound[1]; @@ -80,12 +72,7 @@ bool ConvertArgvToSafeArray( rgsabound[0].lLbound = 0; // rgsabound[0].cElements holds the number of elements that need to be passed to managed exe - // +1 is for the value - showInitialPrompt rgsabound[0].cElements = argc - 1 - skipIndex; - if (showInitialPrompt) - { - rgsabound[0].cElements += 1; - } psa = SafeArrayCreate(VT_BSTR, 1, rgsabound); if (psa == NULL) @@ -97,25 +84,6 @@ bool ConvertArgvToSafeArray( long psaIndex[1]; psaIndex[0] = 0; - if (showInitialPrompt) - { - BSTR bArg = SysAllocString(showInitialPromptParameter); - if (NULL == bArg) - { - returnResult = false; - break; - } - HRESULT hr = SafeArrayPutElement(psa, psaIndex, bArg); - // Free bArg - SysFreeString(bArg); - psaIndex[0]++; - if (FAILED(hr)) - { - returnResult = false; - break; - } - } - if (0 != rgsabound[0].cElements) { // Skip elements from 1 to argc-rgsabound[0].cElements-1 @@ -145,247 +113,11 @@ bool ConvertArgvToSafeArray( return returnResult; } -/********************************************************************++ -Copyright (c) Microsoft Corporation. All rights reserved. ---********************************************************************/ bool FileExists(__in LPWSTR pszFileName) { return (GetFileAttributesW(pszFileName) != INVALID_FILE_ATTRIBUTES); } -/********************************************************************++ -Copyright (c) Microsoft Corporation. All rights reserved. ---********************************************************************/ -bool DoesProfileExist(bool hasShellID, bool forCurrentUser) -{ - wchar_t *basePath = NULL; - size_t basePathLength; - wchar_t *tempBasePath = NULL; - - wchar_t *resultProfileFile = NULL; - size_t resultProfileFileLength; - - size_t productNameLength = RTL_NUMBER_OF_V2(g_PRODUCT_NAME) - 1; - size_t profileStringLength = RTL_NUMBER_OF_V2(g_PROFILE) - 1; - size_t profileStringWithShellIdLength = RTL_NUMBER_OF_V2(g_PROFILE_WITH_SHELL_ID) - 1; - size_t versionStringLength = RTL_NUMBER_OF_V2(g_PSHOME_VERSION) - 1; - - if (forCurrentUser) - { - if(S_OK != SHGetKnownFolderPath(FOLDERID_Documents,0, NULL, &basePath)) - { - // In case of any error, assume the profile file exists. - // Running the profile (if it does actually exist will be taken care of by the managed layer) - return true; - } - else - { - if (S_OK != StringCchLength(basePath, STRSAFE_MAX_LENGTH, &basePathLength)) - { - if (NULL != basePath) - { - CoTaskMemFree(basePath); - } - - // In case of any error, assume the profile file exists. - //Running the profile (if it does actually exist will be taken care of by the managed layer) - return true; - } - - size_t originalBasePathLength = basePathLength; - basePathLength = basePathLength + productNameLength + 1; - tempBasePath = new wchar_t[basePathLength]; - tempBasePath[0]='\0'; - if (S_OK != StringCchCatN(tempBasePath, basePathLength, basePath, originalBasePathLength)) - { - // In case of any error, assume the profile file exists. - // Running the profile (if it does actually exist will be taken care of by the managed layer) - CoTaskMemFree(basePath); - delete[] tempBasePath; - return true; - } - // free up basePath as it is not used anymore - CoTaskMemFree(basePath); - - if (S_OK != StringCchCatN(tempBasePath, basePathLength, g_PRODUCT_NAME, productNameLength)) - { - delete[] tempBasePath; - return true; - } - basePath = tempBasePath; - } - } - else - { - if(S_OK != SHGetKnownFolderPath(FOLDERID_System,0, NULL, &basePath)) - { - // In case of any error, assume the profile file exists. - // Running the profile (if it does actually exist will be taken care of by the managed layer) - return true; - } - else - { - if (S_OK != StringCchLength(basePath, STRSAFE_MAX_LENGTH, &basePathLength)) - { - if (NULL != basePath) - { - CoTaskMemFree(basePath); - } - // In case of any error, assume the profile file exists. - // Running the profile (if it does actually exist will be taken care of by the managed layer) - return true; - } - - size_t originalBasePathLength = basePathLength; - basePathLength = basePathLength + productNameLength + versionStringLength + 1; - tempBasePath = new wchar_t[basePathLength]; - tempBasePath[0]='\0'; - if (S_OK != StringCchCatN(tempBasePath, basePathLength, basePath, originalBasePathLength)) - { - // In case of any error, assume the profile file exists. - // Running the profile (if it does actually exist will be taken care of by the managed layer) - CoTaskMemFree(basePath); - delete[] tempBasePath; - return true; - } - // free up basePath as it is not used anymore - CoTaskMemFree(basePath); - - if (S_OK != StringCchCatN(tempBasePath, basePathLength, g_PRODUCT_NAME, productNameLength)) - { - delete[] tempBasePath; - return true; - } - if (S_OK != StringCchCatN(tempBasePath, basePathLength, g_PSHOME_VERSION, versionStringLength)) - { - delete[] tempBasePath; - return true; - } - - basePath = tempBasePath; - } - } - - if (hasShellID) - { - resultProfileFileLength = basePathLength + profileStringWithShellIdLength + 1; - resultProfileFile = new wchar_t[resultProfileFileLength]; - resultProfileFile[0] = '\0'; - if (S_OK != StringCchCatN(resultProfileFile, resultProfileFileLength, basePath, basePathLength)) - { - // In case of any error, assume the profile file exists. - // Running the profile (if it does actually exist will be taken care of by the managed layer) - delete[] tempBasePath; - delete[] resultProfileFile; - return true; - } - - if (S_OK != StringCchCatN(resultProfileFile, resultProfileFileLength, g_PROFILE_WITH_SHELL_ID, profileStringWithShellIdLength)) - { - delete[] tempBasePath; - delete[] resultProfileFile; - return true; - } - } - else - { - resultProfileFileLength = basePathLength + profileStringLength + 1; - resultProfileFile = new wchar_t[resultProfileFileLength]; - resultProfileFile[0]='\0'; - if (S_OK != StringCchCatN(resultProfileFile, resultProfileFileLength, basePath, basePathLength)) - { - // In case of any error, assume the profile file exists. - // Running the profile (if it does actually exist will be taken care of by the managed layer) - delete[] tempBasePath; - delete[] resultProfileFile; - return true; - } - - if (S_OK != StringCchCatN(resultProfileFile, resultProfileFileLength, g_PROFILE, profileStringLength)) - { - delete[] tempBasePath; - delete[] resultProfileFile; - return true; - } - } - - delete[] tempBasePath; - - bool result = FileExists(resultProfileFile); - if (NULL != resultProfileFile) - { - delete[] resultProfileFile; - } - - return result; -} - - -#if !PSREADLINE_SUPPORTED -/********************************************************************++ -Copyright (c) Microsoft Corporation. All rights reserved. ---********************************************************************/ -bool DoWeHaveProfileFiles() -{ - // Returns true if either one of the four locations exist - // allUsersProfile "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\profile.ps1" - // allUsersHostSpecificProfile "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\Microsoft.PowerShell_profile.ps1" - // currentUserProfile "C:\\Users\\\\Documents\\WindowsPowerShell\\profile.ps1" - // currentUserHostSpecificProfile "C:\\Users\\\\Documents\\WindowsPowerShell\\Microsoft.PowerShell_profile.ps1" - - bool allUsersProfilePath = DoesProfileExist(false, false); - bool allUsersHostSpecificProfile = DoesProfileExist(true, false); - bool currentUserProfile = DoesProfileExist(false, true); - bool currentUserHostSpecificProfile = DoesProfileExist(true, true); - if (allUsersProfilePath || allUsersHostSpecificProfile || currentUserProfile || currentUserHostSpecificProfile) - { - return true; - } - return false; -} -#endif - -/********************************************************************++ -Copyright (c) Microsoft Corporation. All rights reserved. ---********************************************************************/ -bool DisplayBannerAndPrompt() -{ - bool isPromptDisplayed = false; - TCHAR Buffer[MAX_PATH]; - DWORD dwRet; - dwRet = GetCurrentDirectory(MAX_PATH, Buffer); - - if( dwRet == 0 ) - { - return false; - } - if(dwRet > MAX_PATH) - { - return false; - } - - size_t length; - if (S_OK != StringCchLength(Buffer, STRSAFE_MAX_LENGTH, &length)) - { - return false; - } - - // Display Banner - pwrshExeOutput->DisplayMessage(false, g_SHELLBANNER1); - pwrshExeOutput->DisplayMessage(false, g_SHELLBANNER2); - WriteStandard(false, L"\n", 1); - - // Display Prompt - WriteStandard(false, L"PS ", 3); - WriteStandard(false, Buffer, length); - WriteStandard(false, L"> ", 2); - - return true; -} - -/********************************************************************++ -Copyright (c) Microsoft Corporation. All rights reserved. ---********************************************************************/ unsigned int LaunchManagedMonad( LPCWSTR wszMonadVersion, int monadMajorVersion, @@ -393,7 +125,6 @@ unsigned int LaunchManagedMonad( LPCWSTR wszRuntimeVersion, LPCWSTR wszConsoleHostAssemblyName, __in_ecount_opt(1) SAFEARRAY * pArgvSA, - bool showInitialPrompt, int skipIndex, int argc, __in_ecount(argc) LPWSTR * argv) @@ -421,23 +152,11 @@ unsigned int LaunchManagedMonad( break; } - if (showInitialPrompt) - { - // Display both banner and prompt from native code or display both from managed layer. - // This helps keeping things simple when we want to decide whether to show the initial prompt from the managed layer. - if (!DisplayBannerAndPrompt()) - { - // If there was an error while displaying prompt, set this flag to false so that the initial prompt is displayed from the managed layer. - showInitialPrompt = false; - } - } - if(!ConvertArgvToSafeArray( argc, argv, skipIndex, - &pArgvSA, - showInitialPrompt)) + &pArgvSA)) { exitCode = EXIT_CODE_INIT_FAILURE; break; @@ -582,9 +301,6 @@ static bool IsDash(WCHAR wch) return (enDash == wch || emDash == wch || horizontalBar == wch || '-' == wch); } -/********************************************************************++ -Copyright (c) Microsoft Corporation. All rights reserved. ---********************************************************************/ static bool IsParameterMatched( LPCWSTR wszParameter, int cchParameter, @@ -649,9 +365,6 @@ static bool IsParameterMatched( return bReturnResult; } -/********************************************************************++ -Copyright (c) Microsoft Corporation. All rights reserved. ---********************************************************************/ static bool CheckConsoleFileExtension( LPCWSTR wszFileName) { @@ -872,9 +585,6 @@ void DisplaySpecificXMLDOMError( } } -/********************************************************************++ -Copyright (c) Microsoft Corporation. All rights reserved. ---********************************************************************/ static bool ReadVersionFromConsoleFile( LPCWSTR wszFileName, __deref_out_opt PWSTR * pwszMonadVersion, @@ -1022,9 +732,6 @@ static bool ReadVersionFromConsoleFile( #pragma prefast (disable: 6101) // Returning uninitialized memory - pwszRuntimeVersion, pwszConsoleFile, pwszMonadVersion, and pwszRuntimeVersion are not always set on success. -/********************************************************************++ -Copyright (c) Microsoft Corporation. All rights reserved. ---********************************************************************/ unsigned int ParseCommandLineArguments( IN int argc, __in_ecount(argc) LPWSTR * argv, @@ -1847,9 +1554,6 @@ void CreateCustomDestinationList(STARTUPINFO &startupInfo) #endif -/********************************************************************++ -Copyright (c) Microsoft Corporation. All rights reserved. ---********************************************************************/ int __cdecl wmain( int argc, @@ -1988,56 +1692,6 @@ int __cdecl skipIndex = skipIndex + 1; - bool showInitialPrompt = false; -#if !PSREADLINE_SUPPORTED - // If there are any more parameters to be passed to managed layer, do not do anything here. - // Handle everything in the managed layer - // Do not do any optimization for PowerShell 1.0 or PowerShell 2.0 - if (monadMajorVersion != 1 && monadMajorVersion != 2) - { - if (skipProfile) - { - // Are there any more parameters to managed layer? - // Yes --> Do not show prompt here. - // No --> Show prompt here - // We check for a difference of 2 here (1 for PowerShell.exe and 1 for NoProfile) - if (argc - skipIndex > 2) - { - showInitialPrompt = false; - } - else - { - showInitialPrompt = true; - } - } - else - { - // Are there any more parameters to managed layer? - // Yes --> Do not show prompt here. - // No --> Additional checks - // We check for a difference of 1 here (1 for PowerShell.exe) - if (argc - skipIndex > 1) - { - showInitialPrompt = false; - } - else - { - // Do we have profile files? - // Yes -> Do not show prompt here. - // No -> Show prompt here - if (DoWeHaveProfileFiles()) - { - showInitialPrompt = false; - } - else - { - showInitialPrompt = true; - } - } - } - } -#endif - // WTR - Check for the key that indicates absence of NetFx4 and output appropriate message to the user // Open PowerShellEngine Registry Key @@ -2088,7 +1742,6 @@ int __cdecl wszRuntimeVersion, wszConsoleHostAssemblyName, pArgvSA, - showInitialPrompt, skipIndex, argc, argv);