diff --git a/.github/ISSUE_TEMPLATE/Release_Process.md b/.github/ISSUE_TEMPLATE/Release_Process.md index 47e5bd4dd50..121b4b9d771 100644 --- a/.github/ISSUE_TEMPLATE/Release_Process.md +++ b/.github/ISSUE_TEMPLATE/Release_Process.md @@ -40,3 +40,4 @@ Please **only** use this template if you are a maintainer. - [ ] Delete the release branch. - [ ] Trigger the Docker image release. - [ ] Retain builds. + - [ ] Update https://github.com/dotnet/dotnet-docker/tree/master/3.0/sdk with new version and SHA hashes for global tool. diff --git a/.vsts-ci/install-ps.yml b/.vsts-ci/install-ps.yml index 67b21241de7..2d7d07a63f6 100644 --- a/.vsts-ci/install-ps.yml +++ b/.vsts-ci/install-ps.yml @@ -6,6 +6,7 @@ trigger: include: - master - release* + - feature* paths: include: - /tools/install-powershell.sh @@ -21,6 +22,7 @@ pr: include: - master - release* + - feature* paths: include: - /tools/install-powershell.sh diff --git a/.vsts-ci/linux.yml b/.vsts-ci/linux.yml index ecc83ee813a..7e442ad99c3 100644 --- a/.vsts-ci/linux.yml +++ b/.vsts-ci/linux.yml @@ -6,6 +6,7 @@ trigger: include: - master - release* + - feature* paths: include: - '*' @@ -19,6 +20,7 @@ pr: include: - master - release* + - feature* paths: include: - '*' diff --git a/.vsts-ci/mac.yml b/.vsts-ci/mac.yml index 2e72d6d779f..de46de6b182 100644 --- a/.vsts-ci/mac.yml +++ b/.vsts-ci/mac.yml @@ -6,6 +6,7 @@ trigger: include: - master - release* + - feature* paths: include: - '*' @@ -19,6 +20,7 @@ pr: include: - master - release* + - feature* paths: include: - '*' diff --git a/.vsts-ci/misc-analysis.yml b/.vsts-ci/misc-analysis.yml index f18a3c5a037..f8504fd730f 100644 --- a/.vsts-ci/misc-analysis.yml +++ b/.vsts-ci/misc-analysis.yml @@ -6,12 +6,14 @@ trigger: include: - master - release* + - feature* pr: branches: include: - master - release* + - feature* resources: - repo: self diff --git a/.vsts-ci/windows.yml b/.vsts-ci/windows.yml index 91ed0829157..56ccd52fbbb 100644 --- a/.vsts-ci/windows.yml +++ b/.vsts-ci/windows.yml @@ -6,6 +6,7 @@ trigger: include: - master - release* + - feature* paths: include: - '*' @@ -19,6 +20,7 @@ pr: include: - master - release* + - feature* paths: include: - '*' diff --git a/assets/Square150x150Logo-Preview.png b/assets/Square150x150Logo-Preview.png new file mode 100644 index 00000000000..e206cf8064f Binary files /dev/null and b/assets/Square150x150Logo-Preview.png differ diff --git a/assets/Square44x44Logo-Preview.png b/assets/Square44x44Logo-Preview.png new file mode 100644 index 00000000000..df150a063b9 Binary files /dev/null and b/assets/Square44x44Logo-Preview.png differ diff --git a/assets/Square44x44Logo.targetsize-48-Preview.png b/assets/Square44x44Logo.targetsize-48-Preview.png new file mode 100644 index 00000000000..df150a063b9 Binary files /dev/null and b/assets/Square44x44Logo.targetsize-48-Preview.png differ diff --git a/assets/Square44x44Logo.targetsize-48_altform-unplated-Preview.png b/assets/Square44x44Logo.targetsize-48_altform-unplated-Preview.png new file mode 100644 index 00000000000..df150a063b9 Binary files /dev/null and b/assets/Square44x44Logo.targetsize-48_altform-unplated-Preview.png differ diff --git a/assets/StoreLogo-Preview.png b/assets/StoreLogo-Preview.png new file mode 100644 index 00000000000..8c1fa58568f Binary files /dev/null and b/assets/StoreLogo-Preview.png differ diff --git a/build.psm1 b/build.psm1 index 5059be3226c..9a14f5f8c23 100644 --- a/build.psm1 +++ b/build.psm1 @@ -127,7 +127,7 @@ function Get-EnvironmentInformation $LinuxInfo = Get-Content /etc/os-release -Raw | ConvertFrom-StringData $environment += @{'LinuxInfo' = $LinuxInfo} - $environment += @{'IsDebian' = $LinuxInfo.ID -match 'debian'} + $environment += @{'IsDebian' = $LinuxInfo.ID -match 'debian' -or $LinuxInfo.ID -match 'kali'} $environment += @{'IsDebian9' = $Environment.IsDebian -and $LinuxInfo.VERSION_ID -match '9'} $environment += @{'IsUbuntu' = $LinuxInfo.ID -match 'ubuntu'} $environment += @{'IsUbuntu16' = $Environment.IsUbuntu -and $LinuxInfo.VERSION_ID -match '16.04'} @@ -842,7 +842,10 @@ function Get-PesterTag { function Publish-PSTestTools { [CmdletBinding()] - param() + param( + [string] + $runtime + ) Find-Dotnet @@ -859,7 +862,12 @@ function Publish-PSTestTools { { Push-Location $tool.Path try { - dotnet publish --output bin --configuration $Options.Configuration --framework $Options.Framework --runtime $Options.Runtime + if (-not $runtime) { + dotnet publish --output bin --configuration $Options.Configuration --framework $Options.Framework --runtime $Options.Runtime + } else { + dotnet publish --output bin --configuration $Options.Configuration --framework $Options.Framework --runtime $runtime + } + $toolPath = Join-Path -Path $tool.Path -ChildPath "bin" if ( -not $env:PATH.Contains($toolPath) ) { @@ -1253,7 +1261,7 @@ function Publish-TestResults # If the the "test-case" count is greater than 0, then we have results. # Regardless, we want to upload this as an artifact, so this logic doesn't pertain to that. if ( @(([xml](Get-Content $Path)).SelectNodes(".//test-case")).Count -gt 0 -or $Type -eq 'XUnit' ) { - Write-Host "##vso[results.publish type=$Type;mergeResults=true;runTitle=$Title;publishRunAttachments=true;resultFiles=$tempFilePath;]" + Write-Host "##vso[results.publish type=$Type;mergeResults=true;runTitle=$Title;publishRunAttachments=true;resultFiles=$tempFilePath;failTaskOnFailedTests=true]" } $resolvedPath = (Resolve-Path -Path $Path).ProviderPath @@ -2974,7 +2982,8 @@ function New-TestPackage [CmdletBinding()] param( [Parameter(Mandatory = $true)] - [string] $Destination + [string] $Destination, + [string] $Runtime ) if (Test-Path $Destination -PathType Leaf) @@ -3002,7 +3011,7 @@ function New-TestPackage Write-Verbose -Verbose "PackagePath: $packagePath" # Build test tools so they are placed in appropriate folders under 'test' then copy to package root. - $null = Publish-PSTestTools + $null = Publish-PSTestTools -runtime $Runtime $powerShellTestRoot = Join-Path $PSScriptRoot 'test' Copy-Item $powerShellTestRoot -Recurse -Destination $packageRoot -Force Write-Verbose -Message "Copied test directory" diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index bcf689b1a17..cd685204784 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -57,7 +57,7 @@ - + diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index c6deb0e0d3e..2f45e682f64 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -422,7 +422,7 @@ internal string WorkingDirectory { return _workingDirectory.Remove(_workingDirectory.Length - 1); } - #endif +#endif return _workingDirectory; } } @@ -529,7 +529,7 @@ private static string GetConfigurationNameFromGroupPolicy() /// private static void EarlyParseHelper(string[] args) { - if(args == null) + if (args == null) { Dbg.Assert(args != null, "Argument 'args' to EarlyParseHelper should never be null"); return; @@ -1043,7 +1043,7 @@ private void ParseFormat(string[] args, ref int i, ref Serialization.DataFormat foreach (string s in Enum.GetNames(typeof(Serialization.DataFormat))) { sb.Append(s); - sb.Append(ConsoleHostUserInterface.Crlf); + sb.Append(Environment.NewLine); } ++i; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index f925dbd7f73..d8a2c199d65 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -48,7 +48,7 @@ namespace Microsoft.PowerShell internal static class ConsoleControl { #if !UNIX -#region structs + #region structs internal enum InputRecordEventTypes : ushort { @@ -246,7 +246,7 @@ internal struct TEXTMETRIC public byte tmCharSet; } -#region SentInput Data Structures + #region SentInput Data Structures [StructLayout(LayoutKind.Sequential)] internal struct INPUT @@ -417,11 +417,11 @@ internal enum KeyboardFlag : uint ScanCode = 0x0008 } -#endregion SentInput Data Structures + #endregion SentInput Data Structures -#endregion structs + #endregion structs -#region Window Visibility + #region Window Visibility [DllImport(PinvokeDllNames.GetConsoleWindowDllName)] internal static extern IntPtr GetConsoleWindow(); @@ -473,9 +473,9 @@ internal static void SetConsoleMode(ProcessWindowStyle style) } } #endif -#endregion + #endregion -#region Input break handler (Ctrl-C, Ctrl-Break) + #region Input break handler (Ctrl-C, Ctrl-Break) /// /// Types of control ConsoleBreakSignals received by break Win32Handler delegates. @@ -546,9 +546,9 @@ internal static void RemoveBreakHandler() } } -#endregion + #endregion -#region Win32Handles + #region Win32Handles private static readonly Lazy _keyboardInputHandle = new Lazy(() => { @@ -621,9 +621,9 @@ internal static ConsoleHandle GetActiveScreenBufferHandle() return _outputHandle.Value; } -#endregion + #endregion -#region Mode + #region Mode /// /// Flags used by ConsoleControl.GetMode and ConsoleControl.SetMode. @@ -707,9 +707,9 @@ internal static void SetMode(ConsoleHandle consoleHandle, ConsoleModes mode) } } -#endregion + #endregion -#region Input + #region Input /// /// Reads input from the console device according to the mode in effect (see GetMode, SetMode) @@ -943,9 +943,9 @@ internal static void FlushConsoleInputBuffer(ConsoleHandle consoleHandle) } } -#endregion Input + #endregion Input -#region Buffer + #region Buffer /// /// Wraps Win32 GetConsoleScreenBufferInfo @@ -1178,7 +1178,7 @@ private static void BuildEdgeTypeInfo( firstRightLeadingRow = r; } - for (;;) + for (; ; ) { r++; if (r > contentsRegion.Bottom) @@ -1769,7 +1769,7 @@ internal static void ReadConsoleOutput } } -#region ReadConsoleOutput CJK + #region ReadConsoleOutput CJK /// /// If an edge cell read is a blank, it is potentially part of a double width character. Hence, /// at least one of the left and right edges should be checked. @@ -2066,7 +2066,7 @@ out background rowIndex++; } } -#endregion ReadConsoleOutput CJK + #endregion ReadConsoleOutput CJK private static void ReadConsoleOutputPlain ( @@ -2408,9 +2408,9 @@ internal static void ScrollConsoleScreenBuffer } } -#endregion Buffer + #endregion Buffer -#region Window + #region Window /// /// Wraps Win32 SetConsoleWindowInfo. @@ -2536,7 +2536,7 @@ internal static void SetConsoleWindowTitle(string consoleTitle) } } -#endregion Window + #endregion Window /// /// Wrap Win32 WriteConsole. @@ -2562,7 +2562,7 @@ internal static void WriteConsole(ConsoleHandle consoleHandle, ReadOnlySpan outBufferLine = stackalloc char[outBuffer.Length + endOfLineLength]; outBuffer.CopyTo(outBufferLine); @@ -2661,7 +2661,7 @@ internal static void SetConsoleTextAttribute(ConsoleHandle consoleHandle, WORD a } #endif -#region Dealing with CJK + #region Dealing with CJK // Return the length of a VT100 control sequence character in str starting // at the given offset. @@ -2748,11 +2748,11 @@ internal static bool IsCJKOutputCodePage(out uint codePage) } #endif -#endregion Dealing with CJK + #endregion Dealing with CJK #if !UNIX -#region Cursor + #region Cursor /// /// Wraps Win32 SetConsoleCursorPosition. @@ -2874,9 +2874,9 @@ internal static void SetConsoleCursorInfo(ConsoleHandle consoleHandle, CONSOLE_C } } -#endregion Cursor + #endregion Cursor -#region helper + #region helper /// /// Helper function to create the proper HostException. @@ -2895,9 +2895,9 @@ private static HostException CreateHostException( return e; } -#endregion helper + #endregion helper -#region + #region internal static int LengthInBufferCells(char c) { @@ -2915,16 +2915,16 @@ internal static int LengthInBufferCells(char c) (c >= 0xfe30 && c <= 0xfe6f) || /* CJK Compatibility Forms */ (c >= 0xff00 && c <= 0xff60) || /* Fullwidth Forms */ (c >= 0xffe0 && c <= 0xffe6)); - // We can ignore these ranges because .Net strings use surrogate pairs - // for this range and we do not handle surrogage pairs. - // (c >= 0x20000 && c <= 0x2fffd) || - // (c >= 0x30000 && c <= 0x3fffd) + // We can ignore these ranges because .Net strings use surrogate pairs + // for this range and we do not handle surrogage pairs. + // (c >= 0x20000 && c <= 0x2fffd) || + // (c >= 0x30000 && c <= 0x3fffd) return 1 + (isWide ? 1 : 0); } -#endregion + #endregion -#region SendInput + #region SendInput internal static void MimicKeyPress(INPUT[] inputs) { @@ -2941,7 +2941,7 @@ internal static void MimicKeyPress(INPUT[] inputs) } } -#endregion SendInput + #endregion SendInput /// /// Class to hold the Native Methods used in this file enclosing class. @@ -2953,7 +2953,7 @@ internal static class NativeMethods internal const int FontTypeMask = 0x06; internal const int TrueTypeFont = 0x04; -#region CreateFile + #region CreateFile [Flags] internal enum AccessQualifiers : uint @@ -2993,14 +2993,14 @@ internal static extern NakedWin32Handle CreateFile NakedWin32Handle templateFileWin32Handle ); -#endregion CreateFile + #endregion CreateFile -#region Code Page + #region Code Page [DllImport(PinvokeDllNames.GetConsoleOutputCPDllName, SetLastError = false, CharSet = CharSet.Unicode)] internal static extern uint GetConsoleOutputCP(); -#endregion Code Page + #endregion Code Page [DllImport(PinvokeDllNames.GetConsoleWindowDllName, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern HWND GetConsoleWindow(); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 7f8ea165537..a0689ba60a3 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -50,7 +50,7 @@ internal sealed partial class ConsoleHost #region static methods internal const int ExitCodeSuccess = 0; - internal const int ExitCodeCtrlBreak = 128+21; // SIGBREAK + internal const int ExitCodeCtrlBreak = 128 + 21; // SIGBREAK internal const int ExitCodeInitFailure = 70; // Internal Software Error internal const int ExitCodeBadCommandLineParameter = 64; // Command Line Usage Error diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs index 5f1c63af9c0..af9d754861c 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs @@ -1251,7 +1251,7 @@ int LengthInBufferCells(char c) return ConsoleControl.LengthInBufferCells(c); } -#region internal + #region internal /// /// Clear the ReadKey cache. @@ -1262,9 +1262,9 @@ internal void ClearKeyCache() cachedKeyEvent.RepeatCount = 0; } -#endregion internal + #endregion internal -#region helpers + #region helpers // pass-by-ref for speed. /// @@ -1315,7 +1315,7 @@ private static return result; } -#endregion helpers + #endregion helpers private ConsoleColor defaultForeground = ConsoleColor.Gray; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index 53431f42d92..76f0473115f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -712,7 +712,7 @@ private void WriteImpl(string value, bool newLine) if (newLine) { - _parent.OutputSerializer.Serialize(Crlf); + _parent.OutputSerializer.Serialize(Environment.NewLine); } } else @@ -1152,14 +1152,14 @@ internal string WrapToCurrentWindowWidth(string text) sb.Append(s); if (++count != lines.Count) { - sb.Append(Crlf); + sb.Append(Environment.NewLine); } } return sb.ToString(); } -#endregion Word Wrapping + #endregion Word Wrapping /// /// See base class. @@ -1344,7 +1344,7 @@ public override void WriteErrorLine(string value) { Dbg.Assert(writer == _parent.ErrorSerializer.textWriter, "writers should be the same"); - _parent.ErrorSerializer.Serialize(value + Crlf); + _parent.ErrorSerializer.Serialize(value + Environment.NewLine); } else { @@ -1580,8 +1580,8 @@ private string ReadLineFromConsole(bool endOnTab, string initialContent, bool ca } #endif - do - { + do + { #if UNIX keyInfo = Console.ReadKey(true); #else @@ -1595,35 +1595,35 @@ private string ReadLineFromConsole(bool endOnTab, string initialContent, bool ca #else if (s.Length == 0) #endif - { - result = ReadLineResult.endedOnBreak; - s = null; - - if (calledFromPipeline) - { - // make sure that the pipeline that called us is stopped + { + result = ReadLineResult.endedOnBreak; + s = null; - throw new PipelineStoppedException(); - } + if (calledFromPipeline) + { + // make sure that the pipeline that called us is stopped - break; + throw new PipelineStoppedException(); } + break; + } + #if UNIX if (keyInfo.Key == ConsoleKey.Enter) #else - if (s.EndsWith(Crlf, StringComparison.Ordinal)) + if (s.EndsWith(Environment.NewLine, StringComparison.Ordinal)) #endif - { - result = ReadLineResult.endedOnEnter; + { + result = ReadLineResult.endedOnEnter; #if UNIX // We're intercepting characters, so we need to echo the newline Console.Out.WriteLine(); #else - s = s.Remove(s.Length - Crlf.Length); + s = s.Remove(s.Length - Environment.NewLine.Length); #endif - break; - } + break; + } #if UNIX if (keyInfo.Key == ConsoleKey.Tab) @@ -1806,15 +1806,15 @@ private string ReadLineFromConsole(bool endOnTab, string initialContent, bool ca Console.Out.Write(s); Console.CursorLeft = cursorCurrent + 1; #endif - } - while (true); + } + while (true); - Dbg.Assert( - (s == null && result == ReadLineResult.endedOnBreak) - || (s != null && result != ReadLineResult.endedOnBreak), - "s should only be null if input ended with a break"); + Dbg.Assert( + (s == null && result == ReadLineResult.endedOnBreak) + || (s != null && result != ReadLineResult.endedOnBreak), + "s should only be null if input ended with a break"); - return s; + return s; #if UNIX } finally diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs index 88ad4e99792..8cf227ba40e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs @@ -85,7 +85,7 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt progPaneUpdateFlag = 1; // The timer will be auto restarted every 'UpdateTimerThreshold' ms - _progPaneUpdateTimer = new Timer( new TimerCallback(ProgressPaneUpdateTimerElapsed), null, UpdateTimerThreshold, UpdateTimerThreshold); + _progPaneUpdateTimer = new Timer(new TimerCallback(ProgressPaneUpdateTimerElapsed), null, UpdateTimerThreshold, UpdateTimerThreshold); } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs index faee86bfd40..2a88d2d997d 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs @@ -55,7 +55,8 @@ public static int Start(string consoleFilePath, [MarshalAs(UnmanagedType.LPArray if (args.Length > 0 && !string.IsNullOrEmpty(args[0]) && args[0].Equals("-isswait", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("Attach the debugger to continue..."); - while (!System.Diagnostics.Debugger.IsAttached) { + while (!System.Diagnostics.Debugger.IsAttached) + { Thread.Sleep(100); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs index d65c545a327..e24823da6cc 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs @@ -172,7 +172,7 @@ class WrappedDeserializer : Serialization switch (format) { case DataFormat.XML: - _xmlReader = XmlReader.Create(textReader, new XmlReaderSettings { XmlResolver = null }); + _xmlReader = XmlReader.Create(textReader, new XmlReaderSettings { XmlResolver = null }); _xmlDeserializer = new Deserializer(_xmlReader); break; case DataFormat.Text: diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs index f979f9a010f..ed602725cf2 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs @@ -44,7 +44,7 @@ public string Path /// The literal name of the file in which to write the transcript. /// [Parameter(Position = 0, ParameterSetName = "ByLiteralPath")] - [Alias("PSPath","LP")] + [Alias("PSPath", "LP")] [ValidateNotNullOrEmpty] public string LiteralPath { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Telemetry.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Telemetry.cs index 0a827ba10e5..988ef5262fc 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Telemetry.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Telemetry.cs @@ -37,7 +37,8 @@ static ApplicationInsightsTelemetry() TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = _developerMode; } - private static bool GetEnvironmentVariableAsBool(string name, bool defaultValue) { + private static bool GetEnvironmentVariableAsBool(string name, bool defaultValue) + { var str = Environment.GetEnvironmentVariable(name); if (string.IsNullOrEmpty(str)) { @@ -62,11 +63,11 @@ private static bool GetEnvironmentVariableAsBool(string name, bool defaultValue) /// /// Send the telemetry. /// - private static void SendTelemetry(string eventName, Dictionary payload) + private static void SendTelemetry(string eventName, Dictionary payload) { try { - var enabled = !GetEnvironmentVariableAsBool(name : TelemetryOptoutEnvVar, defaultValue : false); + var enabled = !GetEnvironmentVariableAsBool(name: TelemetryOptoutEnvVar, defaultValue: false); if (!enabled) { diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs index 26e6a073e0e..a77a9abc9b3 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs @@ -1,14 +1,15 @@ + // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System; +using System.Diagnostics.Eventing.Reader; +using System.Runtime.InteropServices; +using System.Security; +using System.Text; + namespace System.Diagnostics.Eventing { - using System; - using System.Runtime.InteropServices; - using System.Security; - using System.Text; - using System.Diagnostics.Eventing.Reader; - internal static class UnsafeNativeMethods { private const string FormatMessageDllName = "api-ms-win-core-localization-l1-2-0.dll"; diff --git a/src/Microsoft.PowerShell.MarkdownRender/CodeInlineRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/CodeInlineRenderer.cs index ff755ac7903..0f0874a1513 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/CodeInlineRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/CodeInlineRenderer.cs @@ -16,7 +16,7 @@ internal class CodeInlineRenderer : VT100ObjectRenderer { protected override void Write(VT100Renderer renderer, CodeInline obj) { - renderer.Write(renderer.EscapeSequences.FormatCode(obj.Content, isInline : true)); + renderer.Write(renderer.EscapeSequences.FormatCode(obj.Content, isInline: true)); } } } diff --git a/src/Microsoft.PowerShell.MarkdownRender/EmphasisInlineRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/EmphasisInlineRenderer.cs index 01ee3913266..296fa53f188 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/EmphasisInlineRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/EmphasisInlineRenderer.cs @@ -16,7 +16,7 @@ internal class EmphasisInlineRenderer : VT100ObjectRenderer { protected override void Write(VT100Renderer renderer, EmphasisInline obj) { - renderer.Write(renderer.EscapeSequences.FormatEmphasis(obj.FirstChild.ToString(), isBold : obj.DelimiterCount == 2 ? true : false)); + renderer.Write(renderer.EscapeSequences.FormatEmphasis(obj.FirstChild.ToString(), isBold: obj.DelimiterCount == 2 ? true : false)); } } } diff --git a/src/Microsoft.PowerShell.MarkdownRender/ListItemBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/ListItemBlockRenderer.cs index 857192ae683..2ac778f9657 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/ListItemBlockRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/ListItemBlockRenderer.cs @@ -73,7 +73,7 @@ internal static string Padding(int countOfSpaces) if (result == null) { - Interlocked.CompareExchange(ref IndentCache[countOfSpaces], new string(' ', countOfSpaces), comparand : null); + Interlocked.CompareExchange(ref IndentCache[countOfSpaces], new string(' ', countOfSpaces), comparand: null); result = IndentCache[countOfSpaces]; } diff --git a/src/Microsoft.PowerShell.Security/security/AclCommands.cs b/src/Microsoft.PowerShell.Security/security/AclCommands.cs index 731ff5dd7cc..5590506f4aa 100644 --- a/src/Microsoft.PowerShell.Security/security/AclCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/AclCommands.cs @@ -1591,7 +1591,6 @@ protected override void ProcessRecord() } } #endif // !UNIX - } #pragma warning restore 56506 diff --git a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs index 938721a1c2b..89d1ab99628 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs @@ -140,22 +140,22 @@ protected override void ProcessRecord() } else { - if (Password == null && !NoPromptForPassword.IsPresent) + if (Password == null && !NoPromptForPassword.IsPresent) { - try + try { cert = GetCertFromPfxFile(resolvedProviderPath, null); WriteObject(cert); continue; - } - catch (CryptographicException) + } + catch (CryptographicException) { Password = SecurityUtils.PromptForSecureString( Host.UI, CertificateCommands.GetPfxCertPasswordPrompt); - } + } } - + try { cert = GetCertFromPfxFile(resolvedProviderPath, Password); diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index 4a4bce37c2b..6165f8b862a 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -3155,7 +3155,7 @@ public EnhancedKeyUsageProperty(X509Certificate2 cert) if (extension.Oid.Value == "2.5.29.37") { X509EnhancedKeyUsageExtension ext = extension as X509EnhancedKeyUsageExtension; - if(ext != null) + if (ext != null) { OidCollection oids = ext.EnhancedKeyUsages; foreach (Oid oid in oids) @@ -3204,21 +3204,21 @@ public DnsNameProperty(X509Certificate2 cert) // extract DNS name from subject distinguish name // if it exists and does not contain a comma // a comma, indicates it is not a DNS name - if(cert.Subject.StartsWith(distinguishedNamePrefix, System.StringComparison.InvariantCultureIgnoreCase) && - cert.Subject.IndexOf(",",System.StringComparison.InvariantCulture) == -1) + if (cert.Subject.StartsWith(distinguishedNamePrefix, System.StringComparison.InvariantCultureIgnoreCase) && + cert.Subject.IndexOf(",", System.StringComparison.InvariantCulture) == -1) { name = cert.Subject.Substring(distinguishedNamePrefix.Length); try { unicodeName = idnMapping.GetUnicode(name); } - catch(System.ArgumentException) + catch (System.ArgumentException) { // The name is not valid punyCode, assume it's valid ascii. unicodeName = name; } - dnsName = new DnsNameRepresentation(name,unicodeName); + dnsName = new DnsNameRepresentation(name, unicodeName); _dnsList.Add(dnsName); } @@ -3228,26 +3228,26 @@ public DnsNameProperty(X509Certificate2 cert) if (extension.Oid.Value == "2.5.29.17") { string[] names = extension.Format(true).Split(Environment.NewLine); - foreach(string nameLine in names) + foreach (string nameLine in names) { // Get the part after 'DNS Name=' - if(nameLine.StartsWith(dnsNamePrefix, System.StringComparison.InvariantCultureIgnoreCase)) + if (nameLine.StartsWith(dnsNamePrefix, System.StringComparison.InvariantCultureIgnoreCase)) { name = nameLine.Substring(dnsNamePrefix.Length); try { unicodeName = idnMapping.GetUnicode(name); } - catch(System.ArgumentException) + catch (System.ArgumentException) { // The name is not valid punyCode, assume it's valid ascii. unicodeName = name; } - dnsName = new DnsNameRepresentation(name,unicodeName); + dnsName = new DnsNameRepresentation(name, unicodeName); // Only add the name if it is not the same as an existing name. - if(!_dnsList.Contains(dnsName)) + if (!_dnsList.Contains(dnsName)) { _dnsList.Add(dnsName); } diff --git a/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index 237c3eb111f..46547407f29 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -20,7 +20,6 @@ namespace Microsoft.WSMan.Management { - /// /// WsMan Provider. /// @@ -122,27 +121,27 @@ string ICmdletProviderSupportsHelp.GetHelpMaml(string helpItemName, string path) document.Load(reader); } } - catch(XmlException) + catch (XmlException) { return string.Empty; } - catch(PathTooLongException) + catch (PathTooLongException) { return string.Empty; } - catch(IOException) + catch (IOException) { return string.Empty; } - catch(UnauthorizedAccessException) + catch (UnauthorizedAccessException) { return string.Empty; } - catch(NotSupportedException) + catch (NotSupportedException) { return string.Empty; } - catch(SecurityException) + catch (SecurityException) { return string.Empty; } @@ -167,7 +166,7 @@ string ICmdletProviderSupportsHelp.GetHelpMaml(string helpItemName, string path) { result = document.SelectSingleNode(xpathQuery, nsMgr); } - catch(XPathException) + catch (XPathException) { return string.Empty; } @@ -238,7 +237,6 @@ protected override PSDriveInfo RemoveDrive(PSDriveInfo drive) /// protected override string GetChildName(string path) { - string result = string.Empty; int separatorIndex = path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator); string hostname = string.Empty; @@ -254,7 +252,6 @@ protected override string GetChildName(string path) } return GetCorrectCaseOfName(result, hostname, path); - } /// @@ -328,7 +325,6 @@ protected override bool IsValidPath(string path) bool result = false; result = CheckValidContainerOrPath(path); return result; - } /// @@ -393,7 +389,7 @@ protected override bool HasChildItems(string path) string WsManURI = NormalizePath(path, host); - lock(WSManHelper.AutoSession) + lock (WSManHelper.AutoSession) { // Gets the session object from the cache. object sessionobj; @@ -443,7 +439,6 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi // 3. Plugin and its internal structure Checks else if (WsManURI.Contains(WSManStringLiterals.containerPlugin)) { - strPathCheck = strPathCheck + WSManStringLiterals.containerPlugin; // Check for Plugin path XmlDocument xmlPlugins = FindResourceValue(sessionobj, WsManURI, null); @@ -459,7 +454,6 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi { return false; } - } strPathCheck = strPathCheck + WSManStringLiterals.DefaultPathSeparator + currentpluginname; @@ -549,7 +543,6 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi string sSecurity = security.Properties["SecurityDIR"].Value.ToString(); if (path.EndsWith(sSecurity, StringComparison.OrdinalIgnoreCase)) return true; - } } } @@ -582,7 +575,6 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")] protected override void GetItem(string path) { - string childname = string.Empty; if (path.Length == 0 && string.IsNullOrEmpty(childname)) @@ -618,7 +610,7 @@ protected override void GetItem(string path) string host = GetHostName(path); string uri = NormalizePath(path, host); - lock(WSManHelper.AutoSession) + lock (WSManHelper.AutoSession) { // Gets the session object from the cache. object sessionobj; @@ -881,7 +873,6 @@ protected override void GetItem(string path) [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")] protected override void SetItem(string path, object value) { - if (value == null) { throw new ArgumentException(helper.GetResourceMsgFromResourcetext("value")); @@ -927,7 +918,7 @@ protected override void SetItem(string path, object value) // If validation is not required, that means Clear-Item cmdlet is called. // Clear-Item is not allowed on RunAsPassword, Admin should call Clear-Item RunAsUser // if he intends to disable RunAs on the Plugin. - if(string.Equals(ChildName, WSManStringLiterals.ConfigRunAsPasswordName, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(ChildName, WSManStringLiterals.ConfigRunAsPasswordName, StringComparison.OrdinalIgnoreCase)) { AssertError(helper.GetResourceMsgFromResourcetext("ClearItemOnRunAsPassword"), false); return; @@ -958,7 +949,7 @@ protected override void SetItem(string path, object value) bool settingPickedUpDynamically = false; - lock(WSManHelper.AutoSession) + lock (WSManHelper.AutoSession) { // Gets the session object from the cache. object sessionobj; @@ -1048,7 +1039,7 @@ protected override void SetItem(string path, object value) if (WSManStringLiterals.ConfigRunAsPasswordName.Equals(ChildName, StringComparison.OrdinalIgnoreCase)) { - if(string.IsNullOrEmpty( + if (string.IsNullOrEmpty( pluginConfiguration.GetOneConfiguration( string.Format( CultureInfo.InvariantCulture, @@ -1072,7 +1063,6 @@ protected override void SetItem(string path, object value) { AssertError(helper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false); return; - } strPathChk = strPathChk + WSManStringLiterals.containerResources + WSManStringLiterals.DefaultPathSeparator; @@ -1294,7 +1284,7 @@ protected override void SetItem(string path, object value) { if (!Force) { - string query=""; + string query = ""; string caption = helper.GetResourceMsgFromResourcetext("SetItemGeneralSecurityCaption"); if (ChildName.Equals("TrustedHosts", StringComparison.OrdinalIgnoreCase)) { @@ -1350,7 +1340,7 @@ protected override void SetItem(string path, object value) } } - foreach(String warnings in warningMessage) + foreach (String warnings in warningMessage) { WriteWarning(warnings); } @@ -1405,7 +1395,6 @@ protected override object SetItemDynamicParameters(string path, object value) /// protected override void GetChildItems(string path, bool recurse) { - GetChildItemsOrNames(path, ProviderMethods.GetChildItems, recurse); } @@ -1416,7 +1405,6 @@ protected override void GetChildItems(string path, bool recurse) /// protected override void GetChildNames(string path, ReturnContainers returnContainers) { - GetChildItemsOrNames(path, ProviderMethods.GetChildNames, false); } #endregion @@ -1430,7 +1418,6 @@ protected override void GetChildNames(string path, ReturnContainers returnContai /// protected override bool IsItemContainer(string path) { - string childname = string.Empty; string strPathCheck = string.Empty; @@ -1461,7 +1448,7 @@ protected override bool IsItemContainer(string path) string host = GetHostName(path); string WsManURI = NormalizePath(path, host); - lock(WSManHelper.AutoSession) + lock (WSManHelper.AutoSession) { // Gets the session object from the cache. object sessionobj; @@ -1522,7 +1509,6 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Co // 3. Plugin and its internal structure Checks else if (WsManURI.Contains(WSManStringLiterals.containerPlugin)) { - strPathCheck = strPathCheck + WSManStringLiterals.containerPlugin; // Check for Plugin path if (path.EndsWith(strPathCheck, StringComparison.OrdinalIgnoreCase)) @@ -1603,7 +1589,6 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Co string sSecurity = security.Properties["SecurityDIR"].Value.ToString(); if (path.EndsWith(sSecurity, StringComparison.OrdinalIgnoreCase)) return true; - } } } @@ -1678,7 +1663,7 @@ protected override void RemoveItem(string path, bool recurse) } } - lock(WSManHelper.AutoSession) + lock (WSManHelper.AutoSession) { // Gets the session object from the cache. object sessionobj; @@ -1848,7 +1833,7 @@ protected override void NewItem(string path, string itemTypeName, object newItem string uri = NormalizePath(path, host); - lock(WSManHelper.AutoSession) + lock (WSManHelper.AutoSession) { Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); SessionObjCache.TryGetValue(host, out sessionobj); @@ -1982,7 +1967,6 @@ private void NewItemCreateComputerConnection(string Name) if (dynParams.ConnectionURI != null) { parametersetName = "URI"; - } helper.CreateWsManConnection(parametersetName, dynParams.ConnectionURI, dynParams.Port, Name, dynParams.ApplicationName, dynParams.UseSSL, dynParams.Authentication, dynParams.SessionOption, this.Credential, dynParams.CertificateThumbprint); @@ -2046,7 +2030,6 @@ private void NewItemContainerListenerOrCertMapping(object sessionobj, string pat WriteItemObject(GetItemPSObjectWithTypeName(resource.Key.ToString(), WSManStringLiterals.ContainerChildValue, null, (string[])kCache[resource.Key], string.Empty, WsManElementObjectTypes.WSManConfigContainerElement), path + WSManStringLiterals.DefaultPathSeparator + resource.Key.ToString(), true); } } - } /// @@ -2247,12 +2230,10 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h SecurityArray = newSecurity; } } - } if (path.EndsWith(strPathChk + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) { - WSManProviderInitializeParameters niParams = DynamicParameters as WSManProviderInitializeParameters; mshObj.Properties.Add(new PSNoteProperty(niParams.ParamName, niParams.ParamValue)); inputStr = ConstructInitParamsXml(mshObj, null); @@ -2426,7 +2407,6 @@ private void SetItemListenerOrClientCertificate(object sessionObj, string Resour /// private string GetInputStringForCreate(string ResourceURI, Hashtable value, string host) { - string putstr = string.Empty; string nilns = string.Empty; StringBuilder sbvalues = new StringBuilder(); @@ -2528,7 +2508,6 @@ private string GetHostName(string path) Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); if (!SessionObjCache.ContainsKey(sHostname)) sHostname = null; - } catch (ArgumentNullException e) { @@ -2642,7 +2621,6 @@ private XmlNodeList SearchXml(XmlDocument resourcexmldocument, string searchitem } nodes = resourcexmldocument.SelectNodes(xpathString); - } catch (System.Xml.XPath.XPathException ex) { @@ -2682,7 +2660,7 @@ private void PutResourceValue(object sessionobj, string ResourceURI, Hashtable v { for (int i = 0; i < node.ChildNodes.Count; i++) { - if ( (node.ChildNodes[i].ChildNodes.Count == 0) || node.ChildNodes[i].FirstChild.Name.Equals("#text", StringComparison.OrdinalIgnoreCase)) + if ((node.ChildNodes[i].ChildNodes.Count == 0) || node.ChildNodes[i].FirstChild.Name.Equals("#text", StringComparison.OrdinalIgnoreCase)) { foreach (string key in value.Keys) { @@ -2797,7 +2775,6 @@ private XmlDocument EnumerateResourceValue(object sessionobj, string ResourceURI xmlEnumResources.LoadXml(strXmlValue); this.enumerateMapping.Add(ResourceURI, xmlEnumResources); } - } finally { @@ -2809,7 +2786,6 @@ private XmlDocument EnumerateResourceValue(object sessionobj, string ResourceURI } return xmlEnumResources; - } /// @@ -2832,7 +2808,6 @@ private void DeleteResourceValue(object sessionobj, string ResourceURI, Hashtabl } ((IWSManSession)sessionobj).Delete(ResourceURI, 0); - } } finally @@ -2868,7 +2843,6 @@ private void CreateResourceValue(object sessionobj, string ResourceURI, string r AssertError(((IWSManSession)sessionobj).Error, true); } } - } /// @@ -3202,7 +3176,6 @@ private string SplitAndUpdateStringUsingDelimiter(object sessionobj, string uri, } catch (PSArgumentException) { - } return existingvalue; @@ -3239,7 +3212,7 @@ private PSObject BuildHostLevelPSObjectArrayList(object objSessionObject, string foreach (XmlNode node1 in node.ChildNodes) { // Getting Top Element in - if ( (node1.ChildNodes.Count == 0) || node1.FirstChild.Name.Equals("#text", StringComparison.OrdinalIgnoreCase)) + if ((node1.ChildNodes.Count == 0) || node1.FirstChild.Name.Equals("#text", StringComparison.OrdinalIgnoreCase)) { mshobject.Properties.Add(new PSNoteProperty(node1.LocalName, node1.InnerText)); } @@ -3250,7 +3223,6 @@ private PSObject BuildHostLevelPSObjectArrayList(object objSessionObject, string foreach (string root in WinRmRootConfigs) { mshobject.Properties.Add(new PSNoteProperty(root, WSManStringLiterals.ContainerChildValue)); - } } @@ -3268,7 +3240,7 @@ private PSObject ConvertToPSObject(XmlNode xmlnode) foreach (XmlNode node in xmlnode.ChildNodes) { // If node contains 0 child-nodes, it is empty node, if it's name = "#text" then it's a simple node. - if ( (node.ChildNodes.Count == 0) || node.FirstChild.Name.Equals("#text", StringComparison.OrdinalIgnoreCase)) + if ((node.ChildNodes.Count == 0) || node.FirstChild.Name.Equals("#text", StringComparison.OrdinalIgnoreCase)) { XmlAttribute attrSource = null; foreach (XmlAttribute attr in node.Attributes) @@ -3296,7 +3268,6 @@ private PSObject ConvertToPSObject(XmlNode xmlnode) } return mshObject; - } private string SetXPathString(string uri) @@ -3461,7 +3432,7 @@ private PSObject GetItemValue(string path) AssertError("WinRMServiceError", false); } - lock(WSManHelper.AutoSession) + lock (WSManHelper.AutoSession) { object sessionobj; // gets the sessionobject @@ -3649,25 +3620,25 @@ private string GetCorrectCaseOfName(string ChildName, string hostname, string pa string uri = NormalizePath(path, hostname); - lock(WSManHelper.AutoSession) + lock (WSManHelper.AutoSession) { object sessionobj; SessionObjCache.TryGetValue(hostname, out sessionobj); XmlDocument outxml = FindResourceValue(sessionobj, uri, null); if (outxml != null) { - string currentPluginName = string.Empty; - GetPluginNames(outxml, out objPluginNames, out currentPluginName, path); - if (path.EndsWith(hostname + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerPlugin + WSManStringLiterals.DefaultPathSeparator + currentPluginName, StringComparison.OrdinalIgnoreCase)) - { - result = currentPluginName; + string currentPluginName = string.Empty; + GetPluginNames(outxml, out objPluginNames, out currentPluginName, path); + if (path.EndsWith(hostname + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerPlugin + WSManStringLiterals.DefaultPathSeparator + currentPluginName, StringComparison.OrdinalIgnoreCase)) + { + result = currentPluginName; + } } } } } } } - } else { if (ChildName.StartsWith(WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase)) @@ -3787,7 +3758,6 @@ private void GetChildItemOrNamesForListenerOrCertMapping(XmlDocument xmlResource return; } - } /// @@ -3906,7 +3876,6 @@ private bool CheckValidContainerOrPath(string path) if (string.IsNullOrEmpty(host)) { return false; - } // Chks the WinRM Service @@ -3927,7 +3896,7 @@ private bool CheckValidContainerOrPath(string path) return false; } - lock(WSManHelper.AutoSession) + lock (WSManHelper.AutoSession) { object sessionobj = null; Dictionary SessionObjCache = WSManHelper.GetSessionObjCache(); @@ -4029,7 +3998,6 @@ private bool CheckValidContainerOrPath(string path) } } } - } } } @@ -4093,7 +4061,7 @@ private bool ItemExistListenerOrClientCertificate(object sessionobj, string Reso return false; } - Hashtable KeysCache=null, objcache=null; + Hashtable KeysCache = null, objcache = null; if (parentListenerOrCert.Equals(WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) { ProcessCertMappingObjects(outxml, out objcache, out KeysCache); @@ -4131,7 +4099,7 @@ private bool ItemExistListenerOrClientCertificate(object sessionobj, string Reso // Get the object cache from the listener object PSObject obj = (PSObject)objcache[CurrentNode]; - CurrentNode = RemainingPath.Substring(pos+1); + CurrentNode = RemainingPath.Substring(pos + 1); if (CurrentNode.IndexOf(WSManStringLiterals.DefaultPathSeparator) != -1) { // No more directories allowed after listeners objects @@ -4168,7 +4136,6 @@ private void GetChildItemsRecurse(string path, string childname, ProviderMethods { GetChildItemsOrNames(path, ProviderMethods.GetChildItems, recurse); } - } /// @@ -4232,7 +4199,7 @@ private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool } } - lock(WSManHelper.AutoSession) + lock (WSManHelper.AutoSession) { object sessionobj; // gets the sessionobject @@ -4331,9 +4298,8 @@ private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool } return; - } - else if(path.EndsWith(WSManStringLiterals.containerQuotasParameters, StringComparison.OrdinalIgnoreCase)) + else if (path.EndsWith(WSManStringLiterals.containerQuotasParameters, StringComparison.OrdinalIgnoreCase)) { // Get the Quotas element from the config XML. XmlNodeList nodeListForQuotas = CurrentPluginXML.GetElementsByTagName(WSManStringLiterals.containerQuotasParameters); @@ -4515,7 +4481,6 @@ private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool } } } - } } else @@ -4935,7 +4900,6 @@ private ArrayList ProcessPluginResourceLevel(XmlDocument xmldoc, out ArrayList a resourceUri = attributecol[i].Value; strUniqueResourceId = "Resource_" + Convert.ToString(Math.Abs(attributecol[i].Value.GetHashCode()), CultureInfo.InvariantCulture); objResource.Properties.Add(new PSNoteProperty("ResourceDir", strUniqueResourceId)); - } if (attributecol[i].LocalName.Equals("ExactMatch", StringComparison.OrdinalIgnoreCase)) @@ -4988,7 +4952,6 @@ private ArrayList ProcessPluginResourceLevel(XmlDocument xmldoc, out ArrayList a nSecurity = ProcessPluginSecurityLevel(nSecurity, xmlCapabilities, strUniqueResourceId, resourceUri); Resources.Add(objResource); } - } } @@ -5098,7 +5061,6 @@ private ArrayList ProcessPluginSecurityLevel(ArrayList arrSecurity, XmlDocument /// An Configuration XML, ready to send to server. private string ConstructPluginXml(PSObject objinputparam, string ResourceURI, string host, string Operation, ArrayList resources, ArrayList securities, ArrayList initParams) { - StringBuilder sbvalues = new StringBuilder(); sbvalues.Append(" /// Computer dynamic parameters. This is similar to connect-wsman parameters. @@ -5544,7 +5503,6 @@ enum WsManElementObjectTypes /// public class WSManProviderNewItemComputerParameters { - /// /// The following is the definition of the input parameter "OptionSet". /// OptionSet is a hash table and is used to pass a set of switches to the @@ -5688,7 +5646,6 @@ public Uri ConnectionURI } private Uri connectionuri; - } /// @@ -5807,7 +5764,7 @@ public string File [Parameter()] public PSCredential RunAsCredential { - get { return this.runAsCredentials; } + get { return this.runAsCredentials; } set { this.runAsCredentials = value; } } @@ -5866,7 +5823,6 @@ public uint? ProcessIdleTimeoutSec /// public class WSManProviderInitializeParameters { - /// /// Parameter ParamName. /// @@ -5955,7 +5911,7 @@ public string Sddl private string _sddl; } -#region "ClientCertificate Dynamic Parameters" + #region "ClientCertificate Dynamic Parameters" /// /// Client Certificate Dynamic Parameters /// Path - WsMan:\Localhost\ClientCertificate. @@ -6041,12 +5997,11 @@ public bool Enabled } private bool _enabled = true; - } -#endregion + #endregion -#region Listener Dynamic Parameters + #region Listener Dynamic Parameters /// /// Listener Dynamic parameters @@ -6211,17 +6166,16 @@ public bool IsPortSpecified { _IsPortSpecified = value; } - } private bool _IsPortSpecified = false; } -#endregion + #endregion -#endregion + #endregion -#region SetItemDynamicParameters + #region SetItemDynamicParameters /// /// Set-Item Dynamic parameters @@ -6243,11 +6197,11 @@ public SwitchParameter Concatenate private SwitchParameter _concatenate = false; } -#endregion SetItemDynamicParameters + #endregion SetItemDynamicParameters -#endregion + #endregion -#region "String Literals" + #region "String Literals" internal static class WSManStringLiterals { @@ -6311,7 +6265,7 @@ internal static class WSManStringLiterals /// internal const string ContainerChildValue = "Container"; -#region WsMan Containers + #region WsMan Containers /// /// Plugin Container. @@ -6409,9 +6363,9 @@ internal static class WSManStringLiterals /// Possible Values in Plugin Top Security XML internal static readonly string[] NewItemSecurityParams = new string[] { "Uri", "Sddl", "ExactMatch" }; -#endregion WsMan Containers + #endregion WsMan Containers -#region WSMAN Config Names + #region WSMAN Config Names /// /// Name of the configuration which represents RunAs Password. /// @@ -6467,7 +6421,7 @@ internal static class WSManStringLiterals /// internal const string HiddenSuffixForSourceOfValue = "___Source"; -#endregion + #endregion /// /// This is used to start the service. return a bool value. if false we throw error. @@ -6502,12 +6456,11 @@ function Start-WSManServiceD15A7957836142a18627D7E1D342DD82 }} $_ | Start-WSManServiceD15A7957836142a18627D7E1D342DD82 -force $args[0] -captionForStart $args[1] -queryForStart $args[2] "; - } -#endregion "String Literals" + #endregion "String Literals" -#region "WsMan Output Objects" + #region "WsMan Output Objects" /// /// Base Output object. @@ -6532,7 +6485,6 @@ public string Name get { return _name; } set { _name = value; } - } private string _name; @@ -6584,7 +6536,6 @@ public object SourceOfValue get { return _SourceOfValue; } set { _SourceOfValue = value; } - } private object _SourceOfValue; @@ -6597,7 +6548,6 @@ public object Value get { return _value; } set { _value = value; } - } private object _value; @@ -6623,13 +6573,11 @@ public string[] Keys get { return _keys; } set { _keys = value; } - } private string[] _keys; } -#endregion "WsMan Output Objects" - + #endregion "WsMan Output Objects" } diff --git a/src/Microsoft.WSMan.Management/CredSSP.cs b/src/Microsoft.WSMan.Management/CredSSP.cs index 765a21a74d6..99318d96a4a 100644 --- a/src/Microsoft.WSMan.Management/CredSSP.cs +++ b/src/Microsoft.WSMan.Management/CredSSP.cs @@ -255,7 +255,6 @@ private void DeleteDelegateSettings(string applicationname, RegistryKey rootKey, bool otherkeys = false; try { - string Registry_Path_Credentials_Delegation = Registry_Path + @"\CredentialsDelegation"; RegistryKey Allow_Fresh_Credential_Key = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, true); if (Allow_Fresh_Credential_Key != null) @@ -642,7 +641,6 @@ private void UpdateCurrentUserRegistrySettings() { string key = GPOpath + "\\" + keyname + "\\" + @"Software\Policies\Microsoft\Windows"; UpdateGPORegistrySettings(applicationname, this.delegatecomputer, Registry.CurrentUser, key); - } } // saving gpo settings @@ -703,7 +701,6 @@ private void UpdateGPORegistrySettings(string applicationname, string[] delegate ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidOperation, null); WriteError(er); } - } #region IDisposable Members @@ -812,7 +809,7 @@ private string GetDelegateSettings(string applicationname) WriteError(er); } - return result; + return result; } #endregion private @@ -929,7 +926,6 @@ protected override void BeginProcessing() } #endregion IDisposable Members - } #endregion diff --git a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs index 86470c879c8..41427678150 100644 --- a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs +++ b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System; +using System.Globalization; +using System.Xml; + namespace Microsoft.WSMan.Management { - using System; - using System.Globalization; - using System.Xml; - /// /// Class that queries the server and gets current configurations. /// Also provides a generic way to update the configurations. diff --git a/src/Microsoft.WSMan.Management/Interop.cs b/src/Microsoft.WSMan.Management/Interop.cs index 239c59bef8a..25e2d9e81a3 100644 --- a/src/Microsoft.WSMan.Management/Interop.cs +++ b/src/Microsoft.WSMan.Management/Interop.cs @@ -19,7 +19,6 @@ namespace Microsoft.WSMan.Management { - #region "public Api" #region WsManEnumFlags @@ -162,7 +161,7 @@ public enum AuthenticationMechanism /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Credssp")] Credssp = 0x80, - } + } #endregion AuthenticationMechanism @@ -331,7 +330,6 @@ string CertificateThumbprint [DispId(1)] set; } - } /// IWSManConnectionOptions interface. @@ -694,9 +692,9 @@ string Error [DispId(29)] int EnumerationFlagAssociatedInstance(); } -#endregion IWsManEx + #endregion IWsManEx -#region IWsManResourceLocator + #region IWsManResourceLocator /// IWSManResourceLocator interface. [SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces")] @@ -737,7 +735,6 @@ public interface IWSManResourceLocator [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] string ResourceUri { - // IDL: HRESULT resourceUri (BSTR value); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")] [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] @@ -751,7 +748,6 @@ string ResourceUri [DispId(1)] [return: MarshalAs(UnmanagedType.BStr)] get; - } /// AddSelector method of IWSManResourceLocator interface. Add selector to resource locator @@ -857,11 +853,10 @@ string Error [return: MarshalAs(UnmanagedType.BStr)] get; } - } -#endregion IWsManResourceLocator + #endregion IWsManResourceLocator -#region IWSManSession + #region IWSManSession /// IWSManSession interface. [Guid("FC84FC58-1286-40C4-9DA0-C8EF6EC241E0")] [ComImport] @@ -1005,9 +1000,9 @@ int Timeout } } -#endregion IWSManSession + #endregion IWSManSession -#region IWSManResourceLocatorInternal + #region IWSManResourceLocatorInternal /// IWSManResourceLocatorInternal interface. [Guid("EFFAEAD7-7EC8-4716-B9BE-F2E7E9FB4ADB")] [ComImport] @@ -1124,7 +1119,7 @@ void GetMachineName( uint GetPropertySheetPages(out IntPtr hPages); } -#endregion IGroupPolicyObject + #endregion IGroupPolicyObject /// GpoNativeApi public sealed class GpoNativeApi @@ -1140,8 +1135,7 @@ internal static extern System.IntPtr EnterCriticalPolicySection( internal static extern bool LeaveCriticalPolicySection( [In] System.IntPtr hSection); } -#endregion - + #endregion } #pragma warning restore 1591 diff --git a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs index 67d2cc8efed..3722382813d 100644 --- a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs +++ b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs @@ -78,7 +78,6 @@ public string ComputerName { computername = "localhost"; } - } } @@ -261,7 +260,6 @@ protected override void BeginProcessing() // create the connection string connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); - } /// @@ -269,7 +267,6 @@ protected override void BeginProcessing() /// protected override void ProcessRecord() { - try { // create the resourcelocator object @@ -285,7 +282,6 @@ protected override void ProcessRecord() XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(resultXml); WriteObject(xmldoc.DocumentElement); - } finally { @@ -301,9 +297,7 @@ protected override void ProcessRecord() if (m_session != null) Dispose(m_session); - } - } #region IDisposable Members @@ -339,7 +333,5 @@ protected override void EndProcessing() // WSManHelper helper = new WSManHelper(); helper.CleanUp(); } - - } } diff --git a/src/Microsoft.WSMan.Management/NewWSManSession.cs b/src/Microsoft.WSMan.Management/NewWSManSession.cs index c0266497503..a2d3bfe6cfc 100644 --- a/src/Microsoft.WSMan.Management/NewWSManSession.cs +++ b/src/Microsoft.WSMan.Management/NewWSManSession.cs @@ -277,7 +277,6 @@ protected override void BeginProcessing() } WriteObject(objSessionOption); - } } } diff --git a/src/Microsoft.WSMan.Management/PingWSMan.cs b/src/Microsoft.WSMan.Management/PingWSMan.cs index 8f14c8ec99c..6781e940c15 100644 --- a/src/Microsoft.WSMan.Management/PingWSMan.cs +++ b/src/Microsoft.WSMan.Management/PingWSMan.cs @@ -16,7 +16,6 @@ namespace Microsoft.WSMan.Management { - #region Test-WSMAN /// @@ -138,7 +137,6 @@ public string ApplicationName /// protected override void ProcessRecord() { - WSManHelper helper = new WSManHelper(this); IWSManEx wsmanObject = (IWSManEx)new WSManClass(); string connectionStr = string.Empty; @@ -152,7 +150,7 @@ protected override void ProcessRecord() xmldoc.LoadXml(m_SessionObj.Identify(0)); WriteObject(xmldoc.DocumentElement); } - catch(Exception) + catch (Exception) { try { @@ -165,8 +163,8 @@ protected override void ProcessRecord() this.WriteError(er); } } - catch(Exception) - {} + catch (Exception) + { } } finally { @@ -199,7 +197,6 @@ protected override void ProcessRecord() } #endregion IDisposable Members - } #endregion } diff --git a/src/Microsoft.WSMan.Management/Set-QuickConfig.cs b/src/Microsoft.WSMan.Management/Set-QuickConfig.cs index 5525599f83b..b9950f48baf 100644 --- a/src/Microsoft.WSMan.Management/Set-QuickConfig.cs +++ b/src/Microsoft.WSMan.Management/Set-QuickConfig.cs @@ -191,7 +191,7 @@ private void QuickConfigRemoting(bool serviceonly) } string resultAction = resultopxml.SelectSingleNode(xpathText, nsmgr).InnerText; - if ( source != null && source.Equals("GPO")) + if (source != null && source.Equals("GPO")) { string Info_Msg = WSManResourceLoader.GetResourceString("L_QuickConfig_RemotingDisabledbyGP_00_ErrorMessage"); Info_Msg += " " + resultAction; @@ -260,7 +260,6 @@ private void QuickConfigRemoting(bool serviceonly) if (m_SessionObj != null) Dispose(m_SessionObj); - } } #endregion private @@ -289,7 +288,6 @@ private void QuickConfigRemoting(bool serviceonly) } #endregion IDisposable Members - } #endregion Set-WsManQuickConfig } diff --git a/src/Microsoft.WSMan.Management/WSManConnections.cs b/src/Microsoft.WSMan.Management/WSManConnections.cs index a0f5e931c26..98c7196831d 100644 --- a/src/Microsoft.WSMan.Management/WSManConnections.cs +++ b/src/Microsoft.WSMan.Management/WSManConnections.cs @@ -116,7 +116,6 @@ internal void ValidateSpecifiedAuthentication() [Cmdlet(VerbsCommunications.Connect, "WSMan", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=141437")] public class ConnectWSManCommand : AuthenticatingWSManCommand { - #region Parameters /// @@ -253,7 +252,6 @@ public SwitchParameter UseSSL /// protected override void BeginProcessing() { - WSManHelper helper = new WSManHelper(this); if (connectionuri != null) { @@ -283,7 +281,6 @@ protected override void BeginProcessing() helper.CreateWsManConnection(ParameterSetName, connectionuri, port, computername, applicationname, usessl.IsPresent, Authentication, sessionoption, Credential, CertificateThumbprint); } - } #endregion @@ -311,7 +308,6 @@ public string ComputerName set { - computername = value; if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase))) { @@ -343,7 +339,6 @@ public string ComputerName { session = null; this.Dispose(); - } #endregion IDisposable Members @@ -379,7 +374,6 @@ protected override void BeginProcessing() helper.AssertError(helper.GetResourceMsgFromResourcetext("InvalidComputerName"), false, computername); } } - } #endregion Disconnect-WSMAN } diff --git a/src/Microsoft.WSMan.Management/WSManInstance.cs b/src/Microsoft.WSMan.Management/WSManInstance.cs index 5ab3e64b160..329db732d9f 100644 --- a/src/Microsoft.WSMan.Management/WSManInstance.cs +++ b/src/Microsoft.WSMan.Management/WSManInstance.cs @@ -305,7 +305,7 @@ public string ReturnType } } - private string returntype="object"; + private string returntype = "object"; /// /// The following is the definition of the input parameter "SelectorSet". @@ -402,16 +402,16 @@ private string GetFilter() string name; string value; string[] Split = filter.Trim().Split(new char[] { '=', ';' }); - if ((Split.Length)%2 != 0) + if ((Split.Length) % 2 != 0) { // mismatched property name/value pair return null; } filter = ""; - for (int i = 0; i" + value + ""; } @@ -435,11 +435,11 @@ private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsman } else if (returntype.Equals("epr", StringComparison.OrdinalIgnoreCase)) { - flags = wsmanObject.EnumerationFlagReturnEPR(); + flags = wsmanObject.EnumerationFlagReturnEPR(); } else { - flags = wsmanObject.EnumerationFlagReturnObjectAndEPR(); + flags = wsmanObject.EnumerationFlagReturnObjectAndEPR(); } } @@ -458,7 +458,6 @@ private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsman if (dialect != null && filter != null) { - if (dialect.ToString().Equals(helper.ALIAS_WQL, StringComparison.OrdinalIgnoreCase) || dialect.ToString().Equals(helper.URI_WQL_DIALECT, StringComparison.OrdinalIgnoreCase)) { fragment = helper.URI_WQL_DIALECT; @@ -466,36 +465,36 @@ private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsman } else if (dialect.ToString().Equals(helper.ALIAS_ASSOCIATION, StringComparison.OrdinalIgnoreCase) || dialect.ToString().Equals(helper.URI_ASSOCIATION_DIALECT, StringComparison.OrdinalIgnoreCase)) { - if (associations) - { - flags |= wsmanObject.EnumerationFlagAssociationInstance(); - } - else - { - flags |= wsmanObject.EnumerationFlagAssociatedInstance(); - } - - fragment = helper.URI_ASSOCIATION_DIALECT; - dialect = new Uri(fragment); + if (associations) + { + flags |= wsmanObject.EnumerationFlagAssociationInstance(); + } + else + { + flags |= wsmanObject.EnumerationFlagAssociatedInstance(); + } + + fragment = helper.URI_ASSOCIATION_DIALECT; + dialect = new Uri(fragment); } else if (dialect.ToString().Equals(helper.ALIAS_SELECTOR, StringComparison.OrdinalIgnoreCase) || dialect.ToString().Equals(helper.URI_SELECTOR_DIALECT, StringComparison.OrdinalIgnoreCase)) { - filter = GetFilter(); - fragment = helper.URI_SELECTOR_DIALECT; - dialect = new Uri(fragment); + filter = GetFilter(); + fragment = helper.URI_SELECTOR_DIALECT; + dialect = new Uri(fragment); } obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags); } else if (filter != null) { - fragment = helper.URI_WQL_DIALECT; - dialect = new Uri(fragment); - obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags); + fragment = helper.URI_WQL_DIALECT; + dialect = new Uri(fragment); + obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags); } else { - obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, null, flags); + obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, null, flags); } while (!obj.AtEndOfStream) { @@ -536,7 +535,6 @@ protected override void ProcessRecord() { helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } - } try @@ -551,7 +549,7 @@ protected override void ProcessRecord() { xmldoc.LoadXml(m_session.Get(m_resource, 0)); } - catch(XmlException ex) + catch (XmlException ex) { helper.AssertError(ex.Message, false, computername); } @@ -576,7 +574,6 @@ protected override void ProcessRecord() helper.AssertError(ex.Message, false, computername); } } - } finally { @@ -625,10 +622,8 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - helper.CleanUp(); } - } #endregion @@ -644,7 +639,6 @@ protected override void EndProcessing() [Cmdlet(VerbsCommon.Set, "WSManInstance", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=141458")] public class SetWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable { - #region Parameters /// /// The following is the definition of the input parameter "ApplicationName". @@ -883,7 +877,7 @@ public Hashtable ValueSet #endregion - private WSManHelper helper ; + private WSManHelper helper; /// /// ProcessRecord method. /// @@ -921,7 +915,6 @@ protected override void ProcessRecord() { helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } - } IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, fragment, dialect, m_wsmanObject, resourceuri); @@ -934,7 +927,7 @@ protected override void ProcessRecord() { xmldoc.LoadXml(m_session.Put(m_resource, input, 0)); } - catch(XmlException ex) + catch (XmlException ex) { helper.AssertError(ex.Message, false, computername); } @@ -952,7 +945,6 @@ protected override void ProcessRecord() } else WriteObject(xmldoc.DocumentElement); - } finally { @@ -1003,7 +995,6 @@ protected override void EndProcessing() { helper.CleanUp(); } - } #endregion @@ -1020,7 +1011,6 @@ protected override void EndProcessing() [Cmdlet(VerbsCommon.Remove, "WSManInstance", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=141453")] public class RemoveWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable { - #region Parameters /// /// The following is the definition of the input parameter "ApplicationName". @@ -1219,7 +1209,6 @@ protected override void ProcessRecord() { helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } - } IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri); @@ -1233,7 +1222,6 @@ protected override void ProcessRecord() { helper.AssertError(ex.Message, false, computername); } - } finally { @@ -1249,9 +1237,7 @@ protected override void ProcessRecord() if (m_session != null) Dispose(m_session); - } - } #region IDisposable Members @@ -1278,7 +1264,6 @@ protected override void ProcessRecord() } #endregion IDisposable Members - } #endregion @@ -1497,7 +1482,7 @@ public Hashtable ValueSet /// protected override void BeginProcessing() { - helper = new WSManHelper(this ); + helper = new WSManHelper(this); helper.WSManOp = "new"; connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); if (connectionuri != null) @@ -1513,9 +1498,7 @@ protected override void BeginProcessing() { helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } - } - } /// @@ -1560,7 +1543,6 @@ protected override void ProcessRecord() Dispose(m_session); } } - } #region IDisposable Members @@ -1594,7 +1576,6 @@ protected override void ProcessRecord() protected override void EndProcessing() { helper.CleanUp(); - } } diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index ce871b4f612..c5dc9c15e8a 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -123,7 +123,7 @@ internal static void ReleaseSessions() // Somehow the object was a null reference. Ignore the error } - sessionobj=null; + sessionobj = null; } Sessions.SessionObjCache.Clear(); @@ -230,7 +230,6 @@ internal void AddtoDictionary(string key, object value) Sessions.SessionObjCache.Add(key, value); } } - } internal object RemoveFromDictionary(string computer) @@ -338,7 +337,6 @@ internal string ReadFile(string path) string strOut = null; try { - _fs = new FileStream(path, FileMode.Open, FileAccess.Read); // create stream Reader _sr = new StreamReader(_fs); @@ -348,7 +346,6 @@ internal string ReadFile(string path) { ErrorRecord er = new ErrorRecord(e, "ArgumentNullException", ErrorCategory.InvalidArgument, null); cmdletname.ThrowTerminatingError(er); - } catch (UnauthorizedAccessException e) { @@ -374,7 +371,7 @@ internal string ReadFile(string path) { if (_sr != null) { - // _sr.Close(); + // _sr.Close(); _sr.Dispose(); } @@ -390,7 +387,6 @@ internal string ReadFile(string path) internal string ProcessInput(IWSManEx wsman, string filepath, string operation, string root, Hashtable valueset, IWSManResourceLocator resourceUri, IWSManSession sessionObj) { - string resultString = null; // if file path is given @@ -493,7 +489,6 @@ internal string ProcessInput(IWSManEx wsman, string filepath, string operation, node.InnerText = entry.Value.ToString(); } } - } } @@ -554,12 +549,10 @@ internal string CreateConnectionString(Uri ConnUri, int port, string computernam } return ConnectionString; - } internal IWSManResourceLocator InitializeResourceLocator(Hashtable optionset, Hashtable selectorset, string fragment, Uri dialect, IWSManEx wsmanObj, Uri resourceuri) { - string resource = null; if (resourceuri != null) { @@ -694,7 +687,6 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseClientCertificate; } - } IWSManConnectionOptionsEx2 connObject = (IWSManConnectionOptionsEx2)wsmanObject.CreateConnectionOptions(); @@ -707,7 +699,7 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM nwCredential = credential.GetNetworkCredential(); if (string.IsNullOrEmpty(nwCredential.Domain)) { - if ( authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic) ) + if (authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic)) { connObject.UserName = nwCredential.UserName; } @@ -738,7 +730,6 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM if (sessionoption != null) { - if (sessionoption.ProxyAuthentication != 0) { int ProxyAccessflags = 0; @@ -788,7 +779,6 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM { connObject.SetProxy((int)sessionoption.ProxyAccessType, (int)sessionoption.ProxyAuthentication, null, null); } - } if (sessionoption.SkipCACheck) @@ -859,7 +849,6 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM internal void CleanUp() { - if (_sr != null) { _sr.Dispose(); @@ -871,7 +860,6 @@ internal void CleanUp() _fs.Dispose(); _fs = null; } - } internal string GetFilterString(Hashtable seletorset) @@ -993,7 +981,6 @@ internal void CreateWsManConnection(string ParameterSetName, Uri connectionuri, { AssertError(m_wsmanObject.Error, true, computername); } - } } @@ -1122,10 +1109,8 @@ internal static void LoadResourceData() } catch (IOException e) { - throw (e); } - } /// @@ -1154,6 +1139,5 @@ internal static string GetResourceString(string Key) /// /// private static Dictionary ResourceValueCache = new Dictionary(); - } } diff --git a/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs b/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs index 8fbb84e3a77..4a2c757997e 100644 --- a/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs +++ b/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs @@ -17,16 +17,15 @@ using System.Runtime.CompilerServices; [assembly: CLSCompliant(true)] + namespace Microsoft.WSMan.Management { - /// /// Session option class. /// public sealed class SessionOption { - /// /// Property. /// @@ -68,7 +67,6 @@ public bool SkipRevocationCheck { _SkipRevocationCheck = value; } - } private bool _SkipRevocationCheck; diff --git a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs index e7cdc3debdc..a8f79175d4a 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs @@ -272,7 +272,7 @@ private Assembly Resolve(AssemblyLoadContext loadContext, AssemblyName assemblyN // Try loading from GAC if (!TryFindInGAC(assemblyName, out asmFilePath)) { - return null; + return null; } #else return null; diff --git a/src/System.Management.Automation/CoreCLR/CorePsStub.cs b/src/System.Management.Automation/CoreCLR/CorePsStub.cs index b5df89fafc2..47cffe47be2 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsStub.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsStub.cs @@ -276,18 +276,22 @@ internal static Type GetTypeForVarEnum(VarEnum vt) /// 2. There is no Type to represent COM types. __ComObject is a private type, and Object is too /// general. /// - internal static Type GetManagedMarshalType(VarEnum varEnum) { + internal static Type GetManagedMarshalType(VarEnum varEnum) + { Debug.Assert((varEnum & VarEnum.VT_BYREF) == 0); - if (varEnum == VarEnum.VT_CY) { + if (varEnum == VarEnum.VT_CY) + { return typeof(CurrencyWrapper); } - if (IsPrimitiveType(varEnum)) { + if (IsPrimitiveType(varEnum)) + { return _ComToManagedPrimitiveTypes[varEnum]; } - switch (varEnum) { + switch (varEnum) + { case VarEnum.VT_EMPTY: case VarEnum.VT_NULL: case VarEnum.VT_UNKNOWN: @@ -299,7 +303,7 @@ internal static Type GetManagedMarshalType(VarEnum varEnum) { return typeof(ErrorWrapper); default: - throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.CurrentCulture, ParserStrings.UnexpectedVarEnum, varEnum));; + throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.CurrentCulture, ParserStrings.UnexpectedVarEnum, varEnum)); } } @@ -341,12 +345,10 @@ private static Dictionary CreateComToManagedPrimitiveTypes() /// Primitive types are the basic COM types. It includes valuetypes like ints, but also reference types /// like BStrs. It does not include composite types like arrays and user-defined COM types (IUnknown/IDispatch). /// - internal static bool IsPrimitiveType(VarEnum varEnum) { - switch (varEnum) { - - // *** BEGIN GENERATED CODE *** - // generated by function: gen_IsPrimitiveType from: generate_comdispatch.py - + internal static bool IsPrimitiveType(VarEnum varEnum) + { + switch (varEnum) + { case VarEnum.VT_I1: case VarEnum.VT_I2: case VarEnum.VT_I4: @@ -366,8 +368,6 @@ internal static bool IsPrimitiveType(VarEnum varEnum) { case VarEnum.VT_DATE: case VarEnum.VT_BSTR: - // *** END GENERATED CODE *** - return true; } diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index c1aaaf11c92..f179f2133a2 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -684,9 +684,9 @@ public static void Initialize(Collection errors, List moduleP if (!Directory.Exists(systemResourceRoot)) { - configSystemPath = Platform.GetFolderPath(Environment.SpecialFolder.System); - systemResourceRoot = Path.Combine(configSystemPath, "Configuration"); - inboxModulePath = InboxDscResourceModulePath; + configSystemPath = Platform.GetFolderPath(Environment.SpecialFolder.System); + systemResourceRoot = Path.Combine(configSystemPath, "Configuration"); + inboxModulePath = InboxDscResourceModulePath; } var programFilesDirectory = Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles); diff --git a/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs index 21ad20bb5cd..03742dc79ff 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs @@ -64,7 +64,7 @@ internal void Initialize(string[] propertyNames, int screenColumnWidth, DisplayC _propertyLabelsDisplayLength = 0; // reset max // cache the cell lengths for each property - Span propertyNameCellCounts = propertyNames.Length <= OutCommandInner.StackAllocThreshold ? stackalloc int[propertyNames.Length] : new int[propertyNames.Length];; + Span propertyNameCellCounts = propertyNames.Length <= OutCommandInner.StackAllocThreshold ? stackalloc int[propertyNames.Length] : new int[propertyNames.Length]; for (int k = 0; k < propertyNames.Length; k++) { Debug.Assert(propertyNames[k] != null, "propertyNames[k] is null"); diff --git a/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs index 952e716b2a6..53032ac019a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs @@ -258,7 +258,7 @@ private string[] GenerateTableRow(string[] values, ReadOnlySpan alignment, for (int k = 0; k < scArray.Length; k++) { // for the last column, don't pad it with trailing spaces - if (k == scArray.Length-1) + if (k == scArray.Length - 1) { addPadding = false; } @@ -408,7 +408,7 @@ private string GenerateRow(string[] values, ReadOnlySpan alignment, Display for (int k = 0; k < _si.columnInfo.Length; k++) { // don't pad the last column - if (k == _si.columnInfo.Length -1) + if (k == _si.columnInfo.Length - 1) { addPadding = false; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs index 286cc9e14bd..54ae35c7772 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs @@ -17,7 +17,6 @@ namespace Microsoft.PowerShell.Commands /// public class PSPropertyExpressionResult { - /// /// Create a property expression result containing the original object, matching property expression /// and any exception generated during the match process. @@ -323,7 +322,7 @@ private PSPropertyExpressionResult GetValue(PSObject target, bool eatExceptions) CallSite>.Create( PSGetMemberBinder.Get( _stringValue, - classScope: (Type) null, + classScope: (Type)null, @static: false)); } diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs b/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs index 625ba2157d6..d8dca91267b 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs @@ -1,15 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System; +using System.Collections; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Management.Automation.Internal; + +using Microsoft.PowerShell.Commands.Internal.Format; + namespace Microsoft.PowerShell.Commands { - using System; - using System.Collections; - using System.Management.Automation; - using System.Management.Automation.Host; - using System.Management.Automation.Internal; - using Microsoft.PowerShell.Commands.Internal.Format; - /// /// Null sink to absorb pipeline output. /// diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 68ce82fa823..b30fae18a68 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -9,7 +9,7 @@ - + diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodParametersCollection.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodParametersCollection.cs index 1bb13247d32..098303c2118 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodParametersCollection.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodParametersCollection.cs @@ -1,11 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System; +using System.Collections.ObjectModel; + namespace Microsoft.PowerShell.Cmdletization { - using System; - using System.Collections.ObjectModel; - /// /// Collection of method parameters and their arguments /// used to invoke a method in an object model wrapped by diff --git a/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs b/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs index d54bfd85fee..e9de925e3da 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System.Management.Automation; +using System.Text; + // TODO/FIXME: move this to Microsoft.PowerShell.Cim namespace (and move in source depot folder as well) namespace Microsoft.PowerShell.Cmdletization.Cim { - using System.Management.Automation; - using System.Text; - /// /// Translates a into a like-operand for WQL. /// diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs index 228288fc1b2..e6425a51056 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs @@ -1,5 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. + +using System.Xml.Serialization; + #pragma warning disable //------------------------------------------------------------------------------ // @@ -14,10 +17,9 @@ // // This source code was auto-generated by xsd, Version=4.0.30319.17929. // + namespace Microsoft.PowerShell.Cmdletization.Xml { - using System.Xml.Serialization; - /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] @@ -25,7 +27,6 @@ namespace Microsoft.PowerShell.Cmdletization.Xml [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IsNullable = false)] internal partial class PowerShellMetadata { - private ClassMetadata _classField; private EnumMetadataEnum[] _enumsField; @@ -66,7 +67,6 @@ public EnumMetadataEnum[] Enums [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class ClassMetadata { - private string _versionField; private string _defaultNounField; @@ -207,7 +207,6 @@ public string ClassVersion [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class ClassMetadataInstanceCmdlets { - private GetCmdletParameters _getCmdletParametersField; private GetCmdletMetadata _getCmdletField; @@ -264,7 +263,6 @@ public InstanceCmdletMetadata[] Cmdlet [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class GetCmdletParameters { - private PropertyMetadata[] _queryablePropertiesField; private Association[] _queryableAssociationsField; @@ -340,7 +338,6 @@ public string DefaultCmdletParameterSet [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class PropertyMetadata { - private TypeMetadata _typeField; private PropertyQuery[] _itemsField; @@ -420,7 +417,6 @@ public string PropertyName [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class TypeMetadata { - private string _pSTypeField; private string _eTSTypeField; @@ -462,7 +458,6 @@ public string ETSType [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class Association { - private AssociationAssociatedInstance _associatedInstanceField; private string _association1Field; @@ -537,7 +532,6 @@ public string ResultRole [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class AssociationAssociatedInstance { - private TypeMetadata _typeField; private CmdletParameterMetadataForGetCmdletFilteringParameter _cmdletParameterMetadataField; @@ -577,7 +571,6 @@ public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMeta [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataForGetCmdletFilteringParameter : CmdletParameterMetadataForGetCmdletParameter { - private bool _errorOnNoMatchField; private bool _errorOnNoMatchFieldSpecified; @@ -620,7 +613,6 @@ public bool ErrorOnNoMatchSpecified [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataForGetCmdletParameter : CmdletParameterMetadata { - private bool _valueFromPipelineField; private bool _valueFromPipelineFieldSpecified; @@ -717,7 +709,6 @@ public string[] CmdletParameterSets [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadata { - private object _allowEmptyCollectionField; private object _allowEmptyStringField; @@ -971,7 +962,6 @@ public string Position [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataValidateCount { - private string _minField; private string _maxField; @@ -1013,7 +1003,6 @@ public string Max [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataValidateLength { - private string _minField; private string _maxField; @@ -1055,7 +1044,6 @@ public string Max [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataValidateRange { - private string _minField; private string _maxField; @@ -1097,7 +1085,6 @@ public string Max [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class ObsoleteAttributeMetadata { - private string _messageField; /// @@ -1122,7 +1109,6 @@ public string Message [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataForInstanceMethodParameter : CmdletParameterMetadata { - private bool _valueFromPipelineByPropertyNameField; private bool _valueFromPipelineByPropertyNameFieldSpecified; @@ -1164,7 +1150,6 @@ public bool ValueFromPipelineByPropertyNameSpecified [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataForStaticMethodParameter : CmdletParameterMetadata { - private bool _valueFromPipelineField; private bool _valueFromPipelineFieldSpecified; @@ -1240,7 +1225,6 @@ public bool ValueFromPipelineByPropertyNameSpecified [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class QueryOption { - private TypeMetadata _typeField; private CmdletParameterMetadataForGetCmdletParameter _cmdletParameterMetadataField; @@ -1297,7 +1281,6 @@ public string OptionName [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class GetCmdletMetadata { - private CommonCmdletMetadata _cmdletMetadataField; private GetCmdletParameters _getCmdletParametersField; @@ -1337,7 +1320,6 @@ public GetCmdletParameters GetCmdletParameters [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CommonCmdletMetadata { - private ObsoleteAttributeMetadata _obsoleteField; private string _verbField; @@ -1462,7 +1444,6 @@ public string HelpUri [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] public enum ConfirmImpact { - /// None, @@ -1482,7 +1463,6 @@ public enum ConfirmImpact [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class StaticCmdletMetadata { - private StaticCmdletMetadataCmdletMetadata _cmdletMetadataField; private StaticMethodMetadata[] _methodField; @@ -1523,7 +1503,6 @@ public StaticMethodMetadata[] Method [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class StaticCmdletMetadataCmdletMetadata : CommonCmdletMetadata { - private string _defaultCmdletParameterSetField; /// @@ -1548,7 +1527,6 @@ public string DefaultCmdletParameterSet [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class StaticMethodMetadata : CommonMethodMetadata { - private StaticMethodParameterMetadata[] _parametersField; private string _cmdletParameterSetField; @@ -1590,7 +1568,6 @@ public string CmdletParameterSet [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class StaticMethodParameterMetadata : CommonMethodParameterMetadata { - private CmdletParameterMetadataForStaticMethodParameter _cmdletParameterMetadataField; private CmdletOutputMetadata _cmdletOutputMetadataField; @@ -1630,7 +1607,6 @@ public CmdletOutputMetadata CmdletOutputMetadata [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletOutputMetadata { - private object _errorCodeField; private string _pSNameField; @@ -1673,7 +1649,6 @@ public string PSName [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CommonMethodParameterMetadata { - private TypeMetadata _typeField; private string _parameterNameField; @@ -1731,7 +1706,6 @@ public string DefaultValue [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class InstanceMethodParameterMetadata : CommonMethodParameterMetadata { - private CmdletParameterMetadataForInstanceMethodParameter _cmdletParameterMetadataField; private CmdletOutputMetadata _cmdletOutputMetadataField; @@ -1773,7 +1747,6 @@ public CmdletOutputMetadata CmdletOutputMetadata [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CommonMethodMetadata { - private CommonMethodMetadataReturnValue _returnValueField; private string _methodNameField; @@ -1814,7 +1787,6 @@ public string MethodName [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CommonMethodMetadataReturnValue { - private TypeMetadata _typeField; private CmdletOutputMetadata _cmdletOutputMetadataField; @@ -1854,7 +1826,6 @@ public CmdletOutputMetadata CmdletOutputMetadata [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class InstanceMethodMetadata : CommonMethodMetadata { - private InstanceMethodParameterMetadata[] _parametersField; /// @@ -1879,7 +1850,6 @@ public InstanceMethodParameterMetadata[] Parameters [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class InstanceCmdletMetadata { - private CommonCmdletMetadata _cmdletMetadataField; private InstanceMethodMetadata _methodField; @@ -1936,7 +1906,6 @@ public GetCmdletParameters GetCmdletParameters [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class PropertyQuery { - private CmdletParameterMetadataForGetCmdletFilteringParameter _cmdletParameterMetadataField; /// @@ -1960,7 +1929,6 @@ public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMeta [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class WildcardablePropertyQuery : PropertyQuery { - private bool _allowGlobbingField; private bool _allowGlobbingFieldSpecified; @@ -2001,7 +1969,6 @@ public bool AllowGlobbingSpecified [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IncludeInSchema = false)] public enum ItemsChoiceType { - /// ExcludeQuery, @@ -2021,7 +1988,6 @@ public enum ItemsChoiceType [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class ClassMetadataData { - private string _nameField; private string _valueField; @@ -2063,7 +2029,6 @@ public string Value [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class EnumMetadataEnum { - private EnumMetadataEnumValue[] _valueField; private string _enumNameField; @@ -2156,7 +2121,6 @@ public bool BitwiseFlagsSpecified [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class EnumMetadataEnumValue { - private string _nameField; private string _valueField; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs index 69fbe8217e9..1c9a66549ad 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -3,17 +3,16 @@ #if CORECLR +using System; +using System.Collections; +using System.Globalization; +using System.Xml; +using System.Xml.Schema; + #pragma warning disable namespace Microsoft.PowerShell.Cmdletization.Xml { - - using System; - using System.Collections; - using System.Globalization; - using System.Xml; - using System.Xml.Schema; - internal class XmlSerializationReader1 { #region Copy_From_XmlSerializationReader diff --git a/src/System.Management.Automation/engine/CmdletInfo.cs b/src/System.Management.Automation/engine/CmdletInfo.cs index a06c5307a82..e54838822e5 100644 --- a/src/System.Management.Automation/engine/CmdletInfo.cs +++ b/src/System.Management.Automation/engine/CmdletInfo.cs @@ -533,7 +533,8 @@ internal string FullName /// internal override CommandMetadata CommandMetadata { - get { + get + { return _cmdletMetadata ?? (_cmdletMetadata = CommandMetadata.Get(this.Name, this.ImplementingType, Context)); } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 5c6d11c96c4..c771d2c482f 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -6053,7 +6053,7 @@ internal static List CompleteHelpTopics(CompletionContext cont // Add the user scope path first, since it is searched in order. var userHelpRoot = Path.Combine(HelpUtils.GetUserHomeHelpSearchPath(), currentCulture); - if(Directory.Exists(userHelpRoot)) + if (Directory.Exists(userHelpRoot)) { searchPaths.Add(userHelpRoot); } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs index 15647ed3279..50f3e946d3f 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System; + namespace System.Management.Automation { - using System; - /// /// Possible types of CompletionResults. /// diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index 37797460db9..8787a3f1f98 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -180,14 +180,14 @@ internal CommandInfo(string name, CommandInfo other) /// public string Name { get; private set; } = string.Empty; -// Name + // Name /// /// Gets the type of the command. /// public CommandTypes CommandType { get; private set; } = CommandTypes.Application; -// CommandType + // CommandType /// /// Gets the source of the command (shown by default in Get-Command) @@ -938,7 +938,7 @@ internal static PSSyntheticTypeName Create(PSTypeName typename, IList(); members.AddRange(membersTypes); - members.Sort((c1,c2) => string.Compare(c1.Name, c2.Name, StringComparison.OrdinalIgnoreCase)); + members.Sort((c1, c2) => string.Compare(c1.Name, c2.Name, StringComparison.OrdinalIgnoreCase)); return new PSSyntheticTypeName(typeName, typename.Type, members); } diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index 442da89fd3a..f78777c840b 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -2140,7 +2140,7 @@ internal object Invoke(object target, object[] arguments) return ctor.Invoke(arguments); } - var methodInfo = (MethodInfo) method; + var methodInfo = (MethodInfo)method; if (methodInfo.ReturnType.IsByRefLike) { throw new MethodException( @@ -3575,12 +3575,11 @@ private T GetDotNetPropertyImpl(object obj, string propertyName, MemberNamePr : typeTable[propertyName]; switch (entry) { - case null: return null; + case null: + return null; case PropertyCacheEntry cacheEntry when lookingForProperties: - { var isHidden = cacheEntry.member.GetCustomAttributes(typeof(HiddenAttribute), false).Any(); return new PSProperty(cacheEntry.member.Name, this, obj, cacheEntry) { IsHidden = isHidden } as T; - } case ParameterizedPropertyCacheEntry paramCacheEntry when lookingForParameterizedProperties: // TODO: check for HiddenAttribute diff --git a/src/System.Management.Automation/engine/DscResourceInfo.cs b/src/System.Management.Automation/engine/DscResourceInfo.cs index 1a874c755fb..a94cef1eb1b 100644 --- a/src/System.Management.Automation/engine/DscResourceInfo.cs +++ b/src/System.Management.Automation/engine/DscResourceInfo.cs @@ -118,7 +118,7 @@ public void UpdateProperties(IList properties) /// public string HelpFile { get; internal set; } = string.Empty; -// HelpFile + // HelpFile } /// diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index 7e9a007e10e..4c704bccb13 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -2289,8 +2289,10 @@ internal PSEventArgs(string computerName, Guid runspaceId, int eventIdentifier, /// /// Gets the time and date that this event was generated. /// - public DateTime TimeGenerated { get; internal set; -// internal setter using during deserialization + public DateTime TimeGenerated + { + // internal setter using during deserialization + get; internal set; } /// diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 33ac31dce58..2f7d0a7a448 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -715,9 +715,10 @@ internal CommandDiscovery CommandDiscovery /// /// Interface that should be used for interaction with host. /// - internal InternalHost EngineHostInterface { get; private set; - + internal InternalHost EngineHostInterface + { // set not provided: it's not meaningful to change the host post-construction. + get; private set; } /// diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs b/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs index 2c9763dcdc7..35a404b675e 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs @@ -30,6 +30,14 @@ public class EnableDisableExperimentalFeatureCommandBase : PSCmdlet /// [Parameter] public ConfigScope Scope { get; set; } = ConfigScope.CurrentUser; + + /// + /// EndProcessing method. + /// + protected override void EndProcessing() + { + WriteWarning(ExperimentalFeatureStrings.ExperimentalFeaturePending); + } } /// @@ -87,8 +95,6 @@ internal static void UpdateConfig(PSCmdlet cmdlet, string[] name, ConfigScope sc cmdlet.WriteError(new ErrorRecord(new ItemNotFoundException(errMsg), "ItemNotFoundException", ErrorCategory.ObjectNotFound, name)); return; } - - cmdlet.WriteWarning(ExperimentalFeatureStrings.ExperimentalFeaturePending); } } diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 443720eb4f3..5c47fe73f3a 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -317,7 +317,7 @@ public ExperimentalAttribute(string experimentName, ExperimentAction experimentA /// /// Initialize an instance that represents the none-value. /// - private ExperimentalAttribute() {} + private ExperimentalAttribute() { } /// /// An instance that represents the none-value. diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 832134039e1..58bd1ab30a5 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -571,7 +571,6 @@ private void OutputResultsHelper(IEnumerable results) Telemetry.Internal.TelemetryAPI.ReportGetCommandFailed(Name, _timer.ElapsedMilliseconds); } #endif - } /// diff --git a/src/System.Management.Automation/engine/GetEvent_Types_Ps1Xml.cs b/src/System.Management.Automation/engine/GetEvent_Types_Ps1Xml.cs index 16d38a9d1cb..06d8d12be45 100644 --- a/src/System.Management.Automation/engine/GetEvent_Types_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/GetEvent_Types_Ps1Xml.cs @@ -9,6 +9,7 @@ // the code is regenerated. // //------------------------------------------------------------------------------ + using System.Collections.Generic; using System.Management.Automation; using System.Reflection; @@ -39,7 +40,6 @@ static ScriptBlock GetScriptBlock(string s) public static IEnumerable Get() { - var td1 = new TypeData(@"System.Diagnostics.Eventing.Reader.EventLogConfiguration", true); td1.DefaultDisplayPropertySet = new PropertySetData(new[] { "LogName", "MaximumSizeInBytes", "RecordCount", "LogMode" }) { Name = "DefaultDisplayPropertySet" }; diff --git a/src/System.Management.Automation/engine/InformationRecord.cs b/src/System.Management.Automation/engine/InformationRecord.cs index 712b2c3acb4..3eb92db371e 100644 --- a/src/System.Management.Automation/engine/InformationRecord.cs +++ b/src/System.Management.Automation/engine/InformationRecord.cs @@ -138,7 +138,7 @@ public uint ProcessId { if (!this._processId.HasValue) { - this._processId = (uint) System.Diagnostics.Process.GetCurrentProcess().Id; + this._processId = (uint)System.Diagnostics.Process.GetCurrentProcess().Id; } return this._processId.Value; diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index 1492fe96091..1a709ce102c 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -42,7 +42,7 @@ public object GetValue(PSObject inputObject, string propertyName) _getValueDynamicSite = CallSite>.Create( PSGetMemberBinder.Get( propertyName, - classScope: (Type) null, + classScope: (Type)null, @static: false)); } diff --git a/src/System.Management.Automation/engine/InvocationInfo.cs b/src/System.Management.Automation/engine/InvocationInfo.cs index 45fcc921ac2..a610f2829a4 100644 --- a/src/System.Management.Automation/engine/InvocationInfo.cs +++ b/src/System.Management.Automation/engine/InvocationInfo.cs @@ -199,7 +199,8 @@ internal InvocationInfo(PSObject psObject) /// public Dictionary BoundParameters { - get { + get + { return _boundParameters ?? (_boundParameters = new Dictionary(StringComparer.OrdinalIgnoreCase)); } diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index ac7da934a9e..2d09bbeed9c 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -25,6 +25,7 @@ // // Now define the set of commands for manipulating modules. // + namespace Microsoft.PowerShell.Commands { #region ModuleCmdletBase class @@ -685,8 +686,8 @@ private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, Module module = LoadUsingExtensions( parentModule, moduleSpecification.Name, - rootedPath, // fileBaseName - /*extension*/null, + fileBaseName: rootedPath, + extension: null, moduleBase, // not using base from tempModuleInfoFromVerification as we are looking under moduleBase directory prefix, ss, diff --git a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs index 004bfc81bc6..b54549f38ba 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs @@ -607,7 +607,7 @@ internal struct CommandScore public CommandScore(CommandInfo command, int score) { Command = command; - Score = score; + Score = score; } public CommandInfo Command; diff --git a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs index 05330b7f9dc..24bfe88b8bc 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs @@ -18,6 +18,7 @@ // // Now define the set of commands for manipulating modules. // + namespace Microsoft.PowerShell.Commands { #region New-ModuleManifest @@ -1260,5 +1261,5 @@ private void ValidateUriParameterValue(Uri uri, string parameterName) } } -#endregion + #endregion } diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index 081e0d46c69..32a030c9666 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -83,7 +83,7 @@ public bool IsPresent /// /// The SwitchParameter object to convert to bool. /// The corresponding boolean value. - public static implicit operator bool (SwitchParameter switchParameter) + public static implicit operator bool(SwitchParameter switchParameter) { return switchParameter.IsPresent; } @@ -719,11 +719,11 @@ public Collection InvokeScript( { _context.EngineSessionState = sessionState.Internal; return InvokeScript( - sb:scriptBlock, - useNewScope:false, - writeToPipeline:PipelineResultTypes.None, - input:null, - args:args); + sb: scriptBlock, + useNewScope: false, + writeToPipeline: PipelineResultTypes.None, + input: null, + args: args); } finally { diff --git a/src/System.Management.Automation/engine/MshMemberInfo.cs b/src/System.Management.Automation/engine/MshMemberInfo.cs index d6dfd19b681..d7d78d802de 100644 --- a/src/System.Management.Automation/engine/MshMemberInfo.cs +++ b/src/System.Management.Automation/engine/MshMemberInfo.cs @@ -438,7 +438,7 @@ public PSAliasProperty(string name, string referencedMemberName, Type conversion /// A new PSMemberInfo that is a copy of this PSMemberInfo. public override PSMemberInfo Copy() { - PSAliasProperty alias = new PSAliasProperty(name, ReferencedMemberName) {ConversionType = ConversionType}; + PSAliasProperty alias = new PSAliasProperty(name, ReferencedMemberName) { ConversionType = ConversionType }; CloneBaseProperties(alias); return alias; } @@ -1757,7 +1757,7 @@ internal PSScriptProperty(string name, string getterScript, string setterScript, /// A new PSMemberInfo that is a copy of this PSMemberInfo. public override PSMemberInfo Copy() { - var property = new PSScriptProperty(name, this.GetterScript, this.SetterScript) {_shouldCloneOnAccess = _shouldCloneOnAccess}; + var property = new PSScriptProperty(name, this.GetterScript, this.SetterScript) { _shouldCloneOnAccess = _shouldCloneOnAccess }; CloneBaseProperties(property); return property; } @@ -1824,7 +1824,7 @@ internal object InvokeSetter(object scriptThis, object value) dollarUnder: AutomationNull.Value, input: AutomationNull.Value, scriptThis: scriptThis, - args: new[] {value}); + args: new[] { value }); return value; } catch (RuntimeException e) @@ -1985,7 +1985,7 @@ public override bool Equals(object obj) return false; } - return Equals((PSMethodInvocationConstraints) obj); + return Equals((PSMethodInvocationConstraints)obj); } public override int GetHashCode() @@ -2241,7 +2241,7 @@ public override object Invoke(params object[] arguments) if (_codeReferenceMethodInformation == null) { - _codeReferenceMethodInformation = DotNetAdapter.GetMethodInformationArray(new[] {CodeReference}); + _codeReferenceMethodInformation = DotNetAdapter.GetMethodInformationArray(new[] { CodeReference }); } Adapter.GetBestMethodAndArguments(CodeReference.Name, _codeReferenceMethodInformation, newArguments, out object[] convertedArguments); @@ -2420,7 +2420,7 @@ public override Collection OverloadDefinitions { get { - Collection retValue = new Collection {this.ToString()}; + Collection retValue = new Collection { this.ToString() }; return retValue; } } @@ -2431,7 +2431,7 @@ public override Collection OverloadDefinitions /// A new PSMemberInfo that is a copy of this PSMemberInfo. public override PSMemberInfo Copy() { - var method = new PSScriptMethod(this.name, _script) {_shouldCloneOnAccess = _shouldCloneOnAccess}; + var method = new PSScriptMethod(this.name, _script) { _shouldCloneOnAccess = _shouldCloneOnAccess }; CloneBaseProperties(method); return method; } @@ -2693,13 +2693,13 @@ private static Func var types = new Type[methods.Length]; for (int i = 0; i < methods.Length; i++) { - types[i] = GetMethodGroupType((MethodInfo) methods[i].method); + types[i] = GetMethodGroupType((MethodInfo)methods[i].method); } var methodGroupType = CreateMethodGroup(types, 0, types.Length); Type psMethodType = typeof(PSMethod<>).MakeGenericType(methodGroupType); var delegateType = typeof(Func); - return (Func) Delegate.CreateDelegate(delegateType, + return (Func)Delegate.CreateDelegate(delegateType, psMethodType.GetMethod("Create", BindingFlags.NonPublic | BindingFlags.Static)); } @@ -4780,7 +4780,7 @@ public override T this[string name] foreach (CollectionEntry collection in Collections) { Diagnostics.Assert(delegateOwner != null, "all integrating collections with non empty collections have an associated PSObject"); - T memberAsT = collection.GetMember((PSObject) delegateOwner, name); + T memberAsT = collection.GetMember((PSObject)delegateOwner, name); if (memberAsT != null) { return collection.CloneOrReplicateObject(delegateOwner, memberAsT); @@ -4834,7 +4834,7 @@ private PSMemberInfoInternalCollection GetIntegratedMembers(MshMemberMatchOpt delegateOwner = PSObject.AsPSObject(delegateOwner); foreach (CollectionEntry collection in Collections) { - PSMemberInfoInternalCollection members = collection.GetMembers((PSObject) delegateOwner); + PSMemberInfoInternalCollection members = collection.GetMembers((PSObject)delegateOwner); foreach (T member in members) { PSMemberInfo previousMember = returnValue[member.Name]; @@ -5066,7 +5066,7 @@ S IEnumerator.Current } } - object IEnumerator.Current => ((IEnumerator) this).Current; + object IEnumerator.Current => ((IEnumerator)this).Current; void IEnumerator.Reset() { diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index d150dd956d3..4bdaae94a8b 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -110,15 +110,15 @@ internal void BindParameters(Collection parameters) ArrayLiteralAst arrayLiteralAst = null; switch (parameter?.ArgumentAst) { - case StringConstantExpressionAst sce: - usedQuotes = sce.StringConstantType != StringConstantType.BareWord; - break; - case ExpandableStringExpressionAst ese: - usedQuotes = ese.StringConstantType != StringConstantType.BareWord; - break; - case ArrayLiteralAst ala: - arrayLiteralAst = ala; - break; + case StringConstantExpressionAst sce: + usedQuotes = sce.StringConstantType != StringConstantType.BareWord; + break; + case ExpandableStringExpressionAst ese: + usedQuotes = ese.StringConstantType != StringConstantType.BareWord; + break; + case ArrayLiteralAst ala: + arrayLiteralAst = ala; + break; } appendOneNativeArgument(Context, argValue, @@ -220,7 +220,7 @@ private void appendOneNativeArgument(ExecutionContext context, object obj, Array // need to escape all trailing backslashes so the native command receives it correctly // according to http://www.daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULESDOC _arguments.Append(arg); - for (int i = arg.Length-1; i >= 0 && arg[i] == '\\'; i--) + for (int i = arg.Length - 1; i >= 0 && arg[i] == '\\'; i--) { _arguments.Append('\\'); } @@ -383,6 +383,6 @@ private static string GetEnumerableArgSeparator(ArrayLiteralAst arrayLiteralAst, /// The native command to bind to. /// private NativeCommand _nativeCommand; -#endregion private members + #endregion private members } } diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 01327a1af1a..8883cb8c2db 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -557,7 +557,6 @@ private void InitNativeProcess() catch (Win32Exception e) { exceptionToRethrow = e; - } catch (PipelineStoppedException) { diff --git a/src/System.Management.Automation/engine/PSConfiguration.cs b/src/System.Management.Automation/engine/PSConfiguration.cs index 630bda9333f..fea5ed578d5 100644 --- a/src/System.Management.Automation/engine/PSConfiguration.cs +++ b/src/System.Management.Automation/engine/PSConfiguration.cs @@ -475,7 +475,7 @@ private void UpdateValueInFile(ConfigScope scope, string key, T value, bool a if (isReadSuccess) { // Read the stream into a root JObject for manipulation - jsonObject = (JObject) JToken.ReadFrom(jsonReader); + jsonObject = (JObject)JToken.ReadFrom(jsonReader); JProperty propertyToModify = jsonObject.Property(key); if (propertyToModify == null) diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 2910509b868..0f51e913af7 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -516,7 +516,7 @@ public SemanticVersion(int major, int minor, int patch) /// /// If or is less than 0. /// - public SemanticVersion(int major, int minor) : this(major, minor, 0) {} + public SemanticVersion(int major, int minor) : this(major, minor, 0) { } /// /// Construct a SemanticVersion. @@ -525,7 +525,7 @@ public SemanticVersion(int major, int minor) : this(major, minor, 0) {} /// /// If is less than 0. /// - public SemanticVersion(int major) : this(major, 0, 0) {} + public SemanticVersion(int major) : this(major, 0, 0) { } /// /// Construct a from a , @@ -671,9 +671,9 @@ private static bool TryParseVersion(string version, ref VersionResult result) } string versionSansLabel = null; - var major=0; - var minor=0; - var patch=0; + var major = 0; + var minor = 0; + var patch = 0; string preLabel = null; string buildLabel = null; @@ -688,14 +688,14 @@ private static bool TryParseVersion(string version, ref VersionResult result) { // No buildLabel: buildLabel == null // Format is 'major.minor.patch-PreReleaseLabel' - preLabel = version.Substring(dashIndex+1); + preLabel = version.Substring(dashIndex + 1); versionSansLabel = version.Substring(0, dashIndex); } else { // No PreReleaseLabel: preLabel == null // Format is 'major.minor.patch+BuildLabel' - buildLabel = version.Substring(plusIndex+1); + buildLabel = version.Substring(plusIndex + 1); versionSansLabel = version.Substring(0, plusIndex); dashIndex = -1; } @@ -713,13 +713,13 @@ private static bool TryParseVersion(string version, ref VersionResult result) else { // Format is 'major.minor.patch-PreReleaseLabel+BuildLabel' - preLabel = version.Substring(dashIndex+1, plusIndex-dashIndex-1); - buildLabel = version.Substring(plusIndex+1); + preLabel = version.Substring(dashIndex + 1, plusIndex - dashIndex - 1); + buildLabel = version.Substring(plusIndex + 1); versionSansLabel = version.Substring(0, dashIndex); } } - if ((dashIndex != -1 && string.IsNullOrEmpty(preLabel)) || + if ((dashIndex != -1 && string.IsNullOrEmpty(preLabel)) || (plusIndex != -1 && string.IsNullOrEmpty(buildLabel)) || string.IsNullOrEmpty(versionSansLabel)) { diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index e25d6df5063..b294f6db607 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -777,7 +777,8 @@ private void ValidateNullOrEmptyArgument( // because a value-type value cannot be null. if (!isEmpty && !isElementValueType) { - do { + do + { object element = ParserOps.Current(null, ienum); ValidateNullOrEmptyArgument( parameter, diff --git a/src/System.Management.Automation/engine/ProcessCodeMethods.cs b/src/System.Management.Automation/engine/ProcessCodeMethods.cs index 9d8e92a0d3f..298bd0d1f1e 100644 --- a/src/System.Management.Automation/engine/ProcessCodeMethods.cs +++ b/src/System.Management.Automation/engine/ProcessCodeMethods.cs @@ -1,11 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. + using System; using System.Diagnostics; using System.Management.Automation; using System.Runtime.InteropServices; -namespace Microsoft.PowerShell { +namespace Microsoft.PowerShell +{ /// /// Helper functions for process info. /// @@ -86,5 +88,5 @@ static extern int NtQueryInformationProcess( out int returnLength); #endif - } + } } diff --git a/src/System.Management.Automation/engine/SecurityManagerBase.cs b/src/System.Management.Automation/engine/SecurityManagerBase.cs index 57dd32a3caf..18f358018a0 100644 --- a/src/System.Management.Automation/engine/SecurityManagerBase.cs +++ b/src/System.Management.Automation/engine/SecurityManagerBase.cs @@ -86,9 +86,9 @@ internal void ShouldRunInternal(CommandInfo commandInfo, #if DEBUG // If we are debugging, let the unit tests swap the file from beneath us - if(commandInfo.CommandType == CommandTypes.ExternalScript) + if (commandInfo.CommandType == CommandTypes.ExternalScript) { - while(Environment.GetEnvironmentVariable("PSCommandDiscoveryPreDelay") != null) { System.Threading.Thread.Sleep(100); } + while (Environment.GetEnvironmentVariable("PSCommandDiscoveryPreDelay") != null) { System.Threading.Thread.Sleep(100); } } #endif @@ -105,9 +105,9 @@ internal void ShouldRunInternal(CommandInfo commandInfo, #if DEBUG // If we are debugging, let the unit tests swap the file from beneath us - if(commandInfo.CommandType == CommandTypes.ExternalScript) + if (commandInfo.CommandType == CommandTypes.ExternalScript) { - while(Environment.GetEnvironmentVariable("PSCommandDiscoveryPostDelay") != null) { System.Threading.Thread.Sleep(100); } + while (Environment.GetEnvironmentVariable("PSCommandDiscoveryPostDelay") != null) { System.Threading.Thread.Sleep(100); } } #endif } diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index 546965c83cf..ac650368c74 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -1332,7 +1332,7 @@ internal void GetChildItems( bool isFileOrDirectoryPresent = false; - if(context.DynamicParameters is Microsoft.PowerShell.Commands.GetChildDynamicParameters dynParam) + if (context.DynamicParameters is Microsoft.PowerShell.Commands.GetChildDynamicParameters dynParam) { isFileOrDirectoryPresent = dynParam.File.IsPresent || dynParam.Directory.IsPresent; } @@ -1624,17 +1624,17 @@ private bool IsPathContainer( string path, CmdletProviderContext context) { - bool itemContainer = false; - try - { - itemContainer = IsItemContainer(providerInstance, path, context); - } - catch (UnauthorizedAccessException accessException) - { - context.WriteError(new ErrorRecord(accessException, "GetItemUnauthorizedAccessError", ErrorCategory.PermissionDenied, path)); - } - catch (ProviderInvocationException accessException) - { + bool itemContainer = false; + try + { + itemContainer = IsItemContainer(providerInstance, path, context); + } + catch (UnauthorizedAccessException accessException) + { + context.WriteError(new ErrorRecord(accessException, "GetItemUnauthorizedAccessError", ErrorCategory.PermissionDenied, path)); + } + catch (ProviderInvocationException accessException) + { // if providerinvocationexception is wrapping access denied error, it is ok to not terminate the pipeline if (accessException.InnerException != null && accessException.InnerException.GetType().Equals(typeof(System.UnauthorizedAccessException))) @@ -1645,10 +1645,9 @@ private bool IsPathContainer( { throw; } - } - - return itemContainer; + } + return itemContainer; } /// @@ -3428,7 +3427,7 @@ internal void NewItem( else { // To be compatible with Linux OS. Which will be either '/' or '\' depends on the OS type. - char[] charsToTrim = {' ', Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar}; + char[] charsToTrim = { ' ', Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar }; resolvePath = path.TrimEnd(charsToTrim); } diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index d807885caff..c77e80dea21 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -4531,6 +4531,5 @@ internal void Update( } #endregion internal methods - } } diff --git a/src/System.Management.Automation/engine/TypesV3_Ps1Xml.cs b/src/System.Management.Automation/engine/TypesV3_Ps1Xml.cs index 347ede9d8e6..071c4e17919 100644 --- a/src/System.Management.Automation/engine/TypesV3_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/TypesV3_Ps1Xml.cs @@ -8,6 +8,7 @@ // the code is regenerated. // //------------------------------------------------------------------------------ + using System.Collections.Generic; using System.Management.Automation; using System.Reflection; @@ -37,7 +38,6 @@ static ScriptBlock GetScriptBlock(string s) public static IEnumerable Get() { - var td1 = new TypeData(@"System.Security.Cryptography.X509Certificates.X509Certificate2", true); td1.Members.Add("EnhancedKeyUsageList", new ScriptPropertyData(@"EnhancedKeyUsageList", GetScriptBlock(@",(new-object Microsoft.Powershell.Commands.EnhancedKeyUsageProperty -argumentlist $this).EnhancedKeyUsageList;"), null)); @@ -107,7 +107,7 @@ public static IEnumerable Get() new CodePropertyData("SerializedInvocationInfo", GetMethodInfo(typeof(Microsoft.PowerShell.DeserializingTypeConverter), "GetInvocationInfo"), null) { IsHidden = true }); td14.SerializationMethod = "SpecificProperties"; td14.SerializationDepth = 2; - td14.PropertySerializationSet = + td14.PropertySerializationSet = new PropertySetData(new[] { "Breakpoints", "ResumeAction", "SerializedInvocationInfo" }) { Name = "PropertySerializationSet" }; yield return td14; diff --git a/src/System.Management.Automation/engine/Types_Ps1Xml.cs b/src/System.Management.Automation/engine/Types_Ps1Xml.cs index 5b28c7bc5eb..3bebaed7a32 100644 --- a/src/System.Management.Automation/engine/Types_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/Types_Ps1Xml.cs @@ -986,7 +986,7 @@ public static IEnumerable Get() new ScriptPropertyData(@"State", GetScriptBlock(@"$this.JobStateInfo.State.ToString()"), null)); td108.SerializationMethod = "SpecificProperties"; td108.SerializationDepth = 2; - td108.PropertySerializationSet = + td108.PropertySerializationSet = new PropertySetData(new[] { "HasMoreData", "StatusMessage", "Location", "Command", "JobStateInfo", "InstanceId", "Id", "Name", "State", "ChildJobs", "PSJobTypeName", "PSBeginTime", "PSEndTime" }) { Name = "PropertySerializationSet" }; yield return td108; @@ -1013,7 +1013,7 @@ public static IEnumerable Get() var td114 = new TypeData(@"System.Globalization.CultureInfo", true); td114.SerializationMethod = "SpecificProperties"; td114.SerializationDepth = 1; - td114.PropertySerializationSet = + td114.PropertySerializationSet = new PropertySetData(new[] { "LCID", "Name", "DisplayName", "IetfLanguageTag", "ThreeLetterISOLanguageName", "ThreeLetterWindowsLanguageName", "TwoLetterISOLanguageName" }) { Name = "PropertySerializationSet" }; yield return td114; @@ -1056,7 +1056,7 @@ public static IEnumerable Get() var td124 = new TypeData(@"System.Security.Cryptography.X509Certificates.X509Certificate2", true); td124.SerializationMethod = "SpecificProperties"; td124.SerializationDepth = 1; - td124.PropertySerializationSet = + td124.PropertySerializationSet = new PropertySetData(new[] { "RawData" }) { Name = "PropertySerializationSet" }; yield return td124; @@ -1067,7 +1067,7 @@ public static IEnumerable Get() var td126 = new TypeData(@"System.Security.Cryptography.X509Certificates.X500DistinguishedName", true); td126.SerializationMethod = "SpecificProperties"; td126.SerializationDepth = 1; - td126.PropertySerializationSet = + td126.PropertySerializationSet = new PropertySetData(new[] { "RawData" }) { Name = "PropertySerializationSet" }; yield return td126; @@ -1102,7 +1102,7 @@ public static IEnumerable Get() var td134 = new TypeData(@"System.Management.Automation.ParameterMetadata", true); td134.SerializationMethod = "SpecificProperties"; - td134.PropertySerializationSet = + td134.PropertySerializationSet = new PropertySetData(new[] { "Name", "ParameterType", "Aliases", "IsDynamic", "SwitchParameter" }) { Name = "PropertySerializationSet" }; yield return td134; @@ -1127,7 +1127,7 @@ public static IEnumerable Get() td136.Members.Add("Flags", new CodePropertyData("Flags", GetMethodInfo(typeof(Microsoft.PowerShell.DeserializingTypeConverter), "GetParameterSetMetadataFlags"), null) { IsHidden = true }); td136.SerializationMethod = "SpecificProperties"; - td136.PropertySerializationSet = + td136.PropertySerializationSet = new PropertySetData(new[] { "Position", "Flags", "HelpMessage" }) { Name = "PropertySerializationSet" }; yield return td136; diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index ed3e737a63e..808596e6f79 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -232,13 +232,13 @@ internal static BigInteger ParseBinary(ReadOnlySpan digits, bool unsigned) // circumstance was it faster or more effective than this unrolled version. outputBytes[outputByteIndex--] = (byte)( - ( (digits[byteWalker - 7] << 7) + ((digits[byteWalker - 7] << 7) | (digits[byteWalker - 6] << 6) | (digits[byteWalker - 5] << 5) | (digits[byteWalker - 4] << 4) ) | ( - ( (digits[byteWalker - 3] << 3) + ((digits[byteWalker - 3] << 3) | (digits[byteWalker - 2] << 2) | (digits[byteWalker - 1] << 1) | (digits[byteWalker]) @@ -762,17 +762,33 @@ internal static bool IsValidPSEditionValue(string editionValue) PolicyBase result = null; switch (typeof(T).Name) { - case nameof(ScriptExecution): result = policies.ScriptExecution; break; - case nameof(ScriptBlockLogging): result = policies.ScriptBlockLogging; break; - case nameof(ModuleLogging): result = policies.ModuleLogging; break; - case nameof(ProtectedEventLogging): result = policies.ProtectedEventLogging; break; - case nameof(Transcription): result = policies.Transcription; break; - case nameof(UpdatableHelp): result = policies.UpdatableHelp; break; - case nameof(ConsoleSessionConfiguration): result = policies.ConsoleSessionConfiguration; break; - default: Diagnostics.Assert(false, "Should be unreachable code. Update this switch block when new PowerShell policy types are added."); break; + case nameof(ScriptExecution): + result = policies.ScriptExecution; + break; + case nameof(ScriptBlockLogging): + result = policies.ScriptBlockLogging; + break; + case nameof(ModuleLogging): + result = policies.ModuleLogging; + break; + case nameof(ProtectedEventLogging): + result = policies.ProtectedEventLogging; + break; + case nameof(Transcription): + result = policies.Transcription; + break; + case nameof(UpdatableHelp): + result = policies.UpdatableHelp; + break; + case nameof(ConsoleSessionConfiguration): + result = policies.ConsoleSessionConfiguration; + break; + default: + Diagnostics.Assert(false, "Should be unreachable code. Update this switch block when new PowerShell policy types are added."); + break; } - if (result != null) { return (T) result; } + if (result != null) { return (T)result; } } } @@ -889,7 +905,7 @@ internal static bool IsValidPSEditionValue(string editionValue) } // If no property is set, then we consider this policy as undefined - return isAnyPropertySet ? (T) tInstance : null; + return isAnyPropertySet ? (T)tInstance : null; } } @@ -917,7 +933,7 @@ internal static bool IsValidPSEditionValue(string editionValue) } } - if (policy != null) { return (T) policy; } + if (policy != null) { return (T)policy; } } return null; @@ -1956,8 +1972,8 @@ public static class InternalTestHooks internal static bool TestStopComputer; internal static bool TestWaitStopComputer; internal static bool TestRenameComputer; - internal static int TestStopComputerResults; - internal static int TestRenameComputerResults; + internal static int TestStopComputerResults; + internal static int TestRenameComputerResults; // It's useful to test that we don't depend on the ScriptBlock and AST objects and can use a re-parsed version. internal static bool IgnoreScriptBlockCache; diff --git a/src/System.Management.Automation/engine/debugger/Breakpoint.cs b/src/System.Management.Automation/engine/debugger/Breakpoint.cs index f7372a27520..a09f9300387 100644 --- a/src/System.Management.Automation/engine/debugger/Breakpoint.cs +++ b/src/System.Management.Automation/engine/debugger/Breakpoint.cs @@ -64,7 +64,7 @@ internal bool IsScriptBreakpoint /// protected Breakpoint(string script) : this(script, null) - {} + { } /// /// Creates a new instance of a @@ -83,7 +83,7 @@ protected Breakpoint(string script, ScriptBlock action) /// protected Breakpoint(string script, int id) : this(script, null, id) - {} + { } /// /// Creates a new instance of a @@ -161,8 +161,8 @@ public class CommandBreakpoint : Breakpoint /// public CommandBreakpoint(string script, WildcardPattern command, string commandString) : this(script, command, commandString, null) - {} - + { } + /// /// Creates a new instance of a /// @@ -178,7 +178,7 @@ public CommandBreakpoint(string script, WildcardPattern command, string commandS /// public CommandBreakpoint(string script, WildcardPattern command, string commandString, int id) : this(script, command, commandString, null, id) - {} + { } /// /// Creates a new instance of a @@ -284,7 +284,7 @@ public class VariableBreakpoint : Breakpoint /// public VariableBreakpoint(string script, string variable, VariableAccessMode accessMode) : this(script, variable, accessMode, null) - {} + { } /// /// Creates a new instance of a . @@ -301,7 +301,7 @@ public VariableBreakpoint(string script, string variable, VariableAccessMode acc /// public VariableBreakpoint(string script, string variable, VariableAccessMode accessMode, int id) : this(script, variable, accessMode, null, id) - {} + { } /// /// Creates a new instance of a . @@ -366,7 +366,7 @@ public class LineBreakpoint : Breakpoint /// public LineBreakpoint(string script, int line) : this(script, line, null) - {} + { } /// /// Creates a new instance of a @@ -385,7 +385,7 @@ public LineBreakpoint(string script, int line, ScriptBlock action) /// public LineBreakpoint(string script, int line, int column) : this(script, line, column, null) - {} + { } /// /// Creates a new instance of a @@ -404,7 +404,7 @@ public LineBreakpoint(string script, int line, int column, ScriptBlock action) /// public LineBreakpoint(string script, int line, int column, int id) : this(script, line, column, null, id) - {} + { } /// /// Creates a new instance of a diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 1d2c1624d0f..26401c815a3 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -2680,7 +2680,7 @@ internal static void SetDebugJobAsync(IJobDebugger debuggableJob, bool isAsync) internal override void DebugRunspace(Runspace runspace) { - DebugRunspace(runspace, disableBreakAll:false); + DebugRunspace(runspace, disableBreakAll: false); } /// @@ -4028,7 +4028,7 @@ public override void SetBreakpoints(IEnumerable breakpoints) /// Get a breakpoint by id, primarily for Enable/Disable/Remove-PSBreakpoint cmdlets. /// /// Id of the breakpoint you want. - public override Breakpoint GetBreakpoint(int id) => + public override Breakpoint GetBreakpoint(int id) => _wrappedDebugger.GetBreakpoint(id); /// diff --git a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs index d7979a3dd59..82c35951f4c 100644 --- a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs @@ -13,7 +13,6 @@ namespace System.Management.Automation.Host public sealed class ChoiceDescription { - #region DO NOT REMOVE OR RENAME THESE FIELDS - it will break remoting compatibility with Windows PowerShell compatibility with Windows PowerShell private readonly string label = null; diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index 6b861728716..f4f1ee4fd13 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -684,12 +684,15 @@ public abstract InitialSessionState InitialSessionState /// Get unique id for this instance of runspace. It is primarily used /// for logging purposes. /// - public Guid InstanceId { get; + public Guid InstanceId + { + get; // This id is also used to identify proxy and remote runspace objects. // We need to set this when reconstructing a remote runspace to connect // to an existing remote runspace. - internal set; } = Guid.NewGuid(); + internal set; + } = Guid.NewGuid(); /// /// Gets execution context. diff --git a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs index f09376c488a..ecf72c456eb 100644 --- a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs +++ b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; + namespace System.Management.Automation { - using System; - using System.Collections.ObjectModel; - using System.Collections.Generic; - using System.Collections; - /// /// PSListModifier is a simple helper class created by the update-list cmdlet. /// The update-list cmdlet will either return an instance of this class, or diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 7924902f0cf..e867bb8449c 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -399,7 +399,7 @@ private sealed class TranscribeOnlyCookie : IDisposable private bool _disposed = false; public TranscribeOnlyCookie(PSHostUserInterface ui) { - _ui=ui; + _ui = ui; Interlocked.Increment(ref _ui._transcribeOnlyCount); } @@ -725,12 +725,12 @@ private void FlushPendingOutput() throw new ArgumentException(errorMessage); } - if(!Directory.Exists(baseDirectory)) + if (!Directory.Exists(baseDirectory)) { Directory.CreateDirectory(baseDirectory); } - if(!File.Exists(transcript.Path)) + if (!File.Exists(transcript.Path)) { File.Create(transcript.Path).Dispose(); } diff --git a/src/System.Management.Automation/engine/interpreter/AddInstruction.cs b/src/System.Management.Automation/engine/interpreter/AddInstruction.cs index 5af328509d1..d4c648855aa 100644 --- a/src/System.Management.Automation/engine/interpreter/AddInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/AddInstruction.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation.Interpreter { internal abstract class AddInstruction : Instruction { - private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_int16, s_int32, s_int64, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } @@ -152,7 +152,7 @@ public override string ToString() internal abstract class AddOvfInstruction : Instruction { - private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_int16, s_int32, s_int64, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } diff --git a/src/System.Management.Automation/engine/interpreter/DivInstruction.cs b/src/System.Management.Automation/engine/interpreter/DivInstruction.cs index 53a6e13316c..616a9cb8b02 100644 --- a/src/System.Management.Automation/engine/interpreter/DivInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/DivInstruction.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation.Interpreter { internal abstract class DivInstruction : Instruction { - private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_int16, s_int32, s_int64, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } diff --git a/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs b/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs index 68c9ef1dc9c..dae62d33d47 100644 --- a/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs @@ -20,7 +20,7 @@ namespace System.Management.Automation.Interpreter internal abstract class EqualInstruction : Instruction { // Perf: EqualityComparer but is 3/2 to 2 times slower. - private static Instruction s_reference,s_boolean,s_SByte,s_int16,s_char,s_int32,s_int64,s_byte,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_reference, s_boolean, s_SByte, s_int16, s_char, s_int32, s_int64, s_byte, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } diff --git a/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs b/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs index f5e433b8e89..24a4d5ba5bc 100644 --- a/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation.Interpreter { internal abstract class GreaterThanInstruction : Instruction { - private static Instruction s_SByte,s_int16,s_char,s_int32,s_int64,s_byte,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_SByte, s_int16, s_char, s_int32, s_int64, s_byte, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } diff --git a/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs b/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs index 971b2f79040..dcb682f7473 100644 --- a/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation.Interpreter { internal abstract class LessThanInstruction : Instruction { - private static Instruction s_SByte,s_int16,s_char,s_int32,s_int64,s_byte,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_SByte, s_int16, s_char, s_int32, s_int64, s_byte, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } diff --git a/src/System.Management.Automation/engine/interpreter/MulInstruction.cs b/src/System.Management.Automation/engine/interpreter/MulInstruction.cs index 4f67b5be486..16f8d6393ae 100644 --- a/src/System.Management.Automation/engine/interpreter/MulInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/MulInstruction.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation.Interpreter { internal abstract class MulInstruction : Instruction { - private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_int16, s_int32, s_int64, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } @@ -152,7 +152,7 @@ public override string ToString() internal abstract class MulOvfInstruction : Instruction { - private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_int16, s_int32, s_int64, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } diff --git a/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs b/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs index d2dc09e8fc7..2262f19e0b2 100644 --- a/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs @@ -20,7 +20,7 @@ namespace System.Management.Automation.Interpreter internal abstract class NotEqualInstruction : Instruction { // Perf: EqualityComparer but is 3/2 to 2 times slower. - private static Instruction s_reference,s_boolean,s_SByte,s_int16,s_char,s_int32,s_int64,s_byte,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_reference, s_boolean, s_SByte, s_int16, s_char, s_int32, s_int64, s_byte, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } diff --git a/src/System.Management.Automation/engine/interpreter/SubInstruction.cs b/src/System.Management.Automation/engine/interpreter/SubInstruction.cs index 37503783107..4d64b0640ab 100644 --- a/src/System.Management.Automation/engine/interpreter/SubInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/SubInstruction.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation.Interpreter { internal abstract class SubInstruction : Instruction { - private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_int16, s_int32, s_int64, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } @@ -152,7 +152,7 @@ public override string ToString() internal abstract class SubOvfInstruction : Instruction { - private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_int16, s_int32, s_int64, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs index a55561d60d0..338efdb5f7f 100644 --- a/src/System.Management.Automation/engine/lang/parserutils.cs +++ b/src/System.Management.Automation/engine/lang/parserutils.cs @@ -983,7 +983,8 @@ private static object ReplaceOperatorImpl(ExecutionContext context, string input return regex.Replace(input, replacementString); case ScriptBlock sb: - MatchEvaluator me = match => { + MatchEvaluator me = match => + { var result = sb.DoInvokeReturnAsIs( useLocalScope: false, /* Use current scope to be consistent with 'ForEach/Where-Object {}' and 'collection.ForEach{}/Where{}' */ errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, @@ -992,7 +993,7 @@ private static object ReplaceOperatorImpl(ExecutionContext context, string input scriptThis: AutomationNull.Value, args: Array.Empty()); - return PSObject.ToStringParser(context, result);; + return PSObject.ToStringParser(context, result); }; return regex.Replace(input, me); diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index 50ed92dbae3..4dcbf7a9305 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -1281,7 +1281,8 @@ private static IEnumerable GetAssemblyAttributeBuilders( var ctor = typeof(DynamicClassImplementationAssemblyAttribute).GetConstructor(Type.EmptyTypes); var emptyArgs = Array.Empty(); - if (string.IsNullOrEmpty(scriptFile)) { + if (string.IsNullOrEmpty(scriptFile)) + { yield return new CustomAttributeBuilder(ctor, emptyArgs); yield break; } @@ -1292,7 +1293,6 @@ private static IEnumerable GetAssemblyAttributeBuilders( yield return new CustomAttributeBuilder(ctor, emptyArgs, propertyInfo, propertyArgs, Array.Empty(), emptyArgs); - } private static int counter = 0; diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 6e0d02d1c14..8739ddfdbb1 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -127,8 +127,7 @@ internal class TypeInferenceContext public static readonly PSTypeName[] EmptyPSTypeNameArray = Array.Empty(); private readonly PowerShell _powerShell; - public TypeInferenceContext() - : this(PowerShell.Create(RunspaceMode.CurrentRunspace)) + public TypeInferenceContext() : this(PowerShell.Create(RunspaceMode.CurrentRunspace)) { } @@ -564,12 +563,9 @@ object ICustomAstVisitor.VisitHashtable(HashtableAst hashtableAst) switch (expression) { case ConstantExpressionAst constantExpression: - { value = constantExpression.Value; break; - } default: - { typeName = InferTypes(kv.Item2).FirstOrDefault()?.Name; if (typeName == null) { @@ -580,7 +576,6 @@ object ICustomAstVisitor.VisitHashtable(HashtableAst hashtableAst) } break; - } } } @@ -789,7 +784,6 @@ object ICustomAstVisitor.VisitParameter(ParameterAst parameterAst) switch (attrib) { case TypeConstraintAst typeConstraint: - { if (!typeConstraintAdded) { res.Add(new PSTypeName(typeConstraint.TypeName)); @@ -797,9 +791,7 @@ object ICustomAstVisitor.VisitParameter(ParameterAst parameterAst) } break; - } case AttributeAst attributeAst: - { PSTypeNameAttribute attribute = null; try { @@ -815,7 +807,6 @@ object ICustomAstVisitor.VisitParameter(ParameterAst parameterAst) } break; - } } } @@ -1184,21 +1175,15 @@ private void InferTypesFromGroupCommand(PseudoBindingInfo pseudoBinding, Command switch (astPair.Argument) { case StringConstantExpressionAst stringConstant: - { properties = new[] { stringConstant.Value }; break; - } case ArrayLiteralAst arrayLiteral: - { properties = arrayLiteral.Elements.OfType().Select(c => c.Value).ToArray(); scriptBlockProperty = arrayLiteral.Elements.OfType().Any(); - break; - } + break; case CommandElementAst _: - { scriptBlockProperty = true; break; - } } } } @@ -1313,15 +1298,11 @@ void InferFromSelectProperties(AstParameterArgumentPair astParameterArgumentPair switch (astPair.Argument) { case StringConstantExpressionAst stringConstant: - { properties = new[] { ToWildCardOrString(stringConstant.Value) }; break; - } case ArrayLiteralAst arrayLiteral: - { properties = arrayLiteral.Elements.OfType().Select(c => ToWildCardOrString(c.Value)).ToArray(); break; - } } if (properties == null) @@ -1347,23 +1328,19 @@ bool IsInPropertyArgument(object o) switch (propertyNameOrPattern) { case string propertyName: - { if (string.Compare(name, propertyName, StringComparison.OrdinalIgnoreCase) == 0) { return includeMatchedProperties; } break; - } case WildcardPattern pattern: - { if (pattern.IsMatch(name)) { return includeMatchedProperties; } break; - } } } @@ -1452,9 +1429,12 @@ private static bool IsProperty(object member) { switch (member) { - case PropertyInfo _: return true; - case PSMemberInfo memberInfo: return (memberInfo.MemberType & PSMemberTypes.Properties) == memberInfo.MemberType; - default: return false; + case PropertyInfo _: + return true; + case PSMemberInfo memberInfo: + return (memberInfo.MemberType & PSMemberTypes.Properties) == memberInfo.MemberType; + default: + return false; } } @@ -1591,7 +1571,6 @@ private bool TryGetTypeFromMember( switch (member) { case PropertyInfo propertyInfo: // .net property - { if (propertyInfo.Name.EqualsOrdinalIgnoreCase(memberName) && !isInvokeMemberExpressionAst) { result.Add(new PSTypeName(propertyInfo.PropertyType)); @@ -1599,9 +1578,7 @@ private bool TryGetTypeFromMember( } return false; - } case FieldInfo fieldInfo: // .net field - { if (fieldInfo.Name.EqualsOrdinalIgnoreCase(memberName) && !isInvokeMemberExpressionAst) { result.Add(new PSTypeName(fieldInfo.FieldType)); @@ -1609,9 +1586,7 @@ private bool TryGetTypeFromMember( } return false; - } case DotNetAdapter.MethodCacheEntry methodCacheEntry: // .net method - { if (methodCacheEntry[0].method.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) { maybeWantDefaultCtor = false; @@ -1620,9 +1595,7 @@ private bool TryGetTypeFromMember( } return false; - } case MemberAst memberAst: // this is for members defined by PowerShell classes - { if (memberAst.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) { if (isInvokeMemberExpressionAst) @@ -1654,9 +1627,7 @@ private bool TryGetTypeFromMember( } return false; - } case PSMemberInfo memberInfo: - { if (!memberInfo.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) { return false; @@ -1666,7 +1637,6 @@ private bool TryGetTypeFromMember( switch (memberInfo) { case PSMethod m: - { if (m.adapterData is DotNetAdapter.MethodCacheEntry methodCacheEntry) { AddTypesFromMethodCacheEntry(methodCacheEntry, result, isInvokeMemberExpressionAst); @@ -1674,46 +1644,31 @@ private bool TryGetTypeFromMember( } return false; - } case PSProperty p: - { result.Add(new PSTypeName(p.Value.GetType())); return true; - } case PSNoteProperty noteProperty: - { result.Add(new PSTypeName(noteProperty.Value.GetType())); return true; - } case PSAliasProperty aliasProperty: - { memberNamesToCheck.Add(aliasProperty.ReferencedMemberName); return true; - } case PSCodeProperty codeProperty: - { if (codeProperty.GetterCodeReference != null) { result.Add(new PSTypeName(codeProperty.GetterCodeReference.ReturnType)); } return true; - } case PSScriptProperty scriptProperty: - { scriptBlock = scriptProperty.GetterScript; break; - } case PSScriptMethod scriptMethod: - { scriptBlock = scriptMethod.Script; break; - } case PSInferredProperty inferredProperty: - { result.Add(inferredProperty.TypeName); break; - } } if (scriptBlock != null) @@ -1739,7 +1694,6 @@ private bool TryGetTypeFromMember( _context.CurrentThisType = thisToRestore; } } - } return false; } diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index dd5504c5927..0ba4a21cd78 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -5415,9 +5415,8 @@ public PipelineAst(IScriptExtent extent, IEnumerable pipelineEle /// /// If is null or is an empty collection. /// - public PipelineAst(IScriptExtent extent, IEnumerable pipelineElements) :this (extent, pipelineElements, background: false) + public PipelineAst(IScriptExtent extent, IEnumerable pipelineElements) : this(extent, pipelineElements, background: false) { - } /// @@ -5450,9 +5449,8 @@ public PipelineAst(IScriptExtent extent, CommandBaseAst commandAst, bool backgro /// /// If or is null. /// - public PipelineAst(IScriptExtent extent, CommandBaseAst commandAst) :this (extent, commandAst, background: false) + public PipelineAst(IScriptExtent extent, CommandBaseAst commandAst) : this(extent, commandAst, background: false) { - } /// diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index 78397a2d906..9d7d539090d 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -3920,7 +3920,7 @@ public override void SetBreakpoints(IEnumerable breakpoints) /// Get a breakpoint by id, primarily for Enable/Disable/Remove-PSBreakpoint cmdlets. /// /// Id of the breakpoint you want. - public override Breakpoint GetBreakpoint(int id) => + public override Breakpoint GetBreakpoint(int id) => _wrappedDebugger.GetBreakpoint(id); /// diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs index 9d673b5a24c..895e9a6d886 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs @@ -2020,7 +2020,7 @@ public override void SetBreakpoints(IEnumerable breakpoints) /// Get a breakpoint by id, primarily for Enable/Disable/Remove-PSBreakpoint cmdlets. /// /// Id of the breakpoint you want. - public override Breakpoint GetBreakpoint(int id) => + public override Breakpoint GetBreakpoint(int id) => _runspace.Debugger?.GetBreakpoint(id); /// @@ -2612,12 +2612,12 @@ private void SetIsActive(int breakpointCount) } } -#endregion + #endregion } -#endregion + #endregion -#region RemoteSessionStateProxy + #region RemoteSessionStateProxy internal class RemoteSessionStateProxy : SessionStateProxy { @@ -3022,5 +3022,5 @@ public override ProviderIntrinsics InvokeProvider } } -#endregion + #endregion } diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 6d59d474f30..0fad6b71989 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -500,7 +500,7 @@ protected override void BeginProcessing() { PSInvalidOperationException ioe = new PSInvalidOperationException( StringUtil.Format(RemotingErrorIdStrings.PluginDllMissing, RemotingConstants.PSPluginDLLName)); - ThrowTerminatingError(ioe.ErrorRecord); + ThrowTerminatingError(ioe.ErrorRecord); } } @@ -1538,7 +1538,7 @@ internal static string GetWinrmPluginShellName() internal static string GetWinrmPluginDllPath() { // PowerShell Core uses its versioned directory instead of system32 - string pluginDllDirectory = System.IO.Path.Combine("%windir%\\system32\\PowerShell", PSVersionInfo.GitCommitId); + string pluginDllDirectory = System.IO.Path.Combine("%windir%\\system32\\PowerShell", PSVersionInfo.GitCommitId); return System.IO.Path.Combine(pluginDllDirectory, RemotingConstants.PSPluginDLLName); } diff --git a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs index 163ab16067f..a4e83ef7ad5 100644 --- a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs @@ -1250,7 +1250,6 @@ protected override void EndProcessing() // finally dispose the job. _job.Dispose(); - } } } diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index d27be984575..482836dc600 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -3278,7 +3278,6 @@ private void HandleDebuggerStop(object sender, DebuggerStopEventArgs args) } #endregion - } /// diff --git a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs index 1b43b75840d..52930ab46ee 100644 --- a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs @@ -335,7 +335,7 @@ public override string FilePath Mandatory = true, ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)] [ValidateTrustedData] - [Alias("PSPath","LP")] + [Alias("PSPath", "LP")] public string LiteralPath { get diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 17a1faa08d0..2040c9b82ac 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -3045,7 +3045,7 @@ internal class ContainerProcess private const uint FileNotFoundHResult = 0x80070002; // The list of executable to try in order - private static readonly string[] Executables = new string[] { "pwsh.exe", "powershell.exe"}; + private static readonly string[] Executables = new string[] { "pwsh.exe", "powershell.exe" }; #endregion diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs index 304e6b817b2..15a008cba53 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs @@ -59,7 +59,7 @@ internal RemoteSessionCapability(RemotingDestination remotingDestination) // PS Version 3 is fully backward compatible with Version 2 // In the remoting protocol sense, nothing is changing between PS3 and PS2 // For negotiation to succeed with old client/servers we have to use 2. - _psversion = new Version(2,0); // PSVersionInfo.PSVersion; + _psversion = new Version(2, 0); // PSVersionInfo.PSVersion; _serversion = PSVersionInfo.SerializationVersion; _remotingDestination = remotingDestination; } diff --git a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs index 42566593f80..44c1423d8f4 100644 --- a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs +++ b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs @@ -167,7 +167,6 @@ internal void RaiseRunspaceDebugStopEvent(System.Management.Automation.Runspaces } #endregion - } #endregion IThrottleOperation diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs index d5b3013e778..32ce3834bce 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs @@ -118,7 +118,9 @@ public PSSenderInfo(PSPrincipal userPrincipal, string httpUrl) /// /// Contains information related to the user connecting to the server. /// - public PSPrincipal UserInfo { get; + public PSPrincipal UserInfo + { + get; // No public set because PSSenderInfo/PSPrincipal is used by PSSessionConfiguration's // and usually they dont cache this data internally..so did not want to give // cmdlets/scripts a chance to modify these. @@ -137,7 +139,9 @@ public TimeZoneInfo ClientTimeZone /// Connection string used by the client to connect to the server. This is /// directly taken from WSMAN_SENDER_DETAILS struct (from wsman.h) /// - public string ConnectionString { get; + public string ConnectionString + { + get; // No public set because PSSenderInfo/PSPrincipal is used by PSSessionConfiguration's // and usually they dont cache this data internally..so did not want to give // cmdlets/scripts a chance to modify these. @@ -173,7 +177,9 @@ public sealed class PSPrincipal : IPrincipal /// /// Gets the identity of the current user principal. /// - public PSIdentity Identity { get; + public PSIdentity Identity + { + get; // No public set because PSSenderInfo/PSPrincipal is used by PSSessionConfiguration's // and usually they dont cache this data internally..so did not want to give // cmdlets/scripts a chance to modify these. @@ -185,7 +191,9 @@ public sealed class PSPrincipal : IPrincipal /// a domain etc. This property tries to convert the Identity to WindowsIdentity /// using the user token supplied. /// - public WindowsIdentity WindowsIdentity { get; + public WindowsIdentity WindowsIdentity + { + get; // No public set because PSSenderInfo/PSPrincipal is used by PSSessionConfiguration's // and usually they dont cache this data internally..so did not want to give // cmdlets/scripts a chance to modify these. diff --git a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs index 701b7316c8d..abceadb40ac 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs @@ -19,28 +19,36 @@ internal class ServerPowerShellDriver #region Private Members private bool _extraPowerShellAlreadyScheduled; - private PowerShell _extraPowerShell; // extra PowerShell at the server to be run after localPowerShell - private PSDataCollection _localPowerShellOutput; // output buffer for the local PowerShell - // that is associated with this - // powershell driver - // associated with this powershell - // data structure handler object to handle all - // communications with the client - private bool[] _datasent = new bool[2]; // if the remaining data has been sent - // to the client before sending state - // information - private object _syncObject = new object(); // sync object for synchronizing sending - // data to client - private bool _noInput; // there is no input when this driver - // was created + + // extra PowerShell at the server to be run after localPowerShell + private PowerShell _extraPowerShell; + + // output buffer for the local PowerShell that is associated with this powershell driver + // associated with this powershell data structure handler object to handle all communications with the client + private PSDataCollection _localPowerShellOutput; + + // if the remaining data has been sent to the client before sending state information + private bool[] _datasent = new bool[2]; + + // sync object for synchronizing sending data to client + private object _syncObject = new object(); + + // there is no input when this driver was created + private bool _noInput; private bool _addToHistory; - private ServerRemoteHost _remoteHost; // the server remote host instance - // associated with this powershell -#if !CORECLR // No ApartmentState In CoreCLR - private ApartmentState apartmentState; // apartment state for this powershell + + // the server remote host instance + // associated with this powershell + private ServerRemoteHost _remoteHost; + +#if !CORECLR + // No ApartmentState In CoreCLR + // apartment state for this powershell + private ApartmentState apartmentState; #endif - private IRSPDriverInvoke _psDriverInvoker; // Handles nested invocation of PS drivers. + // Handles nested invocation of PS drivers. + private IRSPDriverInvoke _psDriverInvoker; #endregion Private Members diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs index 29ecb409455..e0256662fab 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -1780,7 +1780,7 @@ public override void SetBreakpoints(IEnumerable breakpoints) /// Get a breakpoint by id, primarily for Enable/Disable/Remove-PSBreakpoint cmdlets. /// /// Id of the breakpoint you want. - public override Breakpoint GetBreakpoint(int id) => + public override Breakpoint GetBreakpoint(int id) => _wrappedDebugger.Value.GetBreakpoint(id); /// @@ -2152,7 +2152,7 @@ internal void DoInvoke() { _results = WindowsIdentity.RunImpersonated( _identityToImpersonate.AccessToken, - () =>_wrappedDebugger.ProcessCommand(_command, _output)); + () => _wrappedDebugger.ProcessCommand(_command, _output)); return; } #endif diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs index 940bcec1342..780bc622b4d 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs @@ -160,9 +160,9 @@ internal ServerRemoteSession(PSSenderInfo senderInfo, transportManager.ReceivedDataCollection.MaximumReceivedDataSize = null; } -#endregion Constructors + #endregion Constructors -#region Creation Factory + #region Creation Factory /// /// Creates a server remote session for the supplied @@ -241,9 +241,9 @@ internal static ServerRemoteSession CreateServerRemoteSession(PSSenderInfo sende return result; } -#endregion + #endregion -#region Overrides + #region Overrides /// /// This indicates the remote session object is Client, Server or Listener. @@ -458,9 +458,9 @@ internal void SendEncryptedSessionKey() SessionDataStructureHandler.StateMachine.RaiseEvent(args); } -#endregion Overrides + #endregion Overrides -#region Properties + #region Properties /// /// This property returns the ServerRemoteSessionContext object created inside @@ -474,9 +474,9 @@ internal void SendEncryptedSessionKey() /// internal ServerRemoteSessionDataStructureHandler SessionDataStructureHandler { get; } -#endregion + #endregion -#region Private/Internal Methods + #region Private/Internal Methods /// /// Let the session clear its resources. @@ -1162,6 +1162,6 @@ internal void ApplyQuotaOnCommandTransportManager(AbstractServerTransportManager cmdTransportManager.ReceivedDataCollection.MaximumReceivedObjectSize = _maxRecvdObjectSize; } -#endregion + #endregion } } diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index 94e6fd4e686..55c34275123 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -7157,7 +7157,6 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, } else { - argExprs[i] = args[i].CastOrConvertMethodArgument( parameterType, paramName, diff --git a/src/System.Management.Automation/engine/runtime/MutableTuple.cs b/src/System.Management.Automation/engine/runtime/MutableTuple.cs index 703d76b6050..2982cdf53d6 100644 --- a/src/System.Management.Automation/engine/runtime/MutableTuple.cs +++ b/src/System.Management.Automation/engine/runtime/MutableTuple.cs @@ -53,7 +53,7 @@ internal bool IsValueSet(int index) nestedTuple = (MutableTuple)nestedTuple.GetValueImpl(accessPath[i]); } - return nestedTuple._valuesSet[accessPath[length-1]]; + return nestedTuple._valuesSet[accessPath[length - 1]]; } internal void SetAutomaticVariable(AutomaticVariable auto, object value, ExecutionContext context) diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index d4c6f8f10a6..a483d54c89b 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -456,7 +456,7 @@ internal static void InvokePipeline(object input, { pipelineProcessor.Commands.RemoveAt(commandsCount - 1); commandProcessor = nextToLastCommand; - nextToLastCommand.CommandRuntime.OutputPipe = new Pipe {NullPipe = true}; + nextToLastCommand.CommandRuntime.OutputPipe = new Pipe { NullPipe = true }; } } @@ -524,14 +524,14 @@ internal static void InvokePipelineInBackground( // Prefix variables in the scriptblock with $using: foreach (var v in variables) { - var vName = ((VariableExpressionAst) v).VariablePath.UserPath; + var vName = ((VariableExpressionAst)v).VariablePath.UserPath; // Skip variables that don't exist if (funcContext._executionContext.EngineSessionState.GetVariable(vName) == null) continue; // Skip PowerShell magic variables if (Regex.Match(vName, "^(global:){0,1}(PID|PSVersionTable|PSEdition|PSHOME|HOST|TRUE|FALSE|NULL)$", - RegexOptions.IgnoreCase|RegexOptions.CultureInvariant).Success == false + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant).Success == false ) { updatedScriptblock.Append(scriptblockBodyString.Substring(position, v.Extent.StartOffset - pipelineOffset - position)); @@ -825,7 +825,7 @@ internal static void CheckForInterrupts(ExecutionContext context) internal static void Nop() { } } -#region Redirections + #region Redirections internal abstract class CommandRedirection { @@ -1234,7 +1234,7 @@ private void Dispose(bool disposing) } } -#endregion Redirections + #endregion Redirections internal static class FunctionOps { @@ -1456,7 +1456,8 @@ internal static int FindMatchingHandler(MutableTuple tuple, RuntimeException rte int[] ranks = RankExceptionTypes(types); var current = new HandlerSearchResult(); - do { + do + { // Always assume no need to repeat the search for another interation continueToSearch = false; // The 'ErrorRecord' of the current RuntimeException would be passed to $_ diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index 048a7491d75..c2f35a7671f 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -1888,7 +1888,8 @@ int depth private Collection> _extendedMembersCollection; private Collection> ExtendedMembersCollection { - get { + get + { return _extendedMembersCollection ?? (_extendedMembersCollection = PSObject.GetMemberCollection(PSMemberViewTypes.Extended, _typeTable)); @@ -1898,7 +1899,8 @@ private Collection> ExtendedMembersCollection private Collection> _allPropertiesCollection; private Collection> AllPropertiesCollection { - get { + get + { return _allPropertiesCollection ?? (_allPropertiesCollection = PSObject.GetPropertyCollection(PSMemberViewTypes.All, _typeTable)); } diff --git a/src/System.Management.Automation/help/CabinetNativeApi.cs b/src/System.Management.Automation/help/CabinetNativeApi.cs index a22ad7f3dc8..db5a3ec7452 100644 --- a/src/System.Management.Automation/help/CabinetNativeApi.cs +++ b/src/System.Management.Automation/help/CabinetNativeApi.cs @@ -232,7 +232,7 @@ internal static IntPtr FdiOpen(string filename, int oflag, int pmode) // This method is used for opening the cab file as well as saving the extracted files. // When we are opening the cab file we only need read permissions. // We force read permissions so that non-elevated users can extract cab files. - if(mode == FileMode.Open || mode == FileMode.OpenOrCreate) + if (mode == FileMode.Open || mode == FileMode.OpenOrCreate) { access = FileAccess.Read; share = FileShare.Read; diff --git a/src/System.Management.Automation/help/HelpFileHelpProvider.cs b/src/System.Management.Automation/help/HelpFileHelpProvider.cs index 32066611ac8..b83385205a5 100644 --- a/src/System.Management.Automation/help/HelpFileHelpProvider.cs +++ b/src/System.Management.Automation/help/HelpFileHelpProvider.cs @@ -166,18 +166,18 @@ private Collection FilterToLatestModuleVersion(Collection filesM // This is done after the version check filtering to ensure we do not remove later version files. HashSet fileNameHash = new HashSet(); - foreach(var file in filesMatched) + foreach (var file in filesMatched) { string fileName = Path.GetFileName(file); - if(!fileNameHash.Contains(fileName)) + if (!fileNameHash.Contains(fileName)) { fileNameHash.Add(fileName); } else { // If the file need to be removed, add it to matchedFilesToRemove, if not already present. - if(!matchedFilesToRemove.Contains(file)) + if (!matchedFilesToRemove.Contains(file)) { matchedFilesToRemove.Add(file); } diff --git a/src/System.Management.Automation/help/SaveHelpCommand.cs b/src/System.Management.Automation/help/SaveHelpCommand.cs index 407aae5b788..a1bb355ab9d 100644 --- a/src/System.Management.Automation/help/SaveHelpCommand.cs +++ b/src/System.Management.Automation/help/SaveHelpCommand.cs @@ -62,7 +62,7 @@ public string[] DestinationPath /// Specifies the literal path to save updates to. /// [Parameter(Mandatory = true, ParameterSetName = LiteralPathParameterSetName)] - [Alias("PSPath","LP")] + [Alias("PSPath", "LP")] [ValidateNotNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] LiteralPath diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index 05634917a56..0127f5518be 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -883,7 +883,7 @@ internal void ProcessException(string moduleName, string culture, Exception e) #endregion } - /// + /// /// Scope to which the help should be saved. /// public enum UpdateHelpScope diff --git a/src/System.Management.Automation/help/UpdateHelpCommand.cs b/src/System.Management.Automation/help/UpdateHelpCommand.cs index 9fb1a059b3f..e5514ff6e42 100644 --- a/src/System.Management.Automation/help/UpdateHelpCommand.cs +++ b/src/System.Management.Automation/help/UpdateHelpCommand.cs @@ -94,7 +94,7 @@ public string[] SourcePath /// Specifies the literal path to save updates to. /// [Parameter(ParameterSetName = LiteralPathParameterSetName, ValueFromPipelineByPropertyName = true)] - [Alias("PSPath","LP")] + [Alias("PSPath", "LP")] [ValidateNotNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] LiteralPath @@ -223,7 +223,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, string moduleBase = module.ModuleBase; - if(this.Scope == UpdateHelpScope.CurrentUser) + if (this.Scope == UpdateHelpScope.CurrentUser) { moduleBase = HelpUtils.GetModuleBaseForUserHelp(moduleBase, module.ModuleName); } @@ -391,7 +391,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, // Gather destination paths Collection destPaths = new Collection(); - if(!Directory.Exists(moduleBase)) + if (!Directory.Exists(moduleBase)) { Directory.CreateDirectory(moduleBase); } diff --git a/src/System.Management.Automation/namespaces/AliasProvider.cs b/src/System.Management.Automation/namespaces/AliasProvider.cs index 3ce1bc8a219..aafed93a880 100644 --- a/src/System.Management.Automation/namespaces/AliasProvider.cs +++ b/src/System.Management.Automation/namespaces/AliasProvider.cs @@ -318,7 +318,6 @@ internal override bool CanRenameItem(object item) } #endregion protected members - } /// diff --git a/src/System.Management.Automation/namespaces/EnvironmentProvider.cs b/src/System.Management.Automation/namespaces/EnvironmentProvider.cs index 6a9227030e0..a8c03994869 100644 --- a/src/System.Management.Automation/namespaces/EnvironmentProvider.cs +++ b/src/System.Management.Automation/namespaces/EnvironmentProvider.cs @@ -200,7 +200,8 @@ internal override IDictionary GetSessionStateTable() // (If, by contrast, we just used `entry` as-is every time a duplicate is encountered, // it could - intermittently - represent a value *other* than the effective one.) string effectiveValue = Environment.GetEnvironmentVariable((string)entry.Key); - if (((string)entry.Value).Equals(effectiveValue, StringComparison.Ordinal)) { // We've found the effective definition. + if (((string)entry.Value).Equals(effectiveValue, StringComparison.Ordinal)) + { // We've found the effective definition. // Note: We *recreate* the entry so that the specific name casing of the // effective definition is also reflected. However, if the case variants // define the same value, it is unspecified which name variant is reflected diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 278049098c1..db3d68962a8 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -98,7 +98,75 @@ public FileSystemProvider() /// private static string NormalizePath(string path) { - return path.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator); + return GetCorrectCasedPath(path.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator)); + } + + /// + /// Get the correct casing for a path. This method assumes it's being called by NormalizePath() + /// so that the path is already normalized. + /// + /// + /// The path to retrieve. + /// + /// + /// The path with accurate casing if item exists, otherwise it returns path that was passed in. + /// + private static string GetCorrectCasedPath(string path) + { + // Only apply to directories where there are issues with some tools if the casing + // doesn't match the source like git + if (Directory.Exists(path)) + { + string exactPath = string.Empty; + int itemsToSkip = 0; + if (Utils.PathIsUnc(path)) + { + // With the Split method, a UNC path like \\server\share, we need to skip + // trying to enumerate the server and share, so skip the first two empty + // strings, then server, and finally share name. + itemsToSkip = 4; + } + + foreach (string item in path.Split(StringLiterals.DefaultPathSeparator)) + { + if (itemsToSkip-- > 0) + { + // This handles the UNC server and share and 8.3 short path syntax + exactPath += item + StringLiterals.DefaultPathSeparator; + continue; + } + else if (string.IsNullOrEmpty(exactPath)) + { + // This handles the drive letter or / root path start + exactPath = item + StringLiterals.DefaultPathSeparator; + } + else if (string.IsNullOrEmpty(item)) + { + // This handles the trailing slash case + continue; + } + else if (item.Contains('~')) + { + // This handles short path names + exactPath += StringLiterals.DefaultPathSeparator + item; + } + else + { + exactPath = Directory.GetFileSystemEntries(exactPath, item).First(); + } + } + + if (path.EndsWith(StringLiterals.DefaultPathSeparator)) + { + return exactPath + StringLiterals.DefaultPathSeparator; + } + + return exactPath; + } + else + { + return path; + } } /// @@ -355,7 +423,7 @@ public string GetHelpMaml(string helpItemName, string path) protected override ProviderInfo Start(ProviderInfo providerInfo) { // Set the home folder for the user - if (providerInfo != null && string.IsNullOrEmpty(providerInfo.Home)) + if (providerInfo != null && string.IsNullOrEmpty(providerInfo.Home)) { // %USERPROFILE% - indicate where a user's home directory is located in the file system. string homeDirectory = Environment.GetEnvironmentVariable(Platform.CommonEnvVariableNames.Home); @@ -1910,10 +1978,10 @@ string ToModeString(FileSystemInfo fileSystemInfo) ReadOnlySpan mode = stackalloc char[] { isLink ? 'l' : isDirectory ? 'd' : '-', - fileAttributes.HasFlag(FileAttributes.Archive) ? 'a' : '-', + fileAttributes.HasFlag(FileAttributes.Archive) ? 'a' : '-', fileAttributes.HasFlag(FileAttributes.ReadOnly) ? 'r' : '-', - fileAttributes.HasFlag(FileAttributes.Hidden) ? 'h' : '-', - fileAttributes.HasFlag(FileAttributes.System) ? 's' : '-', + fileAttributes.HasFlag(FileAttributes.Hidden) ? 'h' : '-', + fileAttributes.HasFlag(FileAttributes.System) ? 's' : '-', }; return new string(mode); } @@ -7435,7 +7503,6 @@ public Encoding Encoding /// if the stream was opened with a user-specified encoding, false otherwise. /// public bool WasStreamTypeSpecified { get; private set; } - } /// diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index 4621681764a..efb9ac1298b 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -1524,10 +1524,10 @@ internal static bool IsAbsolutePath(string path) { // see if there are any path separators before the colon which would mean the // colon is part of a file or folder name and not a drive: ./foo:bar vs foo:bar - int separator = path.IndexOf(StringLiterals.DefaultPathSeparator, 0, index-1); + int separator = path.IndexOf(StringLiterals.DefaultPathSeparator, 0, index - 1); if (separator == -1) { - separator = path.IndexOf(StringLiterals.AlternatePathSeparator, 0, index-1); + separator = path.IndexOf(StringLiterals.AlternatePathSeparator, 0, index - 1); } if (separator == -1 || index < separator) @@ -1930,13 +1930,13 @@ internal string GetDriveRootRelativePathFromPSPath( string relativePath = string.Empty; - relativePath = - GenerateRelativePath( - workingDriveForPath, - path, - escapeCurrentLocation, - providerInstance, - context); + relativePath = + GenerateRelativePath( + workingDriveForPath, + path, + escapeCurrentLocation, + providerInstance, + context); return relativePath; } diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index 23a10505162..434532b4430 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -157,16 +157,15 @@ internal static void SetExecutionPolicy(ExecutionPolicyScope scope, ExecutionPol switch (scope) { case ExecutionPolicyScope.Process: - { + if (policy == ExecutionPolicy.Undefined) executionPolicy = null; Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", executionPolicy); break; - } case ExecutionPolicyScope.CurrentUser: - { + // They want to remove it if (policy == ExecutionPolicy.Undefined) { @@ -178,10 +177,9 @@ internal static void SetExecutionPolicy(ExecutionPolicyScope scope, ExecutionPol } break; - } case ExecutionPolicyScope.LocalMachine: - { + // They want to remove it if (policy == ExecutionPolicy.Undefined) { @@ -193,7 +191,6 @@ internal static void SetExecutionPolicy(ExecutionPolicyScope scope, ExecutionPol } break; - } } #endif } @@ -477,7 +474,7 @@ private static string GetLocalPreferenceValue(string shellId, ExecutionPolicySco return null; } -#endregion execution policy + #endregion execution policy private static bool _saferIdentifyLevelApiSupported = true; diff --git a/src/System.Management.Automation/utils/EncodingUtils.cs b/src/System.Management.Automation/utils/EncodingUtils.cs index 2ac22b11c4c..26a1b6a60ac 100644 --- a/src/System.Management.Automation/utils/EncodingUtils.cs +++ b/src/System.Management.Automation/utils/EncodingUtils.cs @@ -10,7 +10,6 @@ namespace System.Management.Automation { - internal static class EncodingConversion { internal const string Unknown = "unknown"; @@ -29,7 +28,7 @@ internal static class EncodingConversion Ascii, BigEndianUnicode, OEM, Unicode, Utf7, Utf8, Utf8Bom, Utf8NoBom, Utf32 }; - internal static Dictionary encodingMap = new Dictionary(StringComparer.OrdinalIgnoreCase) + internal static Dictionary encodingMap = new Dictionary(StringComparer.OrdinalIgnoreCase) { { Ascii, System.Text.Encoding.ASCII }, { BigEndianUnicode, System.Text.Encoding.BigEndianUnicode }, @@ -79,7 +78,6 @@ internal static Encoding Convert(Cmdlet cmdlet, string encoding) return null; } - } /// @@ -103,7 +101,7 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input return System.Text.Encoding.GetEncoding(stringName); } case int intName: - return System.Text.Encoding.GetEncoding(intName); + return System.Text.Encoding.GetEncoding(intName); } return inputData; @@ -126,6 +124,6 @@ public ArgumentEncodingCompletionsAttribute() : base( EncodingConversion.Utf8NoBom, EncodingConversion.Utf32 ) - {} + { } } } diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index bb970e8aee1..297105a1c17 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -710,7 +710,8 @@ protected ParentContainsErrorRecordException( /// public override string Message { - get { + get + { return _message ?? (_message = (_wrapperException != null) ? _wrapperException.Message : string.Empty); } } diff --git a/src/System.Management.Automation/utils/IObjectWriter.cs b/src/System.Management.Automation/utils/IObjectWriter.cs index fe91dc2173c..c3367ee77f3 100644 --- a/src/System.Management.Automation/utils/IObjectWriter.cs +++ b/src/System.Management.Automation/utils/IObjectWriter.cs @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System; +using System.Collections; +using System.Threading; + namespace System.Management.Automation.Runspaces { - using System; - using System.Threading; - using System.Collections; - /// /// PipelineWriter allows the caller to provide an asynchronous stream of objects /// as input to a . diff --git a/src/System.Management.Automation/utils/ObjectReader.cs b/src/System.Management.Automation/utils/ObjectReader.cs index 8cfcaa49e5f..37f27e059c1 100644 --- a/src/System.Management.Automation/utils/ObjectReader.cs +++ b/src/System.Management.Automation/utils/ObjectReader.cs @@ -1,15 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System; +using System.Collections.ObjectModel; +using System.Management.Automation; +using System.Management.Automation.Runspaces; +using System.Runtime.InteropServices; +using System.Threading; + namespace System.Management.Automation.Internal { - using System; - using System.Threading; - using System.Runtime.InteropServices; - using System.Collections.ObjectModel; - using System.Management.Automation.Runspaces; - using System.Management.Automation; - /// /// A PipelineReader for an ObjectStream. /// diff --git a/src/System.Management.Automation/utils/PSTelemetryMethods.cs b/src/System.Management.Automation/utils/PSTelemetryMethods.cs index 820d5aa742c..a131a7bfef4 100644 --- a/src/System.Management.Automation/utils/PSTelemetryMethods.cs +++ b/src/System.Management.Automation/utils/PSTelemetryMethods.cs @@ -19,7 +19,7 @@ namespace Microsoft.PowerShell.Telemetry.Internal [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public static class TelemetryAPI { - #region Public API +#region Public API /// /// Public API to expose Telemetry in PowerShell @@ -31,7 +31,7 @@ public static void TraceMessage(string message, T arguments) TelemetryWrapper.TraceMessage(message, arguments); } - #endregion +#endregion private static int s_anyPowerShellSessionOpen; private static DateTime s_sessionStartTime; diff --git a/src/System.Management.Automation/utils/PlatformInvokes.cs b/src/System.Management.Automation/utils/PlatformInvokes.cs index ab8ac2dc40a..9f7977dcc86 100644 --- a/src/System.Management.Automation/utils/PlatformInvokes.cs +++ b/src/System.Management.Automation/utils/PlatformInvokes.cs @@ -611,7 +611,6 @@ public STARTUPINFO() this.hStdOutput = new SafeFileHandle(IntPtr.Zero, false); this.hStdError = new SafeFileHandle(IntPtr.Zero, false); this.cb = Marshal.SizeOf(this); - } public void Dispose(bool disposing) diff --git a/src/System.Management.Automation/utils/PowerShellETWTracer.cs b/src/System.Management.Automation/utils/PowerShellETWTracer.cs index cfea7b4ac9e..d9945d4cc0f 100644 --- a/src/System.Management.Automation/utils/PowerShellETWTracer.cs +++ b/src/System.Management.Automation/utils/PowerShellETWTracer.cs @@ -11,7 +11,7 @@ namespace System.Management.Automation.Tracing { // pragma warning disable 16001,16003 -#region Constants + #region Constants /// /// Defines enumerations for event ids. @@ -682,7 +682,7 @@ public enum PowerShellTraceKeywords : ulong UseAlwaysAnalytic = 0x4000000000000000, } -#endregion + #endregion /// /// BaseChannelWriter is the abstract base class defines event specific methods that are used to write a trace. diff --git a/src/System.Management.Automation/utils/PsUtils.cs b/src/System.Management.Automation/utils/PsUtils.cs index 422e634228d..f9d1e9c066b 100644 --- a/src/System.Management.Automation/utils/PsUtils.cs +++ b/src/System.Management.Automation/utils/PsUtils.cs @@ -187,7 +187,7 @@ internal static string GetTemporaryDirectory() string tempPath = Path.GetTempPath(); do { - tempDir = Path.Combine(tempPath,System.Guid.NewGuid().ToString()); + tempDir = Path.Combine(tempPath, System.Guid.NewGuid().ToString()); } while (Directory.Exists(tempDir)); diff --git a/src/System.Management.Automation/utils/Verbs.cs b/src/System.Management.Automation/utils/Verbs.cs index caa7497c6d3..1bfefa963ad 100644 --- a/src/System.Management.Automation/utils/Verbs.cs +++ b/src/System.Management.Automation/utils/Verbs.cs @@ -1103,7 +1103,7 @@ internal static class VerbAliasPrefixes public static string GetVerbAliasPrefix(string verb) { FieldInfo aliasField = typeof(VerbAliasPrefixes).GetField(verb); - if(aliasField != null) + if (aliasField != null) { return (string)aliasField.GetValue(null); } @@ -1124,7 +1124,7 @@ public class VerbInfo /// public string Verb { - get;set; + get; set; } /// @@ -1132,7 +1132,7 @@ public string Verb /// public string AliasPrefix { - get;set; + get; set; } /// @@ -1140,7 +1140,7 @@ public string AliasPrefix /// public string Group { - get;set; + get; set; } /// @@ -1148,7 +1148,7 @@ public string Group /// public string Description { - get;set; + get; set; } } diff --git a/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs b/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs index ac4440d7ded..3a753e59182 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs @@ -9,14 +9,14 @@ namespace System.Management.Automation.Tracing internal class EtwActivityReverterMethodInvoker : IMethodInvoker { -#region Instance Data + #region Instance Data private readonly IEtwEventCorrelator _eventCorrelator; private readonly Func _invoker; -#endregion + #endregion -#region Creation/Cleanup + #region Creation/Cleanup public EtwActivityReverterMethodInvoker(IEtwEventCorrelator eventCorrelator) { @@ -29,9 +29,9 @@ public EtwActivityReverterMethodInvoker(IEtwEventCorrelator eventCorrelator) _invoker = DoInvoke; } -#endregion + #endregion -#region Instance Access + #region Instance Access public Delegate Invoker { @@ -51,9 +51,9 @@ public object[] CreateInvokerArgs(Delegate methodToInvoke, object[] methodToInvo return retInvokerArgs; } -#endregion + #endregion -#region Instance Utilities + #region Instance Utilities private object DoInvoke(Guid relatedActivityId, Delegate method, object[] methodArgs) { @@ -63,7 +63,7 @@ private object DoInvoke(Guid relatedActivityId, Delegate method, object[] method } } -#endregion + #endregion } } diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs index 9f1f1415c4a..895e9a0309f 100644 --- a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs @@ -41,7 +41,6 @@ internal static void LogConsoleStartup() PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStart, PSOpcode.WinStart, PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational); - } /// diff --git a/src/System.Management.Automation/utils/tracing/SysLogProvider.cs b/src/System.Management.Automation/utils/tracing/SysLogProvider.cs index 56e64f9cfc3..59b2c0055cf 100755 --- a/src/System.Management.Automation/utils/tracing/SysLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/SysLogProvider.cs @@ -191,7 +191,7 @@ private bool ShouldLog(PSLevel level, PSKeyword keywords, PSChannel channel) IsEnabled(level, keywords)); } - #region resource manager +#region resource manager private static global::System.Resources.ResourceManager _resourceManager; private static global::System.Globalization.CultureInfo _resourceCulture; @@ -239,7 +239,7 @@ private static string GetResourceString(string resourceName) return value; } - #endregion resource manager +#endregion resource manager /// /// Gets the EventMessage for a given event. @@ -272,7 +272,7 @@ private static void GetEventMessage(StringBuilder sb, PSEventId eventId, params } } - #region logging +#region logging // maps a LogLevel to an associated SysLogPriority. static NativeMethods.SysLogPriority[] _levels = @@ -359,7 +359,7 @@ public void Log(PSEventId eventId, PSChannel channel, PSTask task, PSOpcode opco } } - #endregion logging +#endregion logging } internal enum LogLevel : uint diff --git a/test/common/markdown/package.json b/test/common/markdown/package.json index 061f0359901..83f6780cf6b 100644 --- a/test/common/markdown/package.json +++ b/test/common/markdown/package.json @@ -4,7 +4,7 @@ "description": "The PowerShell Common MarkDown Tests.", "main": "gulpfile.js", "dependencies": { - "gulp": "^4.0.0", + "gulp": "^4.0.1", "markdownlint": "^0.12.0", "through2": "^3.0.1" }, diff --git a/test/common/markdown/yarn.lock b/test/common/markdown/yarn.lock index 77b55d95507..1e606cb3740 100644 --- a/test/common/markdown/yarn.lock +++ b/test/common/markdown/yarn.lock @@ -841,7 +841,7 @@ glob-stream@^6.1.0: to-absolute-glob "^2.0.0" unique-stream "^2.0.2" -glob-watcher@^5.0.0: +glob-watcher@^5.0.3: version "5.0.3" resolved "https://registry.yarnpkg.com/glob-watcher/-/glob-watcher-5.0.3.tgz#88a8abf1c4d131eb93928994bc4a593c2e5dd626" integrity sha512-8tWsULNEPHKQ2MR4zXuzSmqbdyV5PtwwCaWSGQ1WwHsJ07ilNeN1JB8ntxhckbnpSHaf9dXFUHzIWvm1I13dsg== @@ -897,10 +897,10 @@ graceful-fs@^4.0.0, graceful-fs@^4.1.11, graceful-fs@^4.1.2, graceful-fs@^4.1.6: resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.15.tgz#ffb703e1066e8a0eeaa4c8b80ba9253eeefbfb00" integrity sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA== -gulp-cli@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/gulp-cli/-/gulp-cli-2.1.0.tgz#2705143ae744c9e10d894ca621ce0a3933aa2e89" - integrity sha512-txzgdFVlEPShBZus6JJyGyKJoBVDq6Do0ZQgIgx5RAsmhNVTDjymmOxpQvo3c20m66FldilS68ZXj2Q9w5dKbA== +gulp-cli@^2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/gulp-cli/-/gulp-cli-2.2.0.tgz#5533126eeb7fe415a7e3e84a297d334d5cf70ebc" + integrity sha512-rGs3bVYHdyJpLqR0TUBnlcZ1O5O++Zs4bA0ajm+zr3WFCfiSLjGwoCBqFs18wzN+ZxahT9DkOK5nDf26iDsWjA== dependencies: ansi-colors "^1.0.1" archy "^1.0.0" @@ -942,14 +942,14 @@ gulp-debug@^4.0.0: through2 "^2.0.0" tildify "^1.1.2" -gulp@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/gulp/-/gulp-4.0.0.tgz#95766c601dade4a77ed3e7b2b6dc03881b596366" - integrity sha1-lXZsYB2t5Kd+0+eyttwDiBtZY2Y= +gulp@^4.0.1: + version "4.0.1" + resolved "https://registry.yarnpkg.com/gulp/-/gulp-4.0.1.tgz#987a38a55a7d3677f6b49e291b06bc05809f33d9" + integrity sha512-yDVtVunxrAdsk7rIV/b7lVSBifPN1Eqe6wTjsESGrFcL+MEVzaaeNTkpUuGTUptloSOU+8oJm/lBJbgPV+tMAw== dependencies: - glob-watcher "^5.0.0" - gulp-cli "^2.0.0" - undertaker "^1.0.0" + glob-watcher "^5.0.3" + gulp-cli "^2.2.0" + undertaker "^1.2.1" vinyl-fs "^3.0.0" gulplog@^1.0.0: @@ -2389,10 +2389,10 @@ undertaker-registry@^1.0.0: resolved "https://registry.yarnpkg.com/undertaker-registry/-/undertaker-registry-1.0.1.tgz#5e4bda308e4a8a2ae584f9b9a4359a499825cc50" integrity sha1-XkvaMI5KiirlhPm5pDWaSZglzFA= -undertaker@^1.0.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/undertaker/-/undertaker-1.2.0.tgz#339da4646252d082dc378e708067299750e11b49" - integrity sha1-M52kZGJS0ILcN45wgGcpl1DhG0k= +undertaker@^1.2.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/undertaker/-/undertaker-1.2.1.tgz#701662ff8ce358715324dfd492a4f036055dfe4b" + integrity sha512-71WxIzDkgYk9ZS+spIB8iZXchFhAdEo2YU8xYqBYJ39DIUIqziK78ftm26eecoIY49X0J2MLhG4hr18Yp6/CMA== dependencies: arr-flatten "^1.0.1" arr-map "^2.0.0" diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/Remove-Module.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/Remove-Module.Tests.ps1 index 70a5b544b57..37739cdb7ad 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/Remove-Module.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/Remove-Module.Tests.ps1 @@ -1,19 +1,407 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. + +Describe "Remove-Module -Name | -FullyQualifiedName | -ModuleInfo" -Tags "CI" { + BeforeAll { + Remove-Module -Name "Foo", "Bar", "Baz" -ErrorAction SilentlyContinue + + New-Item -ItemType Directory -Path "$testdrive\Modules\Foo\1.0\" -Force > $null + New-Item -ItemType Directory -Path "$testdrive\Modules\Foo\2.0\" -Force > $null + New-Item -ItemType Directory -Path "$testdrive\Modules\Bar\" -Force > $null + New-Item -ItemType Directory -Path "$testdrive\Modules\Baz\" -Force > $null + + New-ModuleManifest -Path "$testdrive\Modules\Foo\1.0\Foo.psd1" -ModuleVersion 1.0 + New-ModuleManifest -Path "$testdrive\Modules\Foo\2.0\Foo.psd1" -ModuleVersion 2.0 + New-ModuleManifest -Path "$testdrive\Modules\Bar\Bar.psd1" -ModuleVersion 1.0 + New-ModuleManifest -Path "$testdrive\Modules\Baz\Baz.psd1" -ModuleVersion 1.0 + + New-Item -ItemType File -Path "$testdrive\Modules\Foo\1.0\Foo.psm1" > $null + New-Item -ItemType File -Path "$testdrive\Modules\Foo\2.0\Foo.psm1" > $null + New-Item -ItemType File -Path "$testdrive\Modules\Bar\Bar.psm1" > $null + + $removeModuleByNameTestCases = @( + # Simple patterns + @{ PatternsToRemove = "Bar"; ShouldBeRemoved = "Bar"; ShouldBePresent = "Baz", "Foo", "Foo"} + @{ PatternsToRemove = "Foo"; ShouldBeRemoved = "Foo"; ShouldBePresent = "Bar", "Baz"} + @{ PatternsToRemove = "Bar", "Foo"; ShouldBeRemoved = "Bar", "Foo"; ShouldBePresent = "Baz"} + @{ PatternsToRemove = "Bar", "Baz", "Foo"; ShouldBeRemoved = "Bar", "Baz", "Foo"; ShouldBePresent = ""} + @{ PatternsToRemove = "Foo", "Foo"; ShouldBeRemoved = "Foo"; ShouldBePresent = "Bar", "Baz"} + @{ PatternsToRemove = "Foo", "Foo", "Bar"; ShouldBeRemoved = "Bar", "Foo"; ShouldBePresent = "Baz"} + @{ PatternsToRemove = "Fo", "Foo"; ShouldBeRemoved = "Foo"; ShouldBePresent = "Bar", "Baz"} + + # Regex patterns + #@{ PatternsToRemove = "*"; ShouldBeRemoved = "Bar", "Baz", "Foo"; ShouldBePresent = ""} -> this breaks pester for some reason + @{ PatternsToRemove = "B*"; ShouldBeRemoved = "Bar", "Baz"; ShouldBePresent = "Foo", "Foo"} + @{ PatternsToRemove = "F*"; ShouldBeRemoved = "Foo"; ShouldBePresent = "Bar", "Baz"} + @{ PatternsToRemove = "Foo*"; ShouldBeRemoved = "Foo"; ShouldBePresent = "Bar", "Baz"} + @{ PatternsToRemove = "F*", "Bar"; ShouldBeRemoved = "Foo", "Bar"; ShouldBePresent = "Baz"} + @{ PatternsToRemove = "F*", "F*"; ShouldBeRemoved = "Foo"; ShouldBePresent = "Bar", "Baz"} + @{ PatternsToRemove = "FF*"; ShouldBeRemoved = ""; ShouldBePresent = "Bar", "Baz", "Foo", "Foo"} + ) + + $removeModuleByNameErrorTestCases = @( + # Invalid patterns + @{ PatternsToRemove = "Fo"; ShouldBeRemoved = ""; ShouldBePresent = "Bar", "Baz", "Foo", "Foo"} + @{ PatternsToRemove = "Fo", "Ba"; ShouldBeRemoved = ""; ShouldBePresent = "Bar", "Baz", "Foo", "Foo"} + ) + + $removeModuleByFQNTestCases = @( + @{ + FqnToRemove = @{ModuleName = "Foo"; ModuleVersion = "1.0"}; + ShouldBeRemoved = "Foo"; + ShouldBePresent = "Bar", "Baz"; + } + @{ + FqnToRemove = @{ModuleName = "Foo"; RequiredVersion = "1.0"}; + ShouldBeRemoved = ""; + ShouldBePresent = "Bar", "Baz", "Foo"; + } + @{ + FqnToRemove = @{ModuleName = "Foo"; ModuleVersion = "2.0"}; + ShouldBeRemoved = ""; + ShouldBePresent = "Bar", "Baz", "Foo"; + } + @{ + FqnToRemove = @{ModuleName = "Foo"; RequiredVersion = "2.0"}; + ShouldBeRemoved = ""; + ShouldBePresent = "Bar", "Baz", "Foo"; + } + @{ + FqnToRemove = @{ModuleName = "Foo"; ModuleVersion = "1.0"}; + ShouldBeRemoved = "Foo"; + ShouldBePresent = "Bar", "Baz"; + } + @{ + FqnToRemove = @{ModuleName = "Foo"; ModuleVersion = "1.0"}, @{ModuleName = "Bar"; ModuleVersion = "1.0"}; + ShouldBeRemoved = "Foo", "Bar"; + ShouldBePresent = "Baz"; + } + @{ + FqnToRemove = @{ModuleName = "Foo"; ModuleVersion = "3.0"}, @{ModuleName = "Bar"; ModuleVersion = "1.0"}; + ShouldBeRemoved = "Bar"; + ShouldBePresent = "Baz", "Foo", "Foo"; + } + ) + + $removeModuleByFQNErrorTestCases = @( + @{ + FqnToRemove = @{ModuleName = "Fo"; ModuleVersion = "1.0"}; + ShouldBeRemoved = ""; + ShouldBePresent = "Bar", "Baz", "Foo", "Foo"; + } + @{ + FqnToRemove = @{ModuleName = "Foo"; ModuleVersion = "3.0"}; + ShouldBeRemoved = ""; + ShouldBePresent = "Bar", "Baz", "Foo", "Foo"; + } + @{ + FqnToRemove = @{ModuleName = "Baz"; RequiredVersion = "3.0"}; + ShouldBeRemoved = ""; + ShouldBePresent = "Bar", "Baz", "Foo", "Foo"; + } + ) + } + + BeforeEach { + Import-Module -Name "$testdrive\Modules\Foo\1.0\Foo.psd1" -Force + Import-Module -Name "$testdrive\Modules\Foo\2.0\Foo.psd1" -Force + Import-Module -Name "$testdrive\Modules\Bar\Bar.psd1" -Force + Import-Module -Name "$testdrive\Modules\Baz\Baz.psd1" -Force + } + + AfterAll { + Remove-Module -Name "Foo", "Bar", "Baz" -ErrorAction SilentlyContinue + } + + It "Remove-Module -Name " -TestCases $removeModuleByNameTestCases { + param([string[]]$PatternsToRemove, [string[]]$ShouldBeRemoved, [string[]]$ShouldBePresent) + + (Get-Module -Name "Bar", "Baz", "Foo").Name | Should -BeExactly "Bar", "Baz", "Foo", "Foo" + + { Remove-Module -Name $PatternsToRemove} | Should -Not -Throw + + if ($ShouldBeRemoved) { + (Get-Module -Name $ShouldBeRemoved).Name | Should -BeNullOrEmpty + } + + if ($ShouldBePresent) { + (Get-Module -Name $ShouldBePresent).Name | Should -BeExactly $ShouldBePresent + } + } + + It "Remove-Module -Name (Error cases)" -TestCases $removeModuleByNameErrorTestCases { + param([string[]]$PatternsToRemove, [string[]]$ShouldBeRemoved, [string[]]$ShouldBePresent) + + (Get-Module -Name "Bar", "Baz", "Foo").Name | Should -BeExactly "Bar", "Baz", "Foo", "Foo" + + { Remove-Module -Name $PatternsToRemove -ErrorAction Stop } | Should -Throw -ErrorId "Modules_NoModulesRemoved,Microsoft.PowerShell.Commands.RemoveModuleCommand" + + if ($ShouldBeRemoved) { + (Get-Module -Name $ShouldBeRemoved).Name | Should -BeNullOrEmpty + } + + if ($ShouldBePresent) { + (Get-Module -Name $ShouldBePresent).Name | Should -BeExactly $ShouldBePresent + } + } + + It "Remove-Module -FullyQualifiedName " -TestCases $removeModuleByFQNTestCases { + param([Microsoft.PowerShell.Commands.ModuleSpecification[]]$FqnToRemove, [string[]]$ShouldBeRemoved, [string[]]$ShouldBePresent) + + (Get-Module -Name "Bar", "Baz", "Foo").Name | Should -BeExactly "Bar", "Baz", "Foo", "Foo" + + { Remove-Module -FullyQualifiedName $FqnToRemove } | Should -Not -Throw + + if ($ShouldBeRemoved) { + (Get-Module -Name $ShouldBeRemoved).Name | Should -BeNullOrEmpty + } + + if ($ShouldBePresent) { + (Get-Module -Name $ShouldBePresent).Name | Should -BeExactly $ShouldBePresent + } + } + + It "Remove-Module -FullyQualifiedName (Error cases)" -TestCases $removeModuleByFQNErrorTestCases { + param([Microsoft.PowerShell.Commands.ModuleSpecification[]]$FqnToRemove, [string[]]$ShouldBeRemoved, [string[]]$ShouldBePresent) + + (Get-Module -Name "Bar", "Baz", "Foo").Name | Should -BeExactly "Bar", "Baz", "Foo", "Foo" + + { Remove-Module -FullyQualifiedName $FqnToRemove -ErrorAction Stop } | Should -Throw -ErrorId "Modules_NoModulesRemoved,Microsoft.PowerShell.Commands.RemoveModuleCommand" + + if ($ShouldBeRemoved) { + (Get-Module -Name $ShouldBeRemoved).Name | Should -BeNullOrEmpty + } + + if ($ShouldBePresent) { + (Get-Module -Name $ShouldBePresent).Name | Should -BeExactly $ShouldBePresent + } + } + + It "Remove-Module -ModuleInfo " -TestCases $removeModuleByFQNTestCases { + param([Microsoft.PowerShell.Commands.ModuleSpecification[]]$FqnToRemove, [string[]]$ShouldBeRemoved, [string[]]$ShouldBePresent) + + (Get-Module -Name "Bar", "Baz", "Foo").Name | Should -BeExactly "Bar", "Baz", "Foo", "Foo" + + $modInfo = Get-Module -FullyQualifiedName $FqnToRemove + { Remove-Module -ModuleInfo $modInfo } | Should -Not -Throw + + if ($ShouldBeRemoved) { + (Get-Module -Name $ShouldBeRemoved).Name | Should -BeNullOrEmpty + } + + if ($ShouldBePresent) { + (Get-Module -Name $ShouldBePresent).Name | Should -BeExactly $ShouldBePresent + } + } + + It "Remove-Module -ModuleInfo (removing twice works)" { + (Get-Module -Name "Bar", "Baz", "Foo").Name | Should -BeExactly "Bar", "Baz", "Foo", "Foo" + + $modInfo = Get-Module -Name "Bar" + # Contrary to -Name and -FullyQualifiedName removing a non imported module works using ModuleInfo + { Remove-Module -ModuleInfo $modInfo } | Should -Not -Throw + { Remove-Module -ModuleInfo $modInfo } | Should -Not -Throw + } +} + +Describe "Remove-Module : module is readOnly | Constant" -Tags "CI" { + + BeforeAll { + Remove-Module -Force -Name "Foo", "Bar", "Baz" -ErrorAction SilentlyContinue + + New-Item -ItemType Directory -Path "$testdrive\Modules\Foo\" -Force > $null + New-Item -ItemType Directory -Path "$testdrive\Modules\Bar\" -Force > $null + New-Item -ItemType Directory -Path "$testdrive\Modules\Baz\" -Force > $null + + New-ModuleManifest -Path "$testdrive\Modules\Foo\Foo_ro.psd1" + New-ModuleManifest -Path "$testdrive\Modules\Foo\Foo_rw.psd1" + New-ModuleManifest -Path "$testdrive\Modules\Bar\Bar_rw.psd1" + New-ModuleManifest -Path "$testdrive\Modules\Baz\Baz_const.psd1" + + New-Item -ItemType File -Path "$testdrive\Modules\Foo\Foo_ro.psm1" > $null + New-Item -ItemType File -Path "$testdrive\Modules\Foo\Foo_rw.psm1" > $null + New-Item -ItemType File -Path "$testdrive\Modules\Bar\Bar_rw.psm1" > $null + New-Item -ItemType File -Path "$testdrive\Modules\Baz\Baz_const.psm1" > $null + + $removeReadOnlyModulesTestCases = @( + # Simple patterns + @{ NamesToRemove = "Foo_ro"; ShouldBeRemoved = ""; ShouldBePresent = "Bar_rw", "Baz_const", "Foo_ro", "Foo_rw"} + @{ NamesToRemove = "Foo_ro", "Foo_rw"; ShouldBeRemoved = "Foo_rw"; ShouldBePresent = "Bar_rw", "Baz_const", "Foo_ro"} + @{ NamesToRemove = "Bar_rw", "Foo_ro", "Foo_rw"; ShouldBeRemoved = "Bar_rw", "Foo_rw"; ShouldBePresent = "Baz_const", "Foo_ro"} + + # Regex patterns + @{ NamesToRemove = "Foo_*"; ShouldBeRemoved = "Foo_rw"; ShouldBePresent = "Bar_rw", "Baz_const", "Foo_ro"} + @{ NamesToRemove = "Foo_*", "Bar_*"; ShouldBeRemoved = "Bar_rw", "Foo_rw"; ShouldBePresent = "Baz_const", "Foo_ro"} + ) + + $removeForceReadOnlyModulesTestCases = @( + # Simple patterns + @{ NamesToRemove = "Foo_ro"; ShouldBeRemoved = "Foo_ro"; ShouldBePresent = "Bar_rw", "Baz_const", "Foo_rw"} + @{ NamesToRemove = "Foo_ro", "Foo_rw"; ShouldBeRemoved = "Foo_ro", "Foo_rw"; ShouldBePresent = "Bar_rw", "Baz_const"} + @{ NamesToRemove = "Bar_rw", "Foo_ro", "Foo_rw"; ShouldBeRemoved = "Bar_rw", "Foo_ro", "Foo_rw"; ShouldBePresent = "Baz_const"} + + # Regex patterns + @{ NamesToRemove = "Foo_*"; ShouldBeRemoved = "Foo_ro", "Foo_rw"; ShouldBePresent = "Bar_rw", "Baz_const"} + @{ NamesToRemove = "Foo_*", "Bar_*"; ShouldBeRemoved = "Bar_rw", "Foo_ro", "Foo_rw"; ShouldBePresent = "Baz_const"} + ) + + $removeConstantModulesTestCases = @( + # Simple patterns + @{ NamesToRemove = "Baz_const"; ShouldBeRemoved = ""; ShouldBePresent = "Bar_rw", "Baz_const", "Foo_ro", "Foo_rw"} + @{ NamesToRemove = "Baz_const", "Foo_ro", "Foo_rw"; ShouldBeRemoved = "Foo_ro", "Foo_rw"; ShouldBePresent = "Bar_rw", "Baz_const"} + + # Regex patterns + @{ NamesToRemove = "Foo_*", "Ba*"; ShouldBeRemoved = "Bar_rw", "Foo_ro", "Foo_rw"; ShouldBePresent = "Baz_const"} + ) + } + + AfterAll { + Remove-Module -Force -Name "Foo_*", "Ba*" -ErrorAction SilentlyContinue + } + + BeforeEach { + Import-Module -Name "$testdrive\Modules\Foo\Foo_ro.psd1" -Force + (Get-Module -Name "Foo_ro").AccessMode = "readOnly" + Import-Module -Name "$testdrive\Modules\Foo\Foo_rw.psd1" -Force + Import-Module -Name "$testdrive\Modules\Bar\Bar_rw.psd1" -Force + Import-Module -Name "$testdrive\Modules\Baz\Baz_const.psd1" -Force + (Get-Module -Name "Baz_const").AccessMode = "Constant" + } + + It "Remove-Module (ReadOnly modules): " -TestCases $removeReadOnlyModulesTestCases { + param([string[]]$NamesToRemove, [string[]]$ShouldBeRemoved, [string[]]$ShouldBePresent) + + (Get-Module -Name "Bar_rw", "Foo_ro", "Foo_rw").Name | Should -BeExactly "Bar_rw", "Foo_ro", "Foo_rw" + + { Remove-Module -Name $NamesToRemove -ErrorAction Stop } | Should -Throw -ErrorId "Modules_ModuleIsReadOnly,Microsoft.PowerShell.Commands.RemoveModuleCommand" + { Remove-Module -Name $NamesToRemove -ErrorAction SilentlyContinue } | Should -Not -Throw + + if ($ShouldBeRemoved) { + (Get-Module -Name $ShouldBeRemoved).Name | Should -BeNullOrEmpty + } + + if ($ShouldBePresent) { + (Get-Module -Name $ShouldBePresent).Name | Should -BeExactly $ShouldBePresent + } + } + + It "Remove-Module -Force (ReadOnly modules): " -TestCases $removeForceReadOnlyModulesTestCases { + param([string[]]$NamesToRemove, [string[]]$ShouldBeRemoved, [string[]]$ShouldBePresent) + + (Get-Module -Name "Bar_rw", "Foo_ro", "Foo_rw").Name | Should -BeExactly "Bar_rw", "Foo_ro", "Foo_rw" + + { Remove-Module -Force -Name $NamesToRemove -ErrorAction Stop } | Should -Not -Throw + + if ($ShouldBeRemoved) { + (Get-Module -Name $ShouldBeRemoved).Name | Should -BeNullOrEmpty + } + + if ($ShouldBePresent) { + (Get-Module -Name $ShouldBePresent).Name | Should -BeExactly $ShouldBePresent + } + } + + It "Remove-Module -Force (Constant modules): " -TestCases $removeConstantModulesTestCases { + param([string[]]$NamesToRemove, [string[]]$ShouldBeRemoved, [string[]]$ShouldBePresent) + + (Get-Module -Name "Bar_rw", "Baz_const", "Foo_ro", "Foo_rw").Name | Should -BeExactly "Bar_rw", "Baz_const", "Foo_ro", "Foo_rw" + + { Remove-Module -Force -Name $NamesToRemove -ErrorAction Stop } | Should -Throw -ErrorId "Modules_ModuleIsConstant,Microsoft.PowerShell.Commands.RemoveModuleCommand" + { Remove-Module -Force -Name $NamesToRemove -ErrorAction SilentlyContinue } | Should -Not -Throw + + if ($ShouldBeRemoved) { + (Get-Module -Name $ShouldBeRemoved).Name | Should -BeNullOrEmpty + } + + if ($ShouldBePresent) { + (Get-Module -Name $ShouldBePresent).Name | Should -BeExactly $ShouldBePresent + } + } +} + +Describe "Remove-Module : module provides the PSDrive for current PS Session" -Tags "CI" { + It "Remove-Module : module provides the PSDrive for current PS Session" { + + $module = Get-Module (Join-Path $PSHome "System.Management.Automation.dll") -ListAvailable + { Remove-Module $module -ErrorAction Stop } | Should -Throw -ErrorId "InvalidOperation,Microsoft.PowerShell.Commands.RemoveModuleCommand" + } +} + +Describe "Remove-Module : module contains nested modules" -Tags "CI" { + + BeforeAll { + Remove-Module -Force -Name "Foo", "Bar", "Baz" -ErrorAction SilentlyContinue + + New-Item -ItemType Directory -Path "$testdrive\Modules\Foo\" -Force > $null + New-Item -ItemType Directory -Path "$testdrive\Modules\Bar\" -Force > $null + New-Item -ItemType Directory -Path "$testdrive\Modules\Baz\" -Force > $null + + New-Item -ItemType File -Path "$testdrive\Modules\Foo\Foo.psm1" > $null + New-Item -ItemType File -Path "$testdrive\Modules\Bar\Bar.psm1" > $null + New-Item -ItemType File -Path "$testdrive\Modules\Baz\Baz.psm1" > $null + + Set-Content -Path "$testdrive\Modules\Foo\Foo.psm1" -Value "function FooFunc {}" + Set-Content -Path "$testdrive\Modules\Bar\Bar.psm1" -Value "function BarFunc {}" + } + + It "Remove-Module : module contains nested modules" { + New-ModuleManifest "$testdrive\Modules\Bar\Bar.psd1" -RootModule "./Bar.psm1" -FunctionsToExport "BarFunc" + New-ModuleManifest "$testdrive\Modules\Foo\Foo.psd1" -NestedModules "../Bar/Bar.psd1" -FunctionsToExport "BarFunc" + + Import-Module "$testdrive\Modules\Foo\Foo.psd1" -Force + (Get-Module -Name "Foo").Name | Should -BeExactly "Foo" + + { Get-Command BarFunc -ErrorAction Stop } | Should -Not -Throw + { Remove-Module -Name "Foo" -ErrorAction Stop } | Should -Not -Throw + { Get-Command BarFunc -ErrorAction Stop } | Should -Throw + (Get-Module -Name "Foo").Name | Should -BeNullOrEmpty + } + + It "Remove-Module : module contains nested modules with circular dependencies" { + New-ModuleManifest "$testdrive\Modules\Bar\Bar.psd1" -RootModule "Bar" -FunctionsToExport "BarFunc" -NestedModules "Bar" + + Import-Module "$testdrive\Modules\Bar\Bar.psd1" -Force + (Get-Module -Name "Bar").Name | Should -BeExactly "Bar" + + { Get-Command BarFunc -ErrorAction Stop } | Should -Not -Throw + { Remove-Module -Name "Bar" -ErrorAction Stop } | Should -Not -Throw + { Get-Command BarFunc -ErrorAction Stop } | Should -Throw + (Get-Module -Name "Bar").Name | Should -BeNullOrEmpty + } + + It "Remove-Module : modules are required by other modules" { + New-ModuleManifest "$testdrive\Modules\Bar\Bar.psd1" + New-ModuleManifest "$testdrive\Modules\Foo\Foo.psd1" -RequiredModules "Bar" + + Import-Module "$testdrive\Modules\Bar\Bar.psd1" -Force + Import-Module "$testdrive\Modules\Foo\Foo.psd1" -Force + (Get-Module -Name "Bar").Name | Should -BeExactly "Bar" + (Get-Module -Name "Foo").Name | Should -BeExactly "Foo" + + {Remove-Module "Foo" -ErrorAction Stop } | Should -Not -Throw + Import-Module "$testdrive\Modules\Foo\Foo.psd1" -Force + + { Remove-Module "Bar" -ErrorAction Stop } | Should -Throw -ErrorId "Modules_ModuleIsRequired,Microsoft.PowerShell.Commands.RemoveModuleCommand" + } +} + Describe "Remove-Module core module on module path by name" -Tags "CI" { $moduleName = "Microsoft.PowerShell.Security" BeforeEach { Import-Module -Name $moduleName -Force - (Get-Module -Name $moduleName).Name | Should -BeExactly $moduleName } It "should be able to remove a module with using Name switch" { + (Get-Module -Name $moduleName).Name | Should -BeExactly $moduleName + { Remove-Module -Name $moduleName } | Should -Not -Throw (Get-Module -Name $moduleName).Name | Should -BeNullOrEmpty } It "should be able to remove a module with using ModuleInfo switch" { + (Get-Module -Name $moduleName).Name | Should -BeExactly $moduleName + $a = Get-Module -Name $moduleName { Remove-Module -ModuleInfo $a } | Should -Not -Throw (Get-Module -Name $moduleName).Name | Should -BeNullOrEmpty @@ -44,13 +432,11 @@ Describe "Remove-Module custom module with FullyQualifiedName" -Tags "Feature" { @{ ModPath = "$TestDrive/Modules\$moduleName/$moduleName.psd1" } ) - BeforeEach { - Get-Module $moduleName | Remove-Module - } - It "Removes a module with fully qualified name with path " -TestCases $testCases -Pending { param([string]$ModPath) + Get-Module $moduleName | Remove-Module + $m = Import-Module $modulePath -PassThru $m.Name | Should -Be $moduleName diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Location.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Location.Tests.ps1 index 5824419f3b1..06be4473706 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Location.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Location.Tests.ps1 @@ -70,6 +70,23 @@ Describe "Set-Location" -Tags "CI" { Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand" } + It "Should use actual casing of folder on case-insensitive filesystem" -Skip:($IsLinux) { + $testPath = New-Item -ItemType Directory -Path testdrive:/teST + Set-Location $testPath.FullName.ToUpper() + $(Get-Location).Path | Should -BeExactly $testPath.FullName + } + + It "Should use actual casing of folder on case-sensitive filesystem: " -Skip:(!$IsLinux) { + $dir = "teST" + $testPathLower = New-Item -ItemType Directory -Path (Join-Path $TestDrive $dir.ToLower()) + $testPathUpper = New-Item -ItemType Directory -Path (Join-Path $TestDrive $dir.ToUpper()) + Set-Location $testPathLower.FullName + $(Get-Location).Path | Should -BeExactly $testPathLower.FullName + Set-Location $testPathUpper.FullName + $(Get-Location).Path | Should -BeExactly $testPathUpper.FullName + { Set-Location (Join-Path $TestDrive $dir) -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand" + } + Context 'Set-Location with no arguments' { It 'Should go to $env:HOME when Set-Location run with no arguments from FileSystem provider' { diff --git a/test/powershell/engine/ExperimentalFeature/EnableDisable-ExperimentalFeature.Tests.ps1 b/test/powershell/engine/ExperimentalFeature/EnableDisable-ExperimentalFeature.Tests.ps1 index 75f0fa49dcd..35792753fca 100644 --- a/test/powershell/engine/ExperimentalFeature/EnableDisable-ExperimentalFeature.Tests.ps1 +++ b/test/powershell/engine/ExperimentalFeature/EnableDisable-ExperimentalFeature.Tests.ps1 @@ -94,4 +94,14 @@ Describe "Enable-ExperimentalFeature and Disable-ExperimentalFeature tests" -tag & $cmdlet ExpTest.FeatureOne -WarningVariable warning -WarningAction SilentlyContinue $warning | Should -Not -BeNullOrEmpty -Because "A warning message is always given indicating restart is required" } + + It "Multiple features enabled will only output one warning message for " -TestCases @( + @{ cmdlet = "Enable-ExperimentalFeature" }, + @{ cmdlet = "Disable-Experimentalfeature" } + ) { + param ($cmdlet) + + Get-ExperimentalFeature | & $cmdlet -WarningAction SilentlyContinue -WarningVariable warning + $warning | Should -HaveCount 1 + } } diff --git a/tools/install-powershell.ps1 b/tools/install-powershell.ps1 index 606ae633047..f04ad09e4e9 100644 --- a/tools/install-powershell.ps1 +++ b/tools/install-powershell.ps1 @@ -131,31 +131,31 @@ Function Remove-Destination([string] $Destination) { #> function Test-PathNotInSettings($Path) { if ([string]::IsNullOrWhiteSpace($Path)) { - return $false + throw 'Argument is null' } # Remove ending DirectorySeparatorChar for comparison purposes $Path = [System.Environment]::ExpandEnvironmentVariables($Path.TrimEnd([System.IO.Path]::DirectorySeparatorChar)); if (-not [System.IO.Directory]::Exists($Path)) { - return $false + throw "Path does not exist: $Path" } # [System.Environment]::GetEnvironmentVariable automatically expands all variables [System.Array] $InstalledPaths = @() if ([System.Environment]::OSVersion.Platform -eq "Win32NT") { - $InstalledPaths += @(([System.Environment]::GetEnvironmentVariable('PATH', [System.EnvironmentVariableTarget]::User)).Split([System.IO.Path]::PathSeparator)) - $InstalledPaths += @(([System.Environment]::GetEnvironmentVariable('PATH', [System.EnvironmentVariableTarget]::Machine)).Split([System.IO.Path]::PathSeparator)) + $InstalledPaths += @(([System.Environment]::GetEnvironmentVariable('PATH', [System.EnvironmentVariableTarget]::User)) -split ([System.IO.Path]::PathSeparator)) + $InstalledPaths += @(([System.Environment]::GetEnvironmentVariable('PATH', [System.EnvironmentVariableTarget]::Machine)) -split ([System.IO.Path]::PathSeparator)) } else { - $InstalledPaths += @(([System.Environment]::GetEnvironmentVariable('PATH'), [System.EnvironmentVariableTarget]::Process).Split([System.IO.Path]::PathSeparator)) + $InstalledPaths += @(([System.Environment]::GetEnvironmentVariable('PATH'), [System.EnvironmentVariableTarget]::Process) -split ([System.IO.Path]::PathSeparator)) } # Remove ending DirectorySeparatorChar in all items of array for comparison purposes - $InstalledPaths = $InstalledPaths.ForEach( { $_.TrimEnd([System.IO.Path]::DirectorySeparatorChar) } ) + $InstalledPaths = $InstalledPaths | ForEach-Object { $_.TrimEnd([System.IO.Path]::DirectorySeparatorChar) } # if $InstalledPaths is in setting return false if ($InstalledPaths -icontains $Path) { - return $false + throw 'Already in PATH environment variable' } return $true @@ -370,7 +370,7 @@ try { try { Add-PathTToSettings -Path $Destination -Target $TargetRegistry } catch { - Write-Verbose -Message "Unable to save the new path in the machine wide registry." + Write-Warning -Message "Unable to save the new path in the machine wide registry: $_" $TargetRegistry = [System.EnvironmentVariableTarget]::User } } else { @@ -382,7 +382,7 @@ try { try { Add-PathTToSettings -Path $Destination -Target $TargetRegistry } catch { - Write-Verbose -Message "Unable to save the new path in the registry for the current user" + Write-Warning -Message "Unable to save the new path in the registry for the current user : $_" } } } else { diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index 4454b85b5b3..99f6bc95e0f 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -2811,19 +2811,30 @@ function New-MSIXPackage Set-Content -Path "$ProductSourcePath\AppxManifest.xml" -Value $appxManifest -Force # Necessary image assets need to be in source assets folder $assets = @( - 'Square150x150Logo.png' - 'Square44x44Logo.png' - 'Square44x44Logo.targetsize-48.png' - 'Square44x44Logo.targetsize-48_altform-unplated.png' - 'StoreLogo.png' + 'Square150x150Logo' + 'Square44x44Logo' + 'Square44x44Logo.targetsize-48' + 'Square44x44Logo.targetsize-48_altform-unplated' + 'StoreLogo' ) if (!(Test-Path "$ProductSourcePath\assets")) { $null = New-Item -ItemType Directory -Path "$ProductSourcePath\assets" } + $isPreview = Test-IsPreview -Version $ProductSemanticVersion + if ($isPreview) { + Write-Verbose "Using Preview assets" -Verbose + } + $assets | ForEach-Object { - Copy-Item -Path "$RepoRoot\assets\$_" -Destination "$ProductSourcePath\assets\" + if ($isPreview) { + Copy-Item -Path "$RepoRoot\assets\$_-Preview.png" -Destination "$ProductSourcePath\assets\$_.png" + } + else { + Copy-Item -Path "$RepoRoot\assets\$_.png" -Destination "$ProductSourcePath\assets\" + } + } if ($PSCmdlet.ShouldProcess("Create .msix package?")) { diff --git a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index ea180ca6863..72eb4cfcdac 100644 --- a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -13,7 +13,7 @@ - + diff --git a/tools/releaseBuild/azureDevOps/diagram.puml b/tools/releaseBuild/azureDevOps/diagram.puml index b72312ae504..ade53b11b9c 100644 --- a/tools/releaseBuild/azureDevOps/diagram.puml +++ b/tools/releaseBuild/azureDevOps/diagram.puml @@ -39,6 +39,8 @@ folder "Package Signing and Upload" as PkgSignUpload { folder "Build Test Artifacts" as TestArtifacts { agent "Windows" as WinTest agent "Linux" as LinuxTest + agent "Linux-ARM" as LinuxArmTest + agent "Linux-ARM64" as LinuxArm64Test } agent "Compliance" as Compliance diff --git a/tools/releaseBuild/azureDevOps/diagram.svg b/tools/releaseBuild/azureDevOps/diagram.svg index 5d1b162f1a8..024128bf988 100644 --- a/tools/releaseBuild/azureDevOps/diagram.svg +++ b/tools/releaseBuild/azureDevOps/diagram.svg @@ -1,4 +1,4 @@ -Linux BuildsWindows BuildsLinux Package Scanning and UploadPackage Signing and UploadBuild Test ArtifactsDEBRPMAlpineLinux-FxDependentx64x86arm32arm64FxDependentDEBRPMAlpineLinux-FxDependentmacOSWindowsWindowsLinuxmacOS BuildUpload build metadataComponentRegistrationComplianceCreate SDK and Global Tool and UploadFinishStartLinux BuildsWindows BuildsLinux Package Scanning and UploadPackage Signing and UploadBuild Test ArtifactsDEBRPMAlpineLinux-FxDependentx64x86arm32arm64FxDependentDEBRPMAlpineLinux-FxDependentmacOSWindowsWindowsLinuxLinux-ARMLinux-ARM64macOS BuildUpload build metadataComponentRegistrationComplianceCreate SDK and Global Tool and UploadFinishStart \ No newline at end of file diff --git a/tools/releaseBuild/azureDevOps/releaseBuild.yml b/tools/releaseBuild/azureDevOps/releaseBuild.yml index 481341d0939..be7714dd135 100644 --- a/tools/releaseBuild/azureDevOps/releaseBuild.yml +++ b/tools/releaseBuild/azureDevOps/releaseBuild.yml @@ -88,19 +88,6 @@ jobs: - build_macOS - template: templates/testartifacts.yml - parameters: - buildName: windows - pool: Hosted VS2017 - -- template: templates/testartifacts.yml - parameters: - buildName: linux - pool: Hosted Ubuntu 1604 - -- template: templates/testartifacts.yml - parameters: - buildName: macOS - pool: Hosted Mac Internal - job: release_json displayName: Create and Upload release.json diff --git a/tools/releaseBuild/azureDevOps/templates/testartifacts.yml b/tools/releaseBuild/azureDevOps/templates/testartifacts.yml index 8ebe18b0bbe..3e72ed7038d 100644 --- a/tools/releaseBuild/azureDevOps/templates/testartifacts.yml +++ b/tools/releaseBuild/azureDevOps/templates/testartifacts.yml @@ -1,12 +1,8 @@ -parameters: - buildName: 'linux' - pool: 'Hosted Ubuntu 1604' - jobs: -- job: build_testartifacts_${{ parameters.buildName }} - displayName: Build test artifacts ${{ parameters.buildName }} +- job: build_testartifacts + displayName: Build test artifacts condition: succeeded() - pool: ${{ parameters.pool }} + pool: 'Hosted Ubuntu 1604' steps: - pwsh: | @@ -16,26 +12,35 @@ jobs: - pwsh: | Import-Module ./build.psm1 - New-TestPackage -Destination $(System.ArtifactsDirectory) - displayName: Build test package - - pwsh: | - if (-not (Test-Path $(System.ArtifactsDirectory)/TestPackage.zip)) + function BuildTestPackage([string] $runtime) { - throw "Test Package was not found at: $(System.ArtifactsDirectory)" - } + Write-Verbose -Verbose "Starting to build package for $runtime" - $packageName = if ($IsWindows) { - "TestPackage-win.zip" - } - elseif ($IsLinux) { - "TestPackage-linux.zip" - } - else { - "TestPackage-macOS.zip" + New-TestPackage -Destination $(System.ArtifactsDirectory) -Runtime $runtime + + if (-not (Test-Path $(System.ArtifactsDirectory)/TestPackage.zip)) + { + throw "Test Package was not found at: $(System.ArtifactsDirectory)" + } + + switch ($runtime) + { + win7-x64 { $packageName = "TestPackage-win.zip" } + linux-x64 { $packageName = "TestPackage-linux-x64.zip" } + linux-arm { $packageName = "TestPackage-linux-arm.zip" } + linux-arm64 { $packageName = "TestPackage-linux-arm64.zip" } + osx-x64 { $packageName = "TestPackage-macOS.zip" } + } + + Rename-Item $(System.ArtifactsDirectory)/TestPackage.zip $packageName + Write-Host "##vso[artifact.upload containerfolder=testArtifacts;artifactname=testArtifacts]$(System.ArtifactsDirectory)/$packageName" } - Rename-Item $(System.ArtifactsDirectory)/TestPackage.zip $packageName + BuildTestPackage -runtime win7-x64 + BuildTestPackage -runtime linux-x64 + BuildTestPackage -runtime linux-arm + BuildTestPackage -runtime linux-arm64 + BuildTestPackage -runtime osx-x64 - Write-Host "##vso[artifact.upload containerfolder=testArtifacts;artifactname=testArtifacts]$(System.ArtifactsDirectory)/$packageName" - displayName: Upload to build artifacts + displayName: Build test package and upload