Update files from Source Depot changeset [SD:706766]

Corresponds to e2ce37c87c0ab9795bfac2389edc1aff934bdb9e in psl-monad.
This commit is contained in:
PowerShell Team
2016-05-23 13:14:28 -07:00
committed by Andrew Schwartzmeyer
parent dd950e4837
commit b8dced8e80
21 changed files with 621 additions and 538 deletions
@@ -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;
@@ -513,7 +513,6 @@ namespace Microsoft.PowerShell
/// If Win32's SetConsoleCtrlHandler fails
/// </exception>
[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<ConsoleHandle> _inputHandle = new Lazy<SafeFileHandle>(() =>
static readonly Lazy<ConsoleHandle> _keyboardInputHandle = new Lazy<SafeFileHandle>(() =>
{
var handle = NativeMethods.CreateFile(
"CONIN$",
@@ -580,19 +579,11 @@ namespace Microsoft.PowerShell
);
/// <summary>
///
/// Returns a ConsoleHandle to the console input device, even if stdin has been redirected.
///
/// Returns a ConsoleHandle to the console (keyboard device)
/// </summary>
/// <returns></returns>
/// <exception cref="HostException">
/// If Win32's CreateFile fails
/// </exception>
[ArchitectureSensitive]
internal static ConsoleHandle GetInputHandle()
internal static ConsoleHandle GetConioDeviceHandle()
{
return _inputHandle.Value;
return _keyboardInputHandle.Value;
}
static readonly Lazy<ConsoleHandle> _outputHandle = new Lazy<SafeFileHandle>(() =>
@@ -627,7 +618,6 @@ namespace Microsoft.PowerShell
/// <exception cref="HostException">
/// If Win32's CreateFile fails
/// </exception>
[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
/// </exception>
[ArchitectureSensitive]
internal static ConsoleModes GetMode(ConsoleHandle consoleHandle)
{
Dbg.Assert(!consoleHandle.IsInvalid, "consoleHandle is not valid");
@@ -739,7 +725,6 @@ namespace Microsoft.PowerShell
///
/// </exception>
[ArchitectureSensitive]
internal static void SetMode(ConsoleHandle consoleHandle, ConsoleModes mode)
{
Dbg.Assert(!consoleHandle.IsInvalid, "consoleHandle is not valid");
@@ -800,7 +785,6 @@ namespace Microsoft.PowerShell
///
/// </exception>
[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
/// </exception>
[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
/// </exception>
[ArchitectureSensitive]
internal static int PeekConsoleInput
(
ConsoleHandle consoleHandle,
@@ -960,7 +942,6 @@ namespace Microsoft.PowerShell
/// If Win32's GetNumberOfConsoleInputEvents fails
/// </exception>
[ArchitectureSensitive]
internal static int GetNumberOfConsoleInputEvents(ConsoleHandle consoleHandle)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
@@ -992,7 +973,6 @@ namespace Microsoft.PowerShell
/// <exception cref="HostException">
/// If Win32's FlushConsoleInputBuffer fails
/// </exception>
[ArchitectureSensitive]
internal static void FlushConsoleInputBuffer(ConsoleHandle consoleHandle)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
@@ -1033,7 +1013,6 @@ namespace Microsoft.PowerShell
/// <exception cref="HostException">
/// If Win32's GetConsoleScreenBufferInfo fails
/// </exception>
[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
/// </exception>
[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 <paramref name="contents"/> to the output buffer
/// </exception>
[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
/// <exception cref="HostException">
/// If there is not enough memory to complete calls to Win32's ReadConsoleOutput
/// </exception>
[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
/// </exception>
[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
/// <exception cref="HostException">
/// If there is not enough memory to complete calls to Win32's ReadConsoleOutput
/// </exception>
[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
/// <exception cref="HostException">
/// If Win32's FillConsoleOutputCharacter fails
/// </exception>
[ArchitectureSensitive]
internal static void FillConsoleOutputCharacter
(
ConsoleHandle consoleHandle,
@@ -2423,7 +2386,6 @@ namespace Microsoft.PowerShell
/// <exception cref="HostException">
/// If Win32's FillConsoleOutputAttribute fails
/// </exception>
[ArchitectureSensitive]
internal static void FillConsoleOutputAttribute
(
ConsoleHandle consoleHandle,
@@ -2491,7 +2453,6 @@ namespace Microsoft.PowerShell
/// If Win32's ScrollConsoleScreenBuffer fails
/// </exception>
[ArchitectureSensitive]
internal static void ScrollConsoleScreenBuffer
(
ConsoleHandle consoleHandle,
@@ -2549,7 +2510,6 @@ namespace Microsoft.PowerShell
/// If Win32's SetConsoleWindowInfo fails
/// </exception>
[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
/// </exception>
[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
/// </exception>
[ArchitectureSensitive]
internal static string GetConsoleWindowTitle()
{
const int MaxWindowTitleLength = 1024;
@@ -2654,7 +2612,6 @@ namespace Microsoft.PowerShell
/// If Win32's SetConsoleTitle fails
/// </exception>
[ArchitectureSensitive]
internal static void SetConsoleWindowTitle(string consoleTitle)
{
bool result = NativeMethods.SetConsoleTitle(consoleTitle);
@@ -2795,7 +2752,6 @@ namespace Microsoft.PowerShell
///
/// </exception>
[ArchitectureSensitive]
internal static void WriteConsole(ConsoleHandle consoleHandle, string output)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
@@ -2864,7 +2820,6 @@ namespace Microsoft.PowerShell
///
/// </exception>
[ArchitectureSensitive]
internal static void SetConsoleTextAttribute(ConsoleHandle consoleHandle, WORD attribute)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
@@ -3080,7 +3035,6 @@ namespace Microsoft.PowerShell
/// <param name="c"></param>
/// <param name="codePage"></param>
/// <returns></returns>
[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
/// </summary>
/// <returns></returns>
[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
/// </summary>
/// <param name="codePage"></param>
/// <returns></returns>
[ArchitectureSensitive]
internal static bool IsCJKOutputCodePage(out uint codePage)
{
codePage = NativeMethods.GetConsoleOutputCP();
@@ -3241,7 +3193,6 @@ namespace Microsoft.PowerShell
/// If Win32's SetConsoleCursorPosition fails
/// </exception>
[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
/// </exception>
[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
/// </exception>
[ArchitectureSensitive]
internal static void SetConsoleCursorInfo(ConsoleHandle consoleHandle, CONSOLE_CURSOR_INFO cursorInfo)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
@@ -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
///
/// </returns>
private uint DoRunspaceLoop(string initialCommand, bool skipProfiles, Collection<CommandParameter> 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;
/// <summary>
/// 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)
@@ -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)];
@@ -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;
}
/// <summary>
@@ -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
///
/// </param>
///
/// <returns>
///
/// 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
{
@@ -78,6 +78,41 @@ namespace Microsoft.PowerShell.Commands
}
private Signature signature;
/// <summary>
/// Gets or sets the file type of the byte array containing the content with
/// digital signature.
/// </summary>
[Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByContent")]
public string[] SourcePathOrExtension
{
get
{
return _sourcePathOrExtension;
}
set
{
_sourcePathOrExtension = value;
}
}
private string[] _sourcePathOrExtension;
/// <summary>
/// File contents as a byte array
/// </summary>
[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
/// </summary>
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<string> paths = new Collection<string>();
//
// 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<string> paths = new Collection<string>();
// 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.
/// </param>
protected abstract Signature PerformAction(string filePath);
/// <summary>
/// Performs the action (ie: get signature, or set signature)
/// on the specified contents.
/// </summary>
/// <param name="fileName">
/// The filename used for type if content is specified.
/// </param>
/// <param name="content">
/// The file contents on which to perform the action.
/// </param>
protected abstract Signature PerformAction(string fileName, byte[] content);
}
/// <summary>
@@ -218,6 +278,21 @@ namespace Microsoft.PowerShell.Commands
{
return SignatureHelper.GetSignature(filePath, null);
}
/// <summary>
/// Gets the signature from the specified file contents.
/// </summary>
/// <param name="sourcePathOrExtension">The file type associated with the contents</param>
/// <param name="content">
/// The contents of the file on which to perform the action.
/// </param>
/// <returns>
/// The signature on the specified file contents.
/// </returns>
protected override Signature PerformAction(string sourcePathOrExtension, byte[] content)
{
return SignatureHelper.GetSignature(sourcePathOrExtension, System.Text.Encoding.Unicode.GetString(content));
}
}
/// <summary>
@@ -494,6 +569,14 @@ namespace Microsoft.PowerShell.Commands
}
}
/// <summary>
/// Not implemented
/// </summary>
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.
/// </summary>
static readonly SigningOptionInfo[] sigOptionInfo =
private static readonly SigningOptionInfo[] sigOptionInfo =
{
new SigningOptionInfo(SigningOption.AddOnlyCertificate, "signer"),
new SigningOptionInfo(SigningOption.AddFullCertificateChainExceptRoot, "notroot"),
@@ -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")
}
+51
View File
@@ -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)
@@ -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);
}
@@ -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;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="moduleBase">The base path to use if the file is not rooted</param>
/// <param name="path">The file name to resolve.</param>
///
/// <returns></returns>
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) ||
@@ -285,6 +285,148 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
public abstract partial class PSRemotingBaseCmdlet : PSRemotingCmdlet
{
/// <summary>
/// State of virtual machine. This is the same as VMState in
/// \vm\ux\powershell\objects\common\Types.cs
/// </summary>
internal enum VMState
{
/// <summary>
/// Other. Corresponds to CIM_EnabledLogicalElement.EnabledState = Other.
/// </summary>
Other = 1,
/// <summary>
/// Running. Corresponds to CIM_EnabledLogicalElement.EnabledState = Enabled.
/// </summary>
Running = 2,
/// <summary>
/// Off. Corresponds to CIM_EnabledLogicalElement.EnabledState = Disabled.
/// </summary>
Off = 3,
/// <summary>
/// Stopping. Corresponds to CIM_EnabledLogicalElement.EnabledState = ShuttingDown.
/// </summary>
Stopping = 4,
/// <summary>
/// Saved. Corresponds to CIM_EnabledLogicalElement.EnabledState = Enabled but offline.
/// </summary>
Saved = 6,
/// <summary>
/// Paused. Corresponds to CIM_EnabledLogicalElement.EnabledState = Quiesce.
/// </summary>
Paused = 9,
/// <summary>
/// Starting. EnabledStateStarting. State transition from PowerOff or Saved to Running.
/// </summary>
Starting = 10,
/// <summary>
/// Reset. Corresponds to CIM_EnabledLogicalElement.EnabledState = Reset.
/// </summary>
Reset = 11,
/// <summary>
/// Saving. Corresponds to EnabledStateSaving.
/// </summary>
Saving = 32773,
/// <summary>
/// Pausing. Corresponds to EnabledStatePausing.
/// </summary>
Pausing = 32776,
/// <summary>
/// Resuming. Corresponds to EnabledStateResuming.
/// </summary>
Resuming = 32777,
/// <summary>
/// FastSaved. EnabledStateFastSuspend.
/// </summary>
FastSaved = 32779,
/// <summary>
/// FastSaving. EnabledStateFastSuspending.
/// </summary>
FastSaving = 32780,
/// <summary>
/// ForceShutdown. Used to force a graceful shutdown of the virtual machine.
/// </summary>
ForceShutdown = 32781,
/// <summary>
/// ForceReboot. Used to force a graceful reboot of the virtual machine.
/// </summary>
ForceReboot = 32782,
/// <summary>
/// RunningCritical. Critical states.
/// </summary>
RunningCritical,
/// <summary>
/// OffCritical. Critical states.
/// </summary>
OffCritical,
/// <summary>
/// StoppingCritical. Critical states.
/// </summary>
StoppingCritical,
/// <summary>
/// SavedCritical. Critical states.
/// </summary>
SavedCritical,
/// <summary>
/// PausedCritical. Critical states.
/// </summary>
PausedCritical,
/// <summary>
/// StartingCritical. Critical states.
/// </summary>
StartingCritical,
/// <summary>
/// ResetCritical. Critical states.
/// </summary>
ResetCritical,
/// <summary>
/// SavingCritical. Critical states.
/// </summary>
SavingCritical,
/// <summary>
/// PausingCritical. Critical states.
/// </summary>
PausingCritical,
/// <summary>
/// ResumingCritical. Critical states.
/// </summary>
ResumingCritical,
/// <summary>
/// FastSavedCritical. Critical states.
/// </summary>
FastSavedCritical,
/// <summary>
/// FastSavingCritical. Critical states.
/// </summary>
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<PSObject> 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;
@@ -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
{
@@ -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
@@ -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);
@@ -232,6 +232,7 @@ namespace System.Management.Automation.Remoting
InvalidContainerNameNotExist = 972,
ContainerSessionConnectFailed = 973,
RemoteSessionHyperVSocketClientConstructorSetSocketOptionFailure = 974,
InvalidVMState = 975,
// Invoke-Command related error codes.
InvalidVMIdNotSingle = 981,
@@ -64,11 +64,15 @@ namespace System.Management.Automation
int countHelpInfosFound = 0;
string helpFileName = helpRequest.Target + ".help.txt";
Collection<string> 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<string> FilterToLatestModuleVersion(Collection<string> filesMatched)
{
Collection<string> matchedFilesToRemove = new Collection<string>();
if (filesMatched.Count > 1)
{
//Dictionary<<ModuleName,fileName>, <Version, helpFileFullName>>
Dictionary<Tuple<string,string>, Tuple<string, Version>> modulesAndVersion = new Dictionary<Tuple<string,string>, Tuple<string,Version>>();
HashSet<string> filesProcessed = new HashSet<string>();
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<string, Version> moduleVersion = null;
Tuple<string, string> key = new Tuple<string, string>(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<string, Version>(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<string, string>(moduleName,fileName),
new Tuple<string, Version>(fileFullName, moduleVersionFromPath));
}
}
}
filesProcessed.Add(fileName);
}
}
return matchedFilesToRemove;
}
internal override IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
{
string target = helpRequest.Target;
@@ -132,11 +200,16 @@ namespace System.Management.Automation
Collection<String> 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;
}
/// <summary>
/// Load help file based on the file path.
/// </summary>
@@ -227,7 +320,7 @@ namespace System.Management.Automation
internal Collection<string> GetExtendedSearchPaths()
{
Collection<String> searchPaths = GetSearchPaths();
// Add $pshome at the top of the list
String defaultShellSearchPath = GetDefaultShellSearchPath();
int index = searchPaths.IndexOf(defaultShellSearchPath);
@@ -1225,6 +1225,9 @@ All WinRM sessions connected to Windows PowerShell session configurations, such
<data name="InvalidVMNameNotSingle" xml:space="preserve">
<value>The input VMName {0} does not resolve to a single virtual machine.</value>
</data>
<data name="InvalidVMState" xml:space="preserve">
<value>The virtual machine {0} is not in running state.</value>
</data>
<data name="InvalidCredential" xml:space="preserve">
<value>The credential is invalid.</value>
</data>
@@ -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);
@@ -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;
@@ -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*/
@@ -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 <mscorlib.tlb> 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\\<userName>\\Documents\\WindowsPowerShell\\profile.ps1"
// currentUserHostSpecificProfile "C:\\Users\\<userName>\\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);