From 05943c6c48b3ce30711aa1100b97929888505884 Mon Sep 17 00:00:00 2001 From: Thomas Nieto <38873752+ThomasNieto@users.noreply.github.com> Date: Wed, 21 Jul 2021 20:05:06 -0500 Subject: [PATCH 01/55] Add position 0 to Write-Error parameters (#13813) --- .../commands/utility/Write.cs | 6 ++--- .../Write-Error.Tests.ps1 | 27 +++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs index bf907203544..40c4ec63568 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs @@ -214,7 +214,7 @@ public class WriteOrThrowErrorCommand : PSCmdlet /// /// ErrorRecord.Exception -- if not specified, ErrorRecord.Exception is System.Exception. /// - [Parameter(ParameterSetName = "WithException", Mandatory = true)] + [Parameter(Position = 0, ParameterSetName = "WithException", Mandatory = true)] public Exception Exception { get; set; } /// @@ -232,9 +232,9 @@ public class WriteOrThrowErrorCommand : PSCmdlet /// If Exception is specified, this is ErrorRecord.ErrorDetails.Message; /// otherwise, the Exception is System.Exception, and this is Exception.Message. /// - [Parameter(ParameterSetName = "ErrorRecord", Mandatory = true)] + [Parameter(Position = 0, ParameterSetName = "ErrorRecord", Mandatory = true)] public ErrorRecord ErrorRecord { get; set; } - + /// /// ErrorRecord.CategoryInfo.Category. /// diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 index ce52a59285a..d243ec07988 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 @@ -105,4 +105,31 @@ Describe "Write-Error Tests" -Tags "CI" { $result.Count | Should -BeExactly 3 $result[0] | Should -Match $longtext } + + It "Should be able to pass ErrorRecord to parameter position 0." { + try { + [int]::parse('foo') + } catch { } + + (Write-Error $Error[0] 2>&1).Exception.GetType().FullName | + Should -Be System.Management.Automation.MethodInvocationException + } + + It "Should be able to pass Exception to parameter position 0." { + try { + [int]::parse('foo') + } catch { } + + (Write-Error $Error[0].Exception.InnerException 2>&1).Exception.GetType().FullName | + Should -Be System.FormatException + } + + It "Should be able to pass string to parameter position 0." { + try { + [int]::parse('foo') + } catch { } + + (Write-Error "$($Error[0])" 2>&1).Exception.GetType().FullName | + Should -Be Microsoft.PowerShell.Commands.WriteErrorException + } } From efa9b251931e80d6e6be303180c7f7f68338ce00 Mon Sep 17 00:00:00 2001 From: "Joel Sallow (/u/ta11ow)" <32407840+vexx32@users.noreply.github.com> Date: Thu, 22 Jul 2021 00:05:17 -0400 Subject: [PATCH 02/55] ConvertTo-Csv / Export-Csv - Serialize IDictionary objects with key/value pairs as properties (#11029) --- .../commands/utility/CsvCommands.cs | 62 +++++++++++++++---- .../ConvertTo-Csv.Tests.ps1 | 42 +++++++++++-- 2 files changed, 88 insertions(+), 16 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index cbd9d4c36b4..96659dcf7e5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System; +using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; @@ -737,14 +738,18 @@ protected override void ProcessRecord() // Write property information string properties = _helper.ConvertPropertyNamesCSV(_propertyNames); if (!properties.Equals(string.Empty)) + { WriteCsvLine(properties); + } } string csv = _helper.ConvertPSObjectToCSV(InputObject, _propertyNames); - // write to the console + // Write to the output stream if (csv != string.Empty) + { WriteCsvLine(csv); + } } #endregion Overrides @@ -908,16 +913,36 @@ internal static IList BuildPropertyNames(PSObject source, IList throw new InvalidOperationException(CsvCommandStrings.BuildPropertyNamesMethodShouldBeCalledOnlyOncePerCmdletInstance); } - // serialize only Extended and Adapted properties.. - PSMemberInfoCollection srcPropertiesToSearch = - new PSMemberInfoIntegratingCollection( + propertyNames = new Collection(); + if (source.BaseObject is IDictionary dictionary) + { + foreach (var key in dictionary.Keys) + { + propertyNames.Add(LanguagePrimitives.ConvertTo(key)); + } + + // Add additional extended members added to the dictionary object, if any + var propertiesToSearch = new PSMemberInfoIntegratingCollection( source, - PSObject.GetPropertyCollection(PSMemberViewTypes.Extended | PSMemberViewTypes.Adapted)); + PSObject.GetPropertyCollection(PSMemberViewTypes.Extended)); - propertyNames = new Collection(); - foreach (PSPropertyInfo prop in srcPropertiesToSearch) + foreach (var prop in propertiesToSearch) + { + propertyNames.Add(prop.Name); + } + } + else { - propertyNames.Add(prop.Name); + // serialize only Extended and Adapted properties. + PSMemberInfoCollection srcPropertiesToSearch = + new PSMemberInfoIntegratingCollection( + source, + PSObject.GetPropertyCollection(PSMemberViewTypes.Extended | PSMemberViewTypes.Adapted)); + + foreach (PSPropertyInfo prop in srcPropertiesToSearch) + { + propertyNames.Add(prop.Name); + } } return propertyNames; @@ -1014,11 +1039,26 @@ internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyN _outputString.Append(_delimiter); } - // If property is not present, assume value is null and skip it. - if (mshObject.Properties[propertyName] is PSPropertyInfo property) + string value = null; + if (mshObject.BaseObject is IDictionary dictionary) { - var value = GetToStringValueForProperty(property); + if (dictionary.Contains(propertyName)) + { + value = dictionary[propertyName].ToString(); + } + else if (mshObject.Properties[propertyName] is PSPropertyInfo property) + { + value = GetToStringValueForProperty(property); + } + } + else if (mshObject.Properties[propertyName] is PSPropertyInfo property) + { + value = GetToStringValueForProperty(property); + } + // If value is null, assume property is not present and skip it. + if (value != null) + { if (_quoteFields != null) { if (_quoteFields.TryGetValue(propertyName, out _)) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 index 494051507f7..6b744b8eb88 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 @@ -49,7 +49,7 @@ Describe "ConvertTo-Csv" -Tags "CI" { It "Should output an array of objects" { $result = $testObject | ConvertTo-Csv - ,$result | Should -BeOfType System.Array + $result.GetType() | Should -Be ([object[]]) } It "Should return the type of data in the first element of the output array" { @@ -59,16 +59,16 @@ Describe "ConvertTo-Csv" -Tags "CI" { } It "Should return the column info in the second element of the output array" { - $result = $testObject | ConvertTo-Csv -IncludeTypeInformation + $result = $testObject | ConvertTo-Csv -IncludeTypeInformation $result[1] | Should -Match "`"FirstColumn`"" - $result[1] | Should -Match "`"SecondColumn`"" + $result[1] | Should -Match "`"SecondColumn`"" } It "Should return the data as a comma-separated list in the third element of the output array" { $result = $testObject | ConvertTo-Csv -IncludeTypeInformation $result[2] | Should -Match "`"Hello`"" - $result[2] | Should -Match "`"World`"" + $result[2] | Should -Match "`"World`"" } It "Includes type information when -IncludeTypeInformation is supplied" { @@ -109,7 +109,7 @@ Describe "ConvertTo-Csv" -Tags "CI" { $result[0] | Should -BeExactly "`"FirstColumn`",SecondColumn" $result[1] | Should -BeExactly "`"Hello`",World" - $result = $testObject | ConvertTo-Csv -QuoteFields FiRstCoLumn,SeCondCoLumn -Delimiter ',' + $result = $testObject | ConvertTo-Csv -QuoteFields FiRstCoLumn, SeCondCoLumn -Delimiter ',' $result[0] | Should -BeExactly "`"FirstColumn`",`"SecondColumn`"" $result[1] | Should -BeExactly "`"Hello`",`"World`"" @@ -160,4 +160,36 @@ Describe "ConvertTo-Csv" -Tags "CI" { $result[1] | Should -BeExactly "Hellor" } } + + Context 'Converting IDictionary Objects' { + BeforeAll { + $Letters = 'A', 'B', 'C', 'D', 'E', 'F' + $Items = 0..5 | ForEach-Object { + [ordered]@{ Number = $_; Letter = $Letters[$_] } + } + $CsvString = $Items | ConvertTo-Csv + } + + It 'should treat dictionary entries as properties' { + $CsvString[0] | Should -MatchExactly ($Items[0].Keys -join '","') + + for ($i = 0; $i -lt $Items.Count; $i++) { + # Index in the CSV strings will be +1 due to header line + $ValuesPattern = $Items[$i].Values -join '","' + $CsvString[$i + 1] | Should -MatchExactly $ValuesPattern + } + } + + It 'should ignore regular object properties' { + $PropertyPattern = $Items[0].PSObject.Properties.Name -join '|' + $CsvString[0] | Should -Not -Match $PropertyPattern + } + + It 'should account for extended properties added deliberately' { + $Items | Add-Member -MemberType NoteProperty -Name 'Extra' -Value 'Surprise!' + $NewCsvString = $Items | ConvertTo-Csv + $NewCsvString[0] | Should -MatchExactly 'Extra' + $NewCsvString | Select-Object -Skip 1 | Should -MatchExactly 'Surprise!' + } + } } From de5dc633791fbb66574851acb02c2c134ad3612d Mon Sep 17 00:00:00 2001 From: Peter Schneider Date: Thu, 22 Jul 2021 06:26:07 +0200 Subject: [PATCH 03/55] Encoding Parameter for Tee-Object (#12135) --- .../commands/utility/Tee-Object.cs | 13 ++++++++ .../Tee-Object.Tests.ps1 | 30 +++++++++++++++---- 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs index 78ca964d408..a23b0be61dc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs @@ -3,6 +3,7 @@ using System; using System.Management.Automation; +using System.Text; using Microsoft.PowerShell.Commands.Internal.Format; @@ -72,6 +73,16 @@ public SwitchParameter Append private bool _append; + /// + /// Gets or sets the Encoding. + /// + [Parameter(ParameterSetName = "File")] + [Parameter(ParameterSetName = "LiteralFile")] + [ArgumentToEncodingTransformationAttribute] + [ArgumentEncodingCompletionsAttribute] + [ValidateNotNullOrEmpty] + public Encoding Encoding { get; set; } = ClrFacade.GetDefaultEncoding(); + /// /// Variable parameter. /// @@ -95,12 +106,14 @@ protected override void BeginProcessing() _commandWrapper.Initialize(Context, "out-file", typeof(OutFileCommand)); _commandWrapper.AddNamedParameter("filepath", _fileName); _commandWrapper.AddNamedParameter("append", _append); + _commandWrapper.AddNamedParameter("encoding", Encoding); } else if (string.Equals(ParameterSetName, "LiteralFile", StringComparison.OrdinalIgnoreCase)) { _commandWrapper.Initialize(Context, "out-file", typeof(OutFileCommand)); _commandWrapper.AddNamedParameter("LiteralPath", _fileName); _commandWrapper.AddNamedParameter("append", _append); + _commandWrapper.AddNamedParameter("encoding", Encoding); } else { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Tee-Object.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Tee-Object.Tests.ps1 index 01527be8435..7483c4d8004 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Tee-Object.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Tee-Object.Tests.ps1 @@ -4,21 +4,39 @@ Describe "Tee-Object" -Tags "CI" { Context "Validate Tee-Object is correctly forking output" { - $testfile = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath assets) -ChildPath testfile.txt + BeforeAll { + $testfile = Join-Path $TestDrive -ChildPath "testfile.txt" + $testvalue = "ф" + if ($IsWindows) { + # Expected bytes: 244 - 'ф', 13 - '`r', 10 - '`n'. + $expectedBytes = 244,13,10 -join "-" + } else { + $expectedBytes = 244,10 -join "-" + } + } + + BeforeEach { + Remove-Item -Path $testfile -ErrorAction SilentlyContinue -Force + } It "Should return the output to the screen and to the variable" { - $teefile = $testfile Write-Output teeobjecttest1 | Tee-Object -Variable teeresults - $teeresults | Should -BeExactly "teeobjecttest1" - Remove-Item $teefile -ErrorAction SilentlyContinue + $teeresults | Should -BeExactly "teeobjecttest1" } It "Should tee the output to a file" { $teefile = $testfile Write-Output teeobjecttest3 | Tee-Object $teefile Get-Content $teefile | Should -BeExactly "teeobjecttest3" - Remove-Item $teefile -ErrorAction SilentlyContinue - } + } + + It "Parameter 'Encoding' should accept encoding" { + $teefile = $testfile + $encoding = 1251 + $testvalue | Tee-Object -Encoding $encoding $teefile + Get-Content $teefile -Encoding $encoding | Should -BeExactly $testvalue + (Get-Content $teefile -AsByteStream) -join "-" | Should -BeExactly $expectedBytes + } } } From 0002f7e8be6301808027ae327032c33c9e9e9cd9 Mon Sep 17 00:00:00 2001 From: Seth Falco Date: Thu, 22 Jul 2021 07:30:29 +0200 Subject: [PATCH 04/55] EditorConfig: don't replace tabs with spaces in tsv files (#15815) --- .editorconfig | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.editorconfig b/.editorconfig index 6fd562d452d..517c9656ba6 100644 --- a/.editorconfig +++ b/.editorconfig @@ -44,6 +44,9 @@ indent_size = 2 [*.{props,targets,config,nuspec}] indent_size = 2 +[*.tsv] +indent_style = tab + # Dotnet code style settings: [*.cs] # Sort using and Import directives with System.* appearing first From 7777afc00501079539cbf41a18434c6ea243b4a4 Mon Sep 17 00:00:00 2001 From: Thomas Nieto <38873752+ThomasNieto@users.noreply.github.com> Date: Thu, 22 Jul 2021 12:17:53 -0500 Subject: [PATCH 05/55] Add `-PassThru` parameter to `Set-Clipboard` (#13713) --- .../management/SetClipboardCommand.cs | 12 +++++++ .../Clipboard.Tests.ps1 | 31 +++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs index b53ffeb01b3..69cea8361a8 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs @@ -17,6 +17,7 @@ namespace Microsoft.PowerShell.Commands /// [Cmdlet(VerbsCommon.Set, "Clipboard", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2109826")] [Alias("scb")] + [OutputType(typeof(string))] public class SetClipboardCommand : PSCmdlet { private readonly List _contentList = new(); @@ -37,6 +38,12 @@ public class SetClipboardCommand : PSCmdlet [Parameter] public SwitchParameter Append { get; set; } + /// + /// Gets or sets if the values sent down the pipeline. + /// + [Parameter] + public SwitchParameter PassThru { get; set; } + /// /// This method implements the BeginProcessing method for Set-Clipboard command. /// @@ -53,6 +60,11 @@ protected override void ProcessRecord() if (Value != null) { _contentList.AddRange(Value); + + if (PassThru) + { + WriteObject(Value); + } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Clipboard.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Clipboard.Tests.ps1 index 8cfc07b8755..7cd4f492bfa 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Clipboard.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Clipboard.Tests.ps1 @@ -51,5 +51,36 @@ Describe 'Clipboard cmdlet tests' -Tag CI { $text | Set-Clipboard Get-Clipboard -Raw | Should -BeNullOrEmpty } + + It 'Set-Clipboard should not return object' { + $result = 'hello' | Set-Clipboard + $result | Should -BeNullOrEmpty + } + + It 'Set-Clipboard -PassThru returns single object with -Append = ' -TestCases @( + @{ Append = $false } + @{ Append = $true } + ){ + param ($append) + + $params = @{ PassThru = $true; Append = $append } + + Set-Clipboard -Value 'world' + $result = 'hello' | Set-Clipboard @params + $result | Should -BeExactly 'hello' + } + + It 'Set-Clipboard -PassThru returns multiple objects with -Append = ' -TestCases @( + @{ Append = $false } + @{ Append = $true } + ){ + param ($append) + + $params = @{ PassThru = $true; Append = $append } + + Set-Clipboard -Value 'world' + $result = 'hello', 'world' | Set-Clipboard @params + $result | Should -BeExactly @('hello', 'world') + } } } From 10dee693e19c686f497fec726f29088570177eb7 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Thu, 22 Jul 2021 10:21:45 -0700 Subject: [PATCH 06/55] Enable `/rebase` to automatically rebase a PR (#15808) --- .github/workflows/rebase.yml | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 .github/workflows/rebase.yml diff --git a/.github/workflows/rebase.yml b/.github/workflows/rebase.yml new file mode 100644 index 00000000000..f54254f1435 --- /dev/null +++ b/.github/workflows/rebase.yml @@ -0,0 +1,21 @@ +# This cannot rebase workflow changes into a PR +# It also only works if the GITHUB_TOKEN has permission to push to the branch +# see: https://github.com/cirrus-actions/rebase/issues/12#issuecomment-632594995 +on: + issue_comment: + types: [created] +name: Automatic Rebase +jobs: + rebase: + name: Rebase + if: github.event.issue.pull_request != '' && contains(github.event.comment.body, '/rebase') + runs-on: ubuntu-latest + steps: + - name: Checkout the latest code + uses: actions/checkout@v2 + with: + fetch-depth: 0 + - name: Automatic Rebase + uses: cirrus-actions/rebase@1.4 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 0d30ebaae95c9650ce1df6772911417261ac3bbf Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 22 Jul 2021 17:02:01 -0700 Subject: [PATCH 07/55] Update README and metadata files for release `v7.2.0-preview.8` (#15819) --- DotnetRuntimeMetadata.json | 6 +++--- README.md | 30 +++++++++++++++++------------- tools/metadata.json | 4 ++-- 3 files changed, 22 insertions(+), 18 deletions(-) diff --git a/DotnetRuntimeMetadata.json b/DotnetRuntimeMetadata.json index c66ef76c639..e7a597bae5a 100644 --- a/DotnetRuntimeMetadata.json +++ b/DotnetRuntimeMetadata.json @@ -1,11 +1,11 @@ { "sdk": { - "channel": "6.0.1xx-preview4", + "channel": "6.0.1xx-preview6", "quality": "signed", "qualityFallback": "daily", - "packageVersionPattern": "6.0.0-preview.4", + "packageVersionPattern": "6.0.0-preview.6", "sdkImageVersion": "6.0.100", - "nextChannel": "6.0.1xx-preview6" + "nextChannel": "6.0.1xx-preview7" }, "internalfeed" : { "url": null diff --git a/README.md b/README.md index 621f0f9f0ed..6a4bab807cf 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,8 @@ You can download and install a PowerShell package for any of the following platf | [Red Hat Enterprise Linux 7][corefx-linux] | [.rpm][lts-centos] | [.rpm][rl-centos] | [.rpm][pv-rpm] | [Instructions][in-rhel7] | | [openSUSE 42.3][corefx-linux] | [.rpm][lts-centos] | [.rpm][rl-centos] | [.rpm][pv-rpm] | [Instructions][in-opensuse] | | [Fedora 30][corefx-linux] | [.rpm][lts-centos] | [.rpm][rl-centos] | [.rpm][pv-rpm] | [Instructions][in-fedora] | -| [macOS 10.13+][corefx-macos] | [.pkg][lts-macos] | [.pkg][rl-macos] | [.pkg][pv-macos] | [Instructions][in-macos] | +| [macOS 10.13+ (x64)][corefx-macos] | [.pkg][lts-macos] | [.pkg][rl-macos] | [.pkg][pv-macos] | [Instructions][in-macos] | +| [macOS 10.13+ (arm64)][corefx-macos] | | | [.pkg][pv-macos-arm64]| [Instructions][in-macos] | | Docker | | | | [Instructions][in-docker] | You can download and install a PowerShell package for any of the following platforms, **which are supported by the community.** @@ -58,6 +59,7 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu | ---------------| --------------------------------------------------- | ------------------------------------------------| -----------------------------------------------| | Windows | [32-bit][rl-winx86-zip]/[64-bit][rl-winx64-zip] | [32-bit][pv-winx86-zip]/[64-bit][pv-winx64-zip] | [Instructions][in-windows-zip] | | macOS | [64-bit][rl-macos-tar] | [64-bit][pv-macos-tar] | [Instructions][in-tar-macos] | +| macOS | | [64-bit][pv-macos-tar-arm64] | [Instructions][in-tar-macos] | | Linux | [64-bit][rl-linux-tar] | [64-bit][pv-linux-tar] | [Instructions][in-tar-linux] | | Windows (Arm) | [64-bit][rl-winarm64] (preview) | [64-bit][pv-winarm64] | [Instructions][in-arm] | | Raspbian (Arm) | [32-bit][rl-arm32]/[64-bit][rl-arm64] | [32-bit][pv-arm32]/[64-bit][pv-arm64] | [Instructions][in-raspbian] | @@ -92,18 +94,20 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu [rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell-7.1.3-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell -[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.7/PowerShell-7.2.0-preview.7-win-x64.msi -[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.7/PowerShell-7.2.0-preview.7-win-x86.msi -[pv-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.7/powershell-preview_7.2.0-preview.7-1.deb_amd64.deb -[pv-rpm]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.7/powershell-preview-7.2.0_preview.7-1.rh.x86_64.rpm -[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.7/powershell-7.2.0-preview.7-osx-x64.pkg -[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.7/PowerShell-7.2.0-preview.7-win-arm64.zip -[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.7/PowerShell-7.2.0-preview.7-win-x86.zip -[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.7/PowerShell-7.2.0-preview.7-win-x64.zip -[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.7/powershell-7.2.0-preview.7-osx-x64.tar.gz -[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.7/powershell-7.2.0-preview.7-linux-x64.tar.gz -[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.7/powershell-7.2.0-preview.7-linux-arm32.tar.gz -[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.7/powershell-7.2.0-preview.7-linux-arm64.tar.gz +[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.8/PowerShell-7.2.0-preview.8-win-x64.msi +[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.8/PowerShell-7.2.0-preview.8-win-x86.msi +[pv-deb]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.8/powershell-preview_7.2.0-preview.8-1.deb_amd64.deb +[pv-rpm]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.8/powershell-preview-7.2.0_preview.8-1.rh.x86_64.rpm +[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.8/powershell-7.2.0-preview.8-osx-x64.pkg +[pv-macos-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.8/powershell-7.2.0-preview.8-osx-arm64.pkg +[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.8/PowerShell-7.2.0-preview.8-win-arm64.zip +[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.8/PowerShell-7.2.0-preview.8-win-x86.zip +[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.8/PowerShell-7.2.0-preview.8-win-x64.zip +[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.8/powershell-7.2.0-preview.8-osx-x64.tar.gz +[pv-macos-tar-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.8/powershell-7.2.0-preview.8-osx-arm64.tar.gz +[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.8/powershell-7.2.0-preview.8-linux-x64.tar.gz +[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.8/powershell-7.2.0-preview.8-linux-arm32.tar.gz +[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.8/powershell-7.2.0-preview.8-linux-arm64.tar.gz [pv-snap]: https://snapcraft.io/powershell-preview [in-windows]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows diff --git a/tools/metadata.json b/tools/metadata.json index 88d872d9ebb..e8e37b57379 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,9 +1,9 @@ { "StableReleaseTag": "v7.1.3", - "PreviewReleaseTag": "v7.2.0-preview.7", + "PreviewReleaseTag": "v7.2.0-preview.8", "ServicingReleaseTag": "v7.0.6", "ReleaseTag": "v7.1.3", "LTSReleaseTag" : ["v7.0.6"], - "NextReleaseTag": "v7.2.0-preview.8", + "NextReleaseTag": "v7.2.0-preview.9", "LTSRelease": false } From 6a21bcc96766a32888bfc8a1aa24e30e21877b8f Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Fri, 23 Jul 2021 05:07:36 +0100 Subject: [PATCH 08/55] Specify api_surface property for all code quality rules (#15778) --- .globalconfig | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/.globalconfig b/.globalconfig index 8e671a5b372..f2201141f97 100644 --- a/.globalconfig +++ b/.globalconfig @@ -25,10 +25,12 @@ dotnet_diagnostic.CA1005.severity = none # CA1008: Enums should have zero value # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1008 dotnet_diagnostic.CA1008.severity = none +dotnet_code_quality.CA1008.api_surface = public # CA1010: Generic interface should also be implemented # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1010 dotnet_diagnostic.CA1010.severity = silent +dotnet_code_quality.CA1010.api_surface = public # CA1012: Abstract types should not have public constructors # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1012 @@ -62,18 +64,22 @@ dotnet_diagnostic.CA1021.severity = none # CA1024: Use properties where appropriate # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1024 dotnet_diagnostic.CA1024.severity = none +dotnet_code_quality.CA1024.api_surface = public # CA1027: Mark enums with FlagsAttribute # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1027 dotnet_diagnostic.CA1027.severity = none +dotnet_code_quality.CA1027.api_surface = public # CA1028: Enum Storage should be Int32 # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1028 dotnet_diagnostic.CA1028.severity = none +dotnet_code_quality.CA1028.api_surface = public # CA1030: Use events where appropriate # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1030 dotnet_diagnostic.CA1030.severity = none +dotnet_code_quality.CA1030.api_surface = public # CA1031: Do not catch general exception types # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1031 @@ -94,23 +100,27 @@ dotnet_diagnostic.CA1034.severity = none # CA1036: Override methods on comparable types # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1036 dotnet_diagnostic.CA1036.severity = silent +dotnet_code_quality.CA1036.api_surface = public # CA1040: Avoid empty interfaces # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1040 dotnet_diagnostic.CA1040.severity = none +dotnet_code_quality.CA1040.api_surface = public # CA1041: Provide ObsoleteAttribute message # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1041 dotnet_diagnostic.CA1041.severity = warning +dotnet_code_quality.CA1041.api_surface = public # CA1043: Use Integral Or String Argument For Indexers # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1043 dotnet_diagnostic.CA1043.severity = warning -dotnet_code_quality.ca1043.api_surface = all +dotnet_code_quality.CA1043.api_surface = all # CA1044: Properties should not be write only # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1044 dotnet_diagnostic.CA1044.severity = none +dotnet_code_quality.CA1044.api_surface = public # CA1045: Do not pass types by reference # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1045 @@ -131,6 +141,7 @@ dotnet_diagnostic.CA1050.severity = warning # CA1051: Do not declare visible instance fields # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1051 dotnet_diagnostic.CA1051.severity = silent +dotnet_code_quality.CA1051.api_surface = public # CA1052: Static holder types should be Static or NotInheritable # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1052 @@ -140,18 +151,22 @@ dotnet_code_quality.CA1052.api_surface = private, internal # CA1054: URI-like parameters should not be strings # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1054 dotnet_diagnostic.CA1054.severity = none +dotnet_code_quality.CA1054.api_surface = public # CA1055: URI-like return values should not be strings # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1055 dotnet_diagnostic.CA1055.severity = none +dotnet_code_quality.CA1055.api_surface = public # CA1056: URI-like properties should not be strings # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1056 dotnet_diagnostic.CA1056.severity = none +dotnet_code_quality.CA1056.api_surface = public # CA1058: Types should not extend certain base types # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1058 dotnet_diagnostic.CA1058.severity = none +dotnet_code_quality.CA1058.api_surface = public # CA1060: Move pinvokes to native methods class # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1060 @@ -168,6 +183,7 @@ dotnet_diagnostic.CA1062.severity = none # CA1063: Implement IDisposable Correctly # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1063 dotnet_diagnostic.CA1063.severity = none +dotnet_code_quality.CA1063.api_surface = public # CA1064: Exceptions should be public # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1064 @@ -284,14 +300,17 @@ dotnet_diagnostic.CA1707.severity = silent # CA1708: Identifiers should differ by more than case # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1708 dotnet_diagnostic.CA1708.severity = silent +dotnet_code_quality.CA1708.api_surface = public # CA1710: Identifiers should have correct suffix # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1710 dotnet_diagnostic.CA1710.severity = silent +dotnet_code_quality.CA1710.api_surface = public # CA1711: Identifiers should not have incorrect suffix # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1711 dotnet_diagnostic.CA1711.severity = silent +dotnet_code_quality.CA1711.api_surface = public # CA1712: Do not prefix enum values with type name # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1712 @@ -304,18 +323,22 @@ dotnet_diagnostic.CA1713.severity = none # CA1715: Identifiers should have correct prefix # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1715 dotnet_diagnostic.CA1715.severity = silent +dotnet_code_quality.CA1715.api_surface = public # CA1716: Identifiers should not match keywords # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1716 dotnet_diagnostic.CA1716.severity = silent +dotnet_code_quality.CA1716.api_surface = public # CA1720: Identifier contains type name # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1720 dotnet_diagnostic.CA1720.severity = silent +dotnet_code_quality.CA1720.api_surface = public # CA1721: Property names should not match get methods # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1721 dotnet_diagnostic.CA1721.severity = none +dotnet_code_quality.CA1721.api_surface = public # CA1724: Type names should not match namespaces # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1724 @@ -324,14 +347,17 @@ dotnet_diagnostic.CA1724.severity = none # CA1725: Parameter names should match base declaration # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1725 dotnet_diagnostic.CA1725.severity = silent +dotnet_code_quality.CA1725.api_surface = public # CA1801: Review unused parameters # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1801 dotnet_diagnostic.CA1801.severity = none +dotnet_code_quality.CA1801.api_surface = all # CA1802: Use literals where appropriate # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1802 dotnet_diagnostic.CA1802.severity = none +dotnet_code_quality.CA1802.api_surface = public # CA1805: Do not initialize unnecessarily # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1805 @@ -360,6 +386,7 @@ dotnet_diagnostic.CA1814.severity = none # CA1815: Override equals and operator equals on value types # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1815 dotnet_diagnostic.CA1815.severity = none +dotnet_code_quality.CA1815.api_surface = public # CA1816: Dispose methods should call SuppressFinalize # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1816 @@ -368,6 +395,7 @@ dotnet_diagnostic.CA1816.severity = warning # CA1819: Properties should not return arrays # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1819 dotnet_diagnostic.CA1819.severity = none +dotnet_code_quality.CA1819.api_surface = public # CA1820: Test for empty strings using string length # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1820 @@ -557,6 +585,7 @@ dotnet_diagnostic.CA2207.severity = warning # CA2208: Instantiate argument exceptions correctly # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2208 dotnet_diagnostic.CA2208.severity = suggestion +dotnet_code_quality.CA2208.api_surface = all # CA2211: Non-constant fields should not be visible # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2211 @@ -581,6 +610,7 @@ dotnet_diagnostic.CA2216.severity = warning # CA2217: Do not mark enums with FlagsAttribute # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2217 dotnet_diagnostic.CA2217.severity = none +dotnet_code_quality.CA2217.api_surface = public # CA2218: Override GetHashCode on overriding Equals # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2218 @@ -597,10 +627,12 @@ dotnet_diagnostic.CA2224.severity = suggestion # CA2225: Operator overloads have named alternates # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2225 dotnet_diagnostic.CA2225.severity = none +dotnet_code_quality.CA2225.api_surface = public # CA2226: Operators should have symmetrical overloads # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2226 dotnet_diagnostic.CA2226.severity = none +dotnet_code_quality.CA2226.api_surface = public # CA2227: Collection properties should be read only # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2227 @@ -613,10 +645,12 @@ dotnet_diagnostic.CA2229.severity = silent # CA2231: Overload operator equals on overriding value type Equals # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2231 dotnet_diagnostic.CA2231.severity = suggestion +dotnet_code_quality.CA2231.api_surface = public # CA2234: Pass system uri objects instead of strings # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2234 dotnet_diagnostic.CA2234.severity = none +dotnet_code_quality.CA2234.api_surface = public # CA2235: Mark all non-serializable fields # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2235 From af19ece88ae246da0fab523d5b59930155475cf2 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Mon, 26 Jul 2021 11:35:01 -0700 Subject: [PATCH 09/55] Update spelling exceptions for latest changelog (#15829) --- .spelling | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.spelling b/.spelling index 112c482fe21..0784aad4ad1 100644 --- a/.spelling +++ b/.spelling @@ -1103,6 +1103,20 @@ DotnetMetadataRuntime.json deps.json Jaykul eltociear +consolehost.proto +IDisposable +ConvertToJsonCommand +CommandPathSearch +UseCoalesceExpression +UseSystemHashCode +UseCoalesceExpressionForNullable +substring +RemoveAll +MakeFieldReadonly +Microsoft.Management.UI.Internal +StringComparison +osx-arm64 +crossgen2 - CHANGELOG.md aavdberg asrosent From 5e15f66f977db10431821e39ed23d774d9d9550d Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Tue, 27 Jul 2021 10:14:20 -0700 Subject: [PATCH 10/55] Add validation to `$PSStyle` to reject printable text as ANSI escape sequence (#15825) --- .../PowerShellCore_format_ps1xml.cs | 2 +- .../FormatAndOutput/common/PSStyle.cs | 212 ++++++++++++++++-- .../resources/PSStyleStrings.resx | 70 ++++++ .../engine/Formatting/PSStyle.Tests.ps1 | 71 ++++++ 4 files changed, 340 insertions(+), 15 deletions(-) create mode 100644 src/System.Management.Automation/resources/PSStyleStrings.resx diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index ddad10cfc5e..2d9cab7b0c2 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -2127,7 +2127,7 @@ private static IEnumerable ViewsOf_System_Management_Autom .AddItemScriptBlock(@"""$($_.ErrorAccent)$($_.ErrorAccent.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "ErrorAccent") .AddItemScriptBlock(@"""$($_.Error)$($_.Error.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Error") .AddItemScriptBlock(@"""$($_.Warning)$($_.Warning.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Warning") - .AddItemScriptBlock(@"""$($_.Verbose)$($_.Verbose.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Verbose") + .AddItemScriptBlock(@"""$($_.Verbose)$($_.Verbose.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Verbose") .AddItemScriptBlock(@"""$($_.Debug)$($_.Debug.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Debug") .EndEntry() .EndList()); diff --git a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs index be6eaef0e09..8efb46e40c7 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs @@ -1,7 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System.Collections; using System.Collections.Generic; +using System.Management.Automation.Internal; namespace System.Management.Automation { @@ -281,12 +283,33 @@ public sealed class ProgressConfiguration /// /// Gets or sets the style for progress bar. /// - public string Style { get; set; } = "\x1b[33;1m"; + public string Style + { + get => _style; + set => _style = ValidateNoContent(value); + } + + private string _style = "\x1b[33;1m"; /// /// Gets or sets the max width of the progress bar. /// - public int MaxWidth { get; set; } = 120; + public int MaxWidth + { + get => _maxWidth; + set + { + // Width less than 18 does not render correctly due to the different parts of the progress bar. + if (value < 18) + { + throw new ArgumentOutOfRangeException(nameof(MaxWidth), PSStyleStrings.ProgressWidthTooSmall); + } + + _maxWidth = value; + } + } + + private int _maxWidth = 120; /// /// Gets or sets the view for progress bar. @@ -307,37 +330,79 @@ public sealed class FormattingData /// /// Gets or sets the accent style for formatting. /// - public string FormatAccent { get; set; } = "\x1b[32;1m"; + public string FormatAccent + { + get => _formatAccent; + set => _formatAccent = ValidateNoContent(value); + } + + private string _formatAccent = "\x1b[32;1m"; /// /// Gets or sets the style for table headers. /// - public string TableHeader { get; set; } = "\x1b[32;1m"; + public string TableHeader + { + get => _tableHeader; + set => _tableHeader = ValidateNoContent(value); + } + + private string _tableHeader = "\x1b[32;1m"; /// /// Gets or sets the accent style for errors. /// - public string ErrorAccent { get; set; } = "\x1b[36;1m"; + public string ErrorAccent + { + get => _errorAccent; + set => _errorAccent = ValidateNoContent(value); + } + + private string _errorAccent = "\x1b[36;1m"; /// /// Gets or sets the style for error messages. /// - public string Error { get; set; } = "\x1b[31;1m"; + public string Error + { + get => _error; + set => _error = ValidateNoContent(value); + } + + private string _error = "\x1b[31;1m"; /// /// Gets or sets the style for warning messages. /// - public string Warning { get; set; } = "\x1b[33;1m"; + public string Warning + { + get => _warning; + set => _warning = ValidateNoContent(value); + } + + private string _warning = "\x1b[33;1m"; /// /// Gets or sets the style for verbose messages. /// - public string Verbose { get; set; } = "\x1b[33;1m"; + public string Verbose + { + get => _verbose; + set => _verbose = ValidateNoContent(value); + } + + private string _verbose = "\x1b[33;1m"; /// /// Gets or sets the style for debug messages. /// - public string Debug { get; set; } = "\x1b[33;1m"; + public string Debug + { + get => _debug; + set => _debug = ValidateNoContent(value); + } + + private string _debug = "\x1b[33;1m"; } /// @@ -348,29 +413,137 @@ public sealed class FileInfoFormatting /// /// Gets or sets the style for directories. /// - public string Directory { get; set; } = "\x1b[44;1m"; + public string Directory + { + get => _directory; + set => _directory = ValidateNoContent(value); + } + + private string _directory = "\x1b[44;1m"; /// /// Gets or sets the style for symbolic links. /// - public string SymbolicLink { get; set; } = "\x1b[36;1m"; + public string SymbolicLink + { + get => _symbolicLink; + set => _symbolicLink = ValidateNoContent(value); + } + + private string _symbolicLink = "\x1b[36;1m"; /// /// Gets or sets the style for executables. /// - public string Executable { get; set; } = "\x1b[32;1m"; + public string Executable + { + get => _executable; + set => _executable = ValidateNoContent(value); + } + + private string _executable = "\x1b[32;1m"; + + /// + /// Custom dictionary handling validation of extension and content. + /// + public sealed class FileExtensionDictionary + { + private static string ValidateExtension(string extension) + { + if (!extension.StartsWith('.')) + { + throw new ArgumentException(PSStyleStrings.ExtensionNotStartingWithPeriod); + } + + return extension; + } + + private readonly Dictionary _extensionDictionary = new(StringComparer.OrdinalIgnoreCase); + + /// + /// Add new extension and decoration to dictionary. + /// + /// Extension to add. + /// ANSI string value to add. + public void Add(string extension, string decoration) + { + _extensionDictionary.Add(ValidateExtension(extension), ValidateNoContent(decoration)); + } + + /// + /// Remove an extension from dictionary. + /// + /// Extension to remove. + public void Remove(string extension) + { + _extensionDictionary.Remove(ValidateExtension(extension)); + } + + /// + /// Clear the dictionary. + /// + public void Clear() + { + _extensionDictionary.Clear(); + } + + /// + /// Gets or sets the decoration by specified extension. + /// + /// Extension to get decoration for. + /// The decoration for specified extension. + public string this[string extension] + { + get + { + return _extensionDictionary[ValidateExtension(extension)]; + } + + set + { + _extensionDictionary[ValidateExtension(extension)] = ValidateNoContent(value); + } + } + + /// + /// Gets whether the dictionary contains the specified extension. + /// + /// Extension to check for. + /// True if the dictionary contains the specified extension, otherwise false. + public bool ContainsKey(string extension) + { + if (string.IsNullOrEmpty(extension)) + { + return false; + } + + return _extensionDictionary.ContainsKey(ValidateExtension(extension)); + } + + /// + /// Gets the extensions for the dictionary. + /// + /// The extensions for the dictionary. + public IEnumerable Keys + { + get + { + return _extensionDictionary.Keys; + } + } + } /// /// Gets the style for archive. /// - public Dictionary Extension { get; } + public FileExtensionDictionary Extension { get; } /// /// Initializes a new instance of the class. /// public FileInfoFormatting() { - Extension = new Dictionary(StringComparer.OrdinalIgnoreCase); + Extension = new FileExtensionDictionary(); // archives Extension.Add(".zip", "\x1b[31;1m"); @@ -516,6 +689,17 @@ private PSStyle() FileInfo = new FileInfoFormatting(); } + private static string ValidateNoContent(string text) + { + var decorartedString = new StringDecorated(text); + if (decorartedString.ContentLength > 0) + { + throw new ArgumentException(string.Format(PSStyleStrings.TextContainsContent, decorartedString.ToString(OutputRendering.PlainText))); + } + + return text; + } + /// /// Gets singleton instance. /// diff --git a/src/System.Management.Automation/resources/PSStyleStrings.resx b/src/System.Management.Automation/resources/PSStyleStrings.resx new file mode 100644 index 00000000000..bc7acb1c200 --- /dev/null +++ b/src/System.Management.Automation/resources/PSStyleStrings.resx @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The specified string contains printable content when it should only contain ANSI escape sequences: {0} + + + The MaxWidth for the Progress rendering must be at least 18 to render correctly. + + + When adding or removing extensions, the extension must start with a period. + + diff --git a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 index f09fc27d1e8..b4d966b8b21 100644 --- a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 +++ b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 @@ -165,4 +165,75 @@ Describe 'Tests for $PSStyle automatic variable' { $PSStyle.Formatting.TableHeader = $old } } + + It 'Should fail if setting formatting contains printable characters: .' -TestCases @( + @{ Submember = 'Reset' } + @{ Submember = 'BlinkOff' } + @{ Submember = 'Blink' } + @{ Submember = 'BoldOff' } + @{ Submember = 'Bold' } + @{ Submember = 'HiddenOff' } + @{ Submember = 'Hidden' } + @{ Submember = 'ItalicOff' } + @{ Submember = 'Italic' } + @{ Submember = 'UnderlineOff' } + @{ Submember = 'Underline' } + @{ Submember = 'StrikethroughOff' } + @{ Submember = 'Strikethrough' } + @{ Member = 'Formatting'; Submember = 'FormatAccent' } + @{ Member = 'Formatting'; Submember = 'TableHeader' } + @{ Member = 'Formatting'; Submember = 'ErrorAccent' } + @{ Member = 'Formatting'; Submember = 'Error' } + @{ Member = 'Formatting'; Submember = 'Warning' } + @{ Member = 'Formatting'; Submember = 'Verbose' } + @{ Member = 'Formatting'; Submember = 'Debug' } + @{ Member = 'Progress'; Submember = 'Style' } + @{ Member = 'FileInfo'; Submember = 'Directory' } + @{ Member = 'FileInfo'; Submember = 'SymbolicLink' } + @{ Member = 'FileInfo'; Submember = 'Executable' } + @{ Member = 'FileInfo'; Submember = 'Hidden' } + ) { + param ($member, $submember) + + if ($null -ne $member) { + { $PSStyle.$member.$submember = $PSStyle.Foreground.Red + 'hello' } | Should -Throw + } + else { + { $PSStyle.$submember = $PSStyle.Foreground.Red + 'hello' } | Should -Throw + } + } + + It 'Should fail adding extension formatting with printable characters' { + { $PSStyle.FileInfo.Extension.Add('.md', 'hello') } | Should -Throw -ErrorId 'ArgumentException' + } + + It 'Should add and remove extension' { + $extension = '.mytest' + $PSStyle.FileInfo.Extension.Keys | Should -Not -Contain $extension + $PSStyle.FileInfo.Extension.Add($extension, $PSStyle.Foreground.Blue) + + $PSStyle.FileInfo.Extension[$extension] | Should -Be $PSStyle.Foreground.Blue + $PSStyle.FileInfo.Extension.Remove($extension) + $PSStyle.FileInfo.Extension.Keys | Should -Not -Contain $extension + } + + It 'Should fail to add extension does not start with a period' { + { $PSStyle.FileInfo.Extension.Add('mytest', $PSStyle.Foreground.Blue) } | Should -Throw -ErrorId 'ArgumentException' + } + + It 'Should fail to remove extension does not start with a period' { + { $PSStyle.FileInfo.Extension.Remove('zip') } | Should -Throw -ErrorId 'ArgumentException' + } + + It 'Should fail if MaxWidth is less than 18' { + $maxWidth = $PSStyle.Progress.MaxWidth + + # minimum allowed width is 18 as less than that doesn't render correctly + try { + { $PSStyle.Progress.MaxWidth = 17 } | Should -Throw -ErrorId 'ExceptionWhenSetting' + } + finally { + $PSStyle.Progress.MaxWidth = $maxWidth + } + } } From 3733a0bb3749b448002b034d0d09055367adac27 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Tue, 27 Jul 2021 19:18:53 +0100 Subject: [PATCH 11/55] Avoid unnecessary StringCollection allocation in formatting code (#15832) --- .../common/BaseOutputtingCommand.cs | 40 +++++++++++-------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index b92aac63668..136b7a26ef5 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Collections.Specialized; using System.Management.Automation; using System.Management.Automation.Internal; @@ -1117,33 +1116,40 @@ private void InternalInitialize(ListViewEntry lve) internal static string[] GetProperties(ListViewEntry lve) { - StringCollection props = new StringCollection(); - foreach (ListViewField lvf in lve.listViewFieldList) + int count = lve.listViewFieldList.Count; + + if (count == 0) { - props.Add(lvf.label ?? lvf.propertyName); + return null; } - if (props.Count == 0) - return null; - string[] retVal = new string[props.Count]; - props.CopyTo(retVal, 0); - return retVal; + string[] result = new string[count]; + for (int index = 0; index < result.Length; ++index) + { + ListViewField lvf = lve.listViewFieldList[index]; + result[index] = lvf.label ?? lvf.propertyName; + } + + return result; } internal static string[] GetValues(ListViewEntry lve) { - StringCollection vals = new StringCollection(); + int count = lve.listViewFieldList.Count; - foreach (ListViewField lvf in lve.listViewFieldList) + if (count == 0) { - vals.Add(lvf.formatPropertyField.propertyValue); + return null; } - if (vals.Count == 0) - return null; - string[] retVal = new string[vals.Count]; - vals.CopyTo(retVal, 0); - return retVal; + string[] result = new string[count]; + for (int index = 0; index < result.Length; ++index) + { + ListViewField lvf = lve.listViewFieldList[index]; + result[index] = lvf.formatPropertyField.propertyValue; + } + + return result; } /// From 055b7f3003dd8699ac7271f9ab1d9de217b744be Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 28 Jul 2021 20:28:24 +0100 Subject: [PATCH 12/55] Fix `CA1052` for public API to make classes static when they only have static methods (#15775) --- .globalconfig | 2 +- src/System.Management.Automation/engine/PSVersionInfo.cs | 2 +- src/System.Management.Automation/engine/serialization.cs | 4 +--- test/powershell/engine/Basic/assets/standardtypes.csv | 2 +- test/tools/WebListener/Program.cs | 2 +- 5 files changed, 5 insertions(+), 7 deletions(-) diff --git a/.globalconfig b/.globalconfig index f2201141f97..fec0d21edc6 100644 --- a/.globalconfig +++ b/.globalconfig @@ -146,7 +146,7 @@ dotnet_code_quality.CA1051.api_surface = public # CA1052: Static holder types should be Static or NotInheritable # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1052 dotnet_diagnostic.CA1052.severity = warning -dotnet_code_quality.CA1052.api_surface = private, internal +dotnet_code_quality.CA1052.api_surface = all # CA1054: URI-like parameters should not be strings # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1054 diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 54cf9e07277..39fa635e733 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -27,7 +27,7 @@ namespace System.Management.Automation /// The above statement retrieves the PowerShell edition. /// /// - public class PSVersionInfo + public static class PSVersionInfo { internal const string PSVersionTableName = "PSVersionTable"; internal const string PSRemotingProtocolVersionName = "PSRemotingProtocolVersion"; diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index d801178a29b..ce21d8258be 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -82,10 +82,8 @@ internal SerializationContext(int depth, SerializationOptions options, PSRemotin /// /// This class provides public functionality for serializing a PSObject. /// - public class PSSerializer + public static class PSSerializer { - internal PSSerializer() { } - /// /// Serializes an object into PowerShell CliXml. /// diff --git a/test/powershell/engine/Basic/assets/standardtypes.csv b/test/powershell/engine/Basic/assets/standardtypes.csv index dfae58ea321..d372000dcb5 100644 --- a/test/powershell/engine/Basic/assets/standardtypes.csv +++ b/test/powershell/engine/Basic/assets/standardtypes.csv @@ -250,7 +250,7 @@ "System.Management.Automation.PSScriptMethod","False","False","False","False","False","False","False","True","True","False","False","False","False","False","False","False","False","False","False","False","False","False","False","True","False","False","False","False","False","False","False","True","True","False","False","True","False","False","False","False","False","False","False","False","False","False","True" "System.Management.Automation.PSScriptProperty","False","False","False","False","False","False","False","True","True","False","False","False","False","False","False","False","False","False","False","False","False","False","False","True","False","False","False","False","False","False","False","True","True","False","False","True","False","False","False","False","False","False","False","False","False","False","True" "System.Management.Automation.PSSecurityException","False","False","False","False","False","False","False","True","True","False","False","False","False","False","False","False","False","False","False","False","False","False","False","True","False","False","False","False","False","False","False","True","True","False","False","True","False","False","False","False","False","False","False","False","False","True","True" -"System.Management.Automation.PSSerializer","False","False","False","False","False","False","False","True","True","False","False","False","False","False","False","False","False","False","False","False","False","False","False","True","False","False","False","False","False","False","False","True","True","False","False","True","False","False","False","False","False","False","False","False","False","False","True" +"System.Management.Automation.PSSerializer","False","False","False","False","False","False","False","True","True","False","False","False","False","False","False","False","False","False","False","True","False","True","False","True","False","False","False","False","False","False","False","True","True","False","False","True","False","False","False","False","False","False","False","False","False","False","True" "System.Management.Automation.PSSessionTypeOption","False","False","False","False","False","False","False","True","True","False","False","False","False","False","False","False","False","False","False","True","False","False","False","True","False","False","False","False","False","False","False","True","True","False","False","True","False","False","False","False","False","False","False","False","False","False","True" "System.Management.Automation.PSTraceSource","False","False","False","False","False","False","False","True","True","False","False","False","False","False","False","False","False","False","False","False","False","False","False","True","False","False","False","False","False","False","False","True","True","False","False","True","False","False","False","False","False","False","False","False","False","False","True" "System.Management.Automation.PSTraceSourceOptions","False","False","False","False","False","False","False","True","True","False","False","False","False","False","False","False","False","False","False","False","False","True","False","False","False","False","False","False","False","False","False","True","True","False","False","True","False","False","False","False","True","False","False","True","False","True","True" diff --git a/test/tools/WebListener/Program.cs b/test/tools/WebListener/Program.cs index 49f3df50bb9..a4b575121d2 100644 --- a/test/tools/WebListener/Program.cs +++ b/test/tools/WebListener/Program.cs @@ -17,7 +17,7 @@ namespace mvc { - public class Program + public static class Program { public static void Main(string[] args) { From 0f2f23f67a2c3ec53cf82c8d1a67b479f62934e4 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 28 Jul 2021 20:39:14 +0100 Subject: [PATCH 13/55] Enable IDE0049 `PreferBuiltInOrFrameworkType` (#14491) --- .globalconfig | 2 +- .../CimCommandBase.cs | 10 +-- .../CimIndicationWatcher.cs | 8 +-- .../CimRegisterCimIndication.cs | 8 +-- .../CimSessionProxy.cs | 16 ++--- .../CimWriteMessage.cs | 4 +- .../CimWriteProgress.cs | 8 +-- .../GetCimAssociatedInstanceCommand.cs | 2 +- .../GetCimClassCommand.cs | 2 +- .../GetCimInstanceCommand.cs | 2 +- .../GetCimSessionCommand.cs | 4 +- .../InvokeCimMethodCommand.cs | 2 +- .../NewCimInstanceCommand.cs | 2 +- .../NewCimSessionCommand.cs | 8 +-- .../NewCimSessionOptionCommand.cs | 4 +- .../RegisterCimIndicationCommand.cs | 2 +- .../RemoveCimInstanceCommand.cs | 2 +- .../RemoveCimSessionCommand.cs | 4 +- .../SetCimInstanceCommand.cs | 2 +- .../CommonUtils.cs | 4 +- .../GetEventCommand.cs | 12 ++-- .../cmdletization/cim/CimJobException.cs | 2 +- .../cmdletization/cim/cimChildJobBase.cs | 34 +++++----- .../cimSupport/cmdletization/cim/cimQuery.cs | 4 +- .../commands/management/Computer.cs | 6 +- .../management/GetComputerInfoCommand.cs | 68 +++++++++---------- .../commands/utility/Compare-Object.cs | 4 +- .../commands/utility/GetRandomCommand.cs | 36 +++++----- .../commands/utility/ImportAliasCommand.cs | 2 +- .../commands/utility/MatchString.cs | 2 +- .../commands/utility/Send-MailMessage.cs | 2 +- .../commands/utility/SetDateCommand.cs | 30 ++++---- .../utility/ShowCommand/ShowCommand.cs | 4 +- .../commands/utility/UtilityCommon.cs | 6 +- .../commands/utility/WaitEventCommand.cs | 2 +- .../Common/InvokeRestMethodCommand.Common.cs | 2 +- .../Common/WebRequestPSCmdlet.Common.cs | 10 +-- .../commands/utility/WebCmdlet/JsonObject.cs | 2 +- .../commands/utility/WriteProgressCmdlet.cs | 4 +- .../WindowsTaskbarJumpList/ComInterfaces.cs | 28 ++++---- .../WindowsTaskbarJumpList/PropertyKey.cs | 4 +- .../host/msh/ConsoleControl.cs | 8 +-- .../host/msh/ConsoleHostUserInterface.cs | 12 ++-- .../msh/ConsoleHostUserInterfaceProgress.cs | 2 +- .../host/msh/PendingProgress.cs | 10 +-- .../host/msh/ProgressNode.cs | 4 +- .../DotNetCode/Eventing/EventProvider.cs | 4 +- .../Eventing/Reader/NativeWrapper.cs | 38 +++++------ .../Eventing/UnsafeNativeMethods.cs | 26 +++---- .../security/SecureStringCommands.cs | 2 +- .../ConfigProvider.cs | 6 +- .../InvokeWSManAction.cs | 6 +- .../NewWSManSession.cs | 12 ++-- src/Microsoft.WSMan.Management/PingWSMan.cs | 6 +- .../WSManConnections.cs | 6 +- .../WSManInstance.cs | 22 +++--- 56 files changed, 262 insertions(+), 262 deletions(-) diff --git a/.globalconfig b/.globalconfig index fec0d21edc6..d7fb942772c 100644 --- a/.globalconfig +++ b/.globalconfig @@ -1314,7 +1314,7 @@ dotnet_diagnostic.IDE0048.severity = suggestion # IDE0049: PreferBuiltInOrFrameworkType # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0049 -dotnet_diagnostic.IDE0049.severity = silent +dotnet_diagnostic.IDE0049.severity = warning # IDE0050: ConvertAnonymousTypeToTuple # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0050 diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs index a7e75bb98c7..4e9bf4f296e 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs @@ -57,7 +57,7 @@ internal class ParameterSetEntry /// Initializes a new instance of the class. /// /// - internal ParameterSetEntry(UInt32 mandatoryParameterCount) + internal ParameterSetEntry(uint mandatoryParameterCount) { this.MandatoryParameterCount = mandatoryParameterCount; this.IsDefaultParameterSet = false; @@ -80,7 +80,7 @@ internal ParameterSetEntry(ParameterSetEntry toClone) /// /// /// - internal ParameterSetEntry(UInt32 mandatoryParameterCount, bool isDefault) + internal ParameterSetEntry(uint mandatoryParameterCount, bool isDefault) { this.MandatoryParameterCount = mandatoryParameterCount; this.IsDefaultParameterSet = isDefault; @@ -104,7 +104,7 @@ internal void reset() /// /// Property MandatoryParameterCount /// - internal UInt32 MandatoryParameterCount { get; } = 0; + internal uint MandatoryParameterCount { get; } = 0; /// /// Property IsValueSet @@ -119,12 +119,12 @@ internal void reset() /// /// Property SetMandatoryParameterCount /// - internal UInt32 SetMandatoryParameterCount { get; set; } = 0; + internal uint SetMandatoryParameterCount { get; set; } = 0; /// /// Property SetMandatoryParameterCountAtBeginProcess /// - internal UInt32 SetMandatoryParameterCountAtBeginProcess { get; set; } = 0; + internal uint SetMandatoryParameterCountAtBeginProcess { get; set; } = 0; } /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs index 0c847265cfe..cb5cfc27056 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs @@ -153,7 +153,7 @@ public CimIndicationWatcher( string theNamespace, string queryDialect, string queryExpression, - UInt32 operationTimeout) + uint operationTimeout) { ValidationHelper.ValidateNoNullorWhiteSpaceArgument(queryExpression, queryExpressionParameterName); computerName = ConstValue.GetComputerName(computerName); @@ -173,7 +173,7 @@ public CimIndicationWatcher( string theNamespace, string queryDialect, string queryExpression, - UInt32 operationTimeout) + uint operationTimeout) { ValidationHelper.ValidateNoNullorWhiteSpaceArgument(queryExpression, queryExpressionParameterName); ValidationHelper.ValidateNoNullArgument(cimSession, cimSessionParameterName); @@ -192,7 +192,7 @@ private void Initialize( string theNameSpace, string theQueryDialect, string theQueryExpression, - UInt32 theOperationTimeout) + uint theOperationTimeout) { enableRaisingEvents = false; status = Status.Default; @@ -378,7 +378,7 @@ internal void SetCmdlet(Cmdlet cmdlet) private string nameSpace; private string queryDialect; private string queryExpression; - private UInt32 operationTimeout; + private uint operationTimeout; #endregion #endregion } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs index 698b4e1c4a0..24b9332bde5 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs @@ -123,7 +123,7 @@ public void RegisterCimIndication( string nameSpace, string queryDialect, string queryExpression, - UInt32 operationTimeout) + uint operationTimeout) { DebugHelper.WriteLogEx("queryDialect = '{0}'; queryExpression = '{1}'", 0, queryDialect, queryExpression); this.TargetComputerName = computerName; @@ -146,7 +146,7 @@ public void RegisterCimIndication( string nameSpace, string queryDialect, string queryExpression, - UInt32 operationTimeout) + uint operationTimeout) { DebugHelper.WriteLogEx("queryDialect = '{0}'; queryExpression = '{1}'", 0, queryDialect, queryExpression); if (cimSession == null) @@ -317,7 +317,7 @@ internal string TargetComputerName /// private CimSessionProxy CreateSessionProxy( string computerName, - UInt32 timeout) + uint timeout) { CimSessionProxy proxy = CreateCimSessionProxy(computerName); proxy.OperationTimeout = timeout; @@ -332,7 +332,7 @@ private CimSessionProxy CreateSessionProxy( /// private CimSessionProxy CreateSessionProxy( CimSession session, - UInt32 timeout) + uint timeout) { CimSessionProxy proxy = CreateCimSessionProxy(session); proxy.OperationTimeout = timeout; diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs index dfbfe090ddc..9321c86ec77 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs @@ -542,11 +542,11 @@ private void CreateSetSession( /// /// Set timeout value (seconds) of the operation. /// - public UInt32 OperationTimeout + public uint OperationTimeout { get { - return (UInt32)this.OperationOptions.Timeout.TotalSeconds; + return (uint)this.OperationOptions.Timeout.TotalSeconds; } set @@ -821,7 +821,7 @@ private void FireOperationDeletedEvent( /// /// /// - internal void WriteMessage(UInt32 channel, string message) + internal void WriteMessage(uint channel, string message) { DebugHelper.WriteLogEx("Channel = {0} message = {1}", 0, channel, message); try @@ -863,7 +863,7 @@ internal void WriteOperationStartMessage(string operation, Hashtable parameterLi CimCmdletStrings.CimOperationStart, operation, (parameters.Length == 0) ? "null" : parameters.ToString()); - WriteMessage((UInt32)CimWriteMessageChannel.Verbose, operationStartMessage); + WriteMessage((uint)CimWriteMessageChannel.Verbose, operationStartMessage); } /// @@ -878,7 +878,7 @@ internal void WriteOperationCompleteMessage(string operation) string operationCompleteMessage = string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.CimOperationCompleted, operation); - WriteMessage((UInt32)CimWriteMessageChannel.Verbose, operationCompleteMessage); + WriteMessage((uint)CimWriteMessageChannel.Verbose, operationCompleteMessage); } /// @@ -894,8 +894,8 @@ internal void WriteOperationCompleteMessage(string operation) public void WriteProgress(string activity, string currentOperation, string statusDescription, - UInt32 percentageCompleted, - UInt32 secondsRemaining) + uint percentageCompleted, + uint secondsRemaining) { DebugHelper.WriteLogEx("activity:{0}; currentOperation:{1}; percentageCompleted:{2}; secondsRemaining:{3}", 0, activity, currentOperation, percentageCompleted, secondsRemaining); @@ -1879,7 +1879,7 @@ private CimSession CreateCimSessionByComputerName(string computerName) /// /// internal static CimSessionOptions CreateCimSessionOption(string computerName, - UInt32 timeout, CimCredential credential) + uint timeout, CimCredential credential) { DebugHelper.WriteLogEx(); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs index cf927617235..f4b244b97f9 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs @@ -26,7 +26,7 @@ internal sealed class CimWriteMessage : CimBaseAction #region Properties - internal UInt32 Channel { get; } + internal uint Channel { get; } internal string Message { get; } @@ -35,7 +35,7 @@ internal sealed class CimWriteMessage : CimBaseAction /// /// Initializes a new instance of the class. /// - public CimWriteMessage(UInt32 channel, + public CimWriteMessage(uint channel, string message) { this.Channel = channel; diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs index 8e5632215a0..b99407ccc81 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs @@ -40,8 +40,8 @@ public CimWriteProgress( int theActivityID, string theCurrentOperation, string theStatusDescription, - UInt32 thePercentageCompleted, - UInt32 theSecondsRemaining) + uint thePercentageCompleted, + uint theSecondsRemaining) { this.Activity = theActivity; this.ActivityID = theActivityID; @@ -112,12 +112,12 @@ public override void Execute(CmdletOperationBase cmdlet) /// /// Gets the percentage completed of the given activity. /// - internal UInt32 PercentageCompleted { get; } + internal uint PercentageCompleted { get; } /// /// Gets the number of seconds remaining for the given activity. /// - internal UInt32 SecondsRemaining { get; } + internal uint SecondsRemaining { get; } #endregion } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs index ea592b40b90..90acd1c6c0e 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs @@ -110,7 +110,7 @@ public CimInstance InputObject /// [Alias(AliasOT)] [Parameter(ValueFromPipelineByPropertyName = true)] - public UInt32 OperationTimeoutSec { get; set; } + public uint OperationTimeoutSec { get; set; } /// /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs index d4ab679f0a7..adc669ab645 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs @@ -79,7 +79,7 @@ public GetCimClassCommand() /// [Alias(AliasOT)] [Parameter(ValueFromPipelineByPropertyName = true)] - public UInt32 OperationTimeoutSec { get; set; } + public uint OperationTimeoutSec { get; set; } /// /// The following is the definition of the input parameter "Session". diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs index cc4de5e84e9..d61a9363922 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs @@ -260,7 +260,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec { get; set; } + public uint OperationTimeoutSec { get; set; } /// /// The following is the definition of the input parameter "InputObject". diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs index a402d58d0d3..3289b6c86c0 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs @@ -81,7 +81,7 @@ public string[] ComputerName ValueFromPipelineByPropertyName = true, ParameterSetName = SessionIdSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public UInt32[] Id + public uint[] Id { get { @@ -95,7 +95,7 @@ public UInt32[] Id } } - private UInt32[] id; + private uint[] id; /// /// The following is the definition of the input parameter "InstanceID". diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs index f920094ae15..26e1d8eaf5f 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs @@ -373,7 +373,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec { get; set; } + public uint OperationTimeoutSec { get; set; } #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs index b43b1e275d7..53d7c28b924 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs @@ -223,7 +223,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec { get; set; } + public uint OperationTimeoutSec { get; set; } /// /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs index 2d1a91f5c0e..9957372d592 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs @@ -104,7 +104,7 @@ public PasswordAuthenticationMechanism Authentication /// [Alias(AliasOT)] [Parameter(ValueFromPipelineByPropertyName = true)] - public UInt32 OperationTimeoutSec + public uint OperationTimeoutSec { get { @@ -118,7 +118,7 @@ public UInt32 OperationTimeoutSec } } - private UInt32 operationTimeout; + private uint operationTimeout; internal bool operationTimeoutSet = false; /// @@ -136,7 +136,7 @@ public UInt32 OperationTimeoutSec /// This is specificly for wsman protocol. /// [Parameter(ValueFromPipelineByPropertyName = true)] - public UInt32 Port + public uint Port { get { @@ -150,7 +150,7 @@ public UInt32 Port } } - private UInt32 port; + private uint port; private bool portSet = false; /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs index 0b62b79d96c..c82a882fb25 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs @@ -231,7 +231,7 @@ public Uri HttpPrefix /// [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = WSManParameterSet)] - public UInt32 MaxEnvelopeSizeKB + public uint MaxEnvelopeSizeKB { get { @@ -246,7 +246,7 @@ public UInt32 MaxEnvelopeSizeKB } } - private UInt32 maxenvelopesizekb; + private uint maxenvelopesizekb; private bool maxenvelopesizekbSet = false; /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs index 246a95f37e3..d22644ececd 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs @@ -124,7 +124,7 @@ public string QueryDialect /// [Alias(CimBaseCommand.AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec { get; set; } + public uint OperationTimeoutSec { get; set; } /// /// The following is the definition of the input parameter "Session". diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs index c3f1230020c..273311485ce 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs @@ -154,7 +154,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec { get; set; } + public uint OperationTimeoutSec { get; set; } /// /// The following is the definition of the input parameter "InputObject". diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs index 53937e57354..2f1a5ad026e 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs @@ -108,7 +108,7 @@ public string[] ComputerName ValueFromPipelineByPropertyName = true, ParameterSetName = SessionIdSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public UInt32[] Id + public uint[] Id { get { @@ -122,7 +122,7 @@ public UInt32[] Id } } - private UInt32[] id; + private uint[] id; /// /// The following is the definition of the input parameter "InstanceId". diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs index 25b3113e452..de6857db5eb 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs @@ -151,7 +151,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec { get; set; } + public uint OperationTimeoutSec { get; set; } /// /// The following is the definition of the input parameter "InputObject". diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs index fb788b4d26c..dfe046ec8ca 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs @@ -40,12 +40,12 @@ uint dwFlags [DllImport(LocalizationDllName, EntryPoint = "GetUserDefaultLangID", CallingConvention = CallingConvention.Winapi, SetLastError = true)] private static extern ushort GetUserDefaultLangID(); - public static uint FormatMessageFromModule(uint lastError, string moduleName, out String msg) + public static uint FormatMessageFromModule(uint lastError, string moduleName, out string msg) { Debug.Assert(!string.IsNullOrEmpty(moduleName)); uint formatError = 0; - msg = String.Empty; + msg = string.Empty; IntPtr moduleHandle = LoadLibraryEx(moduleName, IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE); if (moduleHandle == IntPtr.Zero) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs index 1a74da73d1c..10044e29466 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs @@ -144,8 +144,8 @@ public sealed class GetWinEventCommand : PSCmdlet ValueFromPipelineByPropertyName = false, HelpMessageBaseName = "GetEventResources", HelpMessageResourceId = "MaxEventsParamHelp")] - [ValidateRange((Int64)1, Int64.MaxValue)] - public Int64 MaxEvents { get; set; } = -1; + [ValidateRange((long)1, long.MaxValue)] + public long MaxEvents { get; set; } = -1; /// /// ComputerName parameter. @@ -777,7 +777,7 @@ private void ReadEvents(EventLogQuery logQuery) { using (EventLogReader readerObj = new(logQuery)) { - Int64 numEvents = 0; + long numEvents = 0; EventRecord evtObj = null; while (true) @@ -1311,8 +1311,8 @@ private static string HandleLevelHashValue(object value) // private string HandleKeywordHashValue(object value) { - Int64 keywordsMask = 0; - Int64 keywordLong = 0; + long keywordsMask = 0; + long keywordLong = 0; Array keywordArray = value as Array; if (keywordArray != null) @@ -1609,7 +1609,7 @@ private bool ValidateLogName(string logName, EventLogSession eventLogSession) // Returns true and keyLong ref if successful. // Writes an error and returns false if keyString cannot be converted. // - private bool KeywordStringToInt64(string keyString, ref Int64 keyLong) + private bool KeywordStringToInt64(string keyString, ref long keyLong) { try { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs index 808ca1a4de9..0ffa5bdf98f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs @@ -374,7 +374,7 @@ internal bool IsTerminatingError return false; } - UInt16 perceivedSeverityValue = (UInt16)perceivedSeverityProperty.Value; + ushort perceivedSeverityValue = (ushort)perceivedSeverityProperty.Value; if (perceivedSeverityValue != 7) { /* from CIM Schema: Interop\CIM_Error.mof: diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs index 6dc65424f50..cb4786f005e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs @@ -111,7 +111,7 @@ private static bool IsWsManQuotaReached(Exception exception) return false; } - WsManErrorCode wsManErrorCode = (WsManErrorCode)(UInt32)(errorCodeProperty.Value); + WsManErrorCode wsManErrorCode = (WsManErrorCode)(uint)(errorCodeProperty.Value); switch (wsManErrorCode) // error codes that should result in sleep-and-retry are based on an email from Ryan { case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_SHELLS: @@ -423,11 +423,11 @@ internal CimOperationOptions CreateOperationOptions() (_jobContext.WarningActionPreference == ActionPreference.Ignore) ) && (!_jobContext.IsRunningInBackground)) { - operationOptions.DisableChannel((UInt32)MessageChannel.Warning); + operationOptions.DisableChannel((uint)MessageChannel.Warning); } else { - operationOptions.EnableChannel((UInt32)MessageChannel.Warning); + operationOptions.EnableChannel((uint)MessageChannel.Warning); } if (( @@ -435,11 +435,11 @@ internal CimOperationOptions CreateOperationOptions() (_jobContext.VerboseActionPreference == ActionPreference.Ignore) ) && (!_jobContext.IsRunningInBackground)) { - operationOptions.DisableChannel((UInt32)MessageChannel.Verbose); + operationOptions.DisableChannel((uint)MessageChannel.Verbose); } else { - operationOptions.EnableChannel((UInt32)MessageChannel.Verbose); + operationOptions.EnableChannel((uint)MessageChannel.Verbose); } if (( @@ -447,11 +447,11 @@ internal CimOperationOptions CreateOperationOptions() (_jobContext.DebugActionPreference == ActionPreference.Ignore) ) && (!_jobContext.IsRunningInBackground)) { - operationOptions.DisableChannel((UInt32)MessageChannel.Debug); + operationOptions.DisableChannel((uint)MessageChannel.Debug); } else { - operationOptions.EnableChannel((UInt32)MessageChannel.Debug); + operationOptions.EnableChannel((uint)MessageChannel.Debug); } switch (this.JobContext.ShouldProcessOptimization) @@ -763,7 +763,7 @@ internal void FinishProgressReporting() #region Handling extended semantics callbacks - private void WriteProgressCallback(string activity, string currentOperation, string statusDescription, UInt32 percentageCompleted, UInt32 secondsRemaining) + private void WriteProgressCallback(string activity, string currentOperation, string statusDescription, uint percentageCompleted, uint secondsRemaining) { if (string.IsNullOrEmpty(activity)) { @@ -775,28 +775,28 @@ private void WriteProgressCallback(string activity, string currentOperation, str statusDescription = this.StatusMessage; } - Int32 signedSecondsRemaining; - if (secondsRemaining == UInt32.MaxValue) + int signedSecondsRemaining; + if (secondsRemaining == uint.MaxValue) { signedSecondsRemaining = -1; } - else if (secondsRemaining <= Int32.MaxValue) + else if (secondsRemaining <= int.MaxValue) { - signedSecondsRemaining = (Int32)secondsRemaining; + signedSecondsRemaining = (int)secondsRemaining; } else { - signedSecondsRemaining = Int32.MaxValue; + signedSecondsRemaining = int.MaxValue; } - Int32 signedPercentageComplete; - if (percentageCompleted == UInt32.MaxValue) + int signedPercentageComplete; + if (percentageCompleted == uint.MaxValue) { signedPercentageComplete = -1; } else if (percentageCompleted <= 100) { - signedPercentageComplete = (Int32)percentageCompleted; + signedPercentageComplete = (int)percentageCompleted; } else { @@ -825,7 +825,7 @@ private enum MessageChannel Debug = 2, } - private void WriteMessageCallback(UInt32 channel, string message) + private void WriteMessageCallback(uint channel, string message) { this.ExceptionSafeWrapper( delegate diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs index c1ee2f44dfc..d2e920b7f9d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs @@ -196,7 +196,7 @@ private static string GetMatchCondition(string propertyName, IEnumerable propert /// Property name to query on. /// Property values to accept in the query. /// - /// if should be treated as a containing a wildcard pattern; + /// if should be treated as a containing a wildcard pattern; /// otherwise. /// /// @@ -219,7 +219,7 @@ public override void FilterByProperty(string propertyName, IEnumerable allowedPr /// Property name to query on. /// Property values to reject in the query. /// - /// if should be treated as a containing a wildcard pattern; + /// if should be treated as a containing a wildcard pattern; /// otherwise. /// /// diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index 05c44c26d96..73c2f309508 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -275,12 +275,12 @@ public WaitForServiceTypes For /// The specific time interval (in second) to wait between network pings or service queries. /// [Parameter(ParameterSetName = DefaultParameterSet)] - [ValidateRange(1, Int16.MaxValue)] - public Int16 Delay + [ValidateRange(1, short.MaxValue)] + public short Delay { get { - return (Int16)_delay; + return (short)_delay; } set diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs index 527cd08baff..499358389f4 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -1125,7 +1125,7 @@ internal static string GetLocaleName(string locale) // base-indication prefix. For example, the string "0409" will be // parsed into the base-10 integer value 1033, while the string "0x0409" // will fail to parse due to the "0x" base-indication prefix. - if (UInt32.TryParse(locale, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint localeNum)) + if (uint.TryParse(locale, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint localeNum)) { culture = CultureInfo.GetCultureInfo((int)localeNum); } @@ -1231,11 +1231,11 @@ internal static class EnumConverter where T : struct, IConvertible internal static class RegistryInfo { - public static Dictionary GetServerLevels() + public static Dictionary GetServerLevels() { const string keyPath = @"Software\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels"; - var rv = new Dictionary(); + var rv = new Dictionary(); using (var key = Registry.LocalMachine.OpenSubKey(keyPath)) { @@ -1373,7 +1373,7 @@ internal class WmiBaseBoard [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] internal class WmiBios : WmiClassBase { - public UInt16[] BiosCharacteristics; + public ushort[] BiosCharacteristics; public string[] BIOSVersion; public string BuildNumber; public string Caption; @@ -1416,11 +1416,11 @@ internal class WmiComputerSystem public ushort? BootOptionOnWatchDog; public bool? BootROMSupported; public string BootupState; - public UInt16[] BootStatus; + public ushort[] BootStatus; public string Caption; public ushort? ChassisBootupState; public string ChassisSKUNumber; - public Int16? CurrentTimeZone; + public short? CurrentTimeZone; public bool? DaylightInEffect; public string Description; public string DNSHostName; @@ -1442,10 +1442,10 @@ internal class WmiComputerSystem public uint? NumberOfProcessors; public string[] OEMStringArray; public bool? PartOfDomain; - public Int64? PauseAfterReset; + public long? PauseAfterReset; public ushort? PCSystemType; public ushort? PCSystemTypeEx; - public UInt16[] PowerManagementCapabilities; + public ushort[] PowerManagementCapabilities; public bool? PowerManagementSupported; public ushort? PowerOnPasswordStatus; public ushort? PowerState; @@ -1453,8 +1453,8 @@ internal class WmiComputerSystem public string PrimaryOwnerContact; public string PrimaryOwnerName; public ushort? ResetCapability; - public Int16? ResetCount; - public Int16? ResetLimit; + public short? ResetCount; + public short? ResetLimit; public string[] Roles; public string Status; public string[] SupportContactDescription; @@ -1491,12 +1491,12 @@ public PowerManagementCapabilities[] GetPowerManagementCapabilities() [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] internal class WmiDeviceGuard { - public UInt32[] AvailableSecurityProperties; + public uint[] AvailableSecurityProperties; public uint? CodeIntegrityPolicyEnforcementStatus; public uint? UsermodeCodeIntegrityPolicyEnforcementStatus; - public UInt32[] RequiredSecurityProperties; - public UInt32[] SecurityServicesConfigured; - public UInt32[] SecurityServicesRunning; + public uint[] RequiredSecurityProperties; + public uint[] SecurityServicesConfigured; + public uint[] SecurityServicesRunning; public uint? VirtualizationBasedSecurityStatus; public DeviceGuard AsOutputType @@ -1582,7 +1582,7 @@ internal class WmiKeyboard public ushort? NumberOfFunctionKeys; public ushort? Password; public string PNPDeviceID; - public UInt16[] PowerManagementCapabilities; + public ushort[] PowerManagementCapabilities; public bool? PowerManagementSupported; public string Status; public ushort? StatusInfo; @@ -1613,7 +1613,7 @@ internal class WmiMsftNetAdapter public string ErrorDescription; public uint? LastErrorCode; public string PNPDeviceID; - public UInt16[] PowerManagementCapabilities; + public ushort[] PowerManagementCapabilities; public bool? PowerManagementSupported; public ushort? StatusInfo; public string SystemCreationClassName; @@ -1680,8 +1680,8 @@ internal class WmiMsftNetAdapter public string PnPDeviceID; public string DriverProvider; public string ComponentID; - public UInt32[] LowerLayerInterfaceIndices; - public UInt32[] HigherLayerInterfaceIndices; + public uint[] LowerLayerInterfaceIndices; + public uint[] HigherLayerInterfaceIndices; public bool? AdminLocked; } @@ -1717,7 +1717,7 @@ internal class WmiNetworkAdapter public string PermanentAddress; public bool? PhysicalAdapter; public string PNPDeviceID; - public UInt16[] PowerManagementCapabilities; + public ushort[] PowerManagementCapabilities; public bool? PowerManagementSupported; public string ProductName; public string ServiceName; @@ -1753,7 +1753,7 @@ internal class WmiNetworkAdapterConfiguration public bool? DomainDNSRegistrationEnabled; public uint? ForwardBufferMemory; public bool? FullDNSRegistrationEnabled; - public UInt16[] GatewayCostMetric; + public ushort[] GatewayCostMetric; public byte? IGMPLevel; public uint? Index; public uint? InterfaceIndex; @@ -1769,7 +1769,7 @@ internal class WmiNetworkAdapterConfiguration public bool? IPUseZeroBroadcast; public string IPXAddress; public bool? IPXEnabled; - public UInt32[] IPXFrameType; + public uint[] IPXFrameType; public uint? IPXMediaType; public string[] IPXNetworkNumber; public string IPXVirtualNetNumber; @@ -1807,7 +1807,7 @@ internal class WmiOperatingSystem : WmiClassBase public string CountryCode; public string CSDVersion; public string CSName; - public Int16? CurrentTimeZone; + public short? CurrentTimeZone; public bool? DataExecutionPrevention_Available; public bool? DataExecutionPrevention_32BitApplications; public bool? DataExecutionPrevention_Drivers; @@ -1894,7 +1894,7 @@ private static OSProductSuite[] MakeProductSuites(uint? suiteMask) var list = new List(); foreach (OSProductSuite suite in Enum.GetValues(typeof(OSProductSuite))) - if ((mask & (UInt32)suite) != 0) + if ((mask & (uint)suite) != 0) list.Add(suite); return list.ToArray(); @@ -1954,7 +1954,7 @@ internal class WmiProcessor public string OtherFamilyDescription; public string PartNumber; public string PNPDeviceID; - public UInt16[] PowerManagementCapabilities; + public ushort[] PowerManagementCapabilities; public bool? PowerManagementSupported; public string ProcessorId; public ushort? ProcessorType; @@ -2282,7 +2282,7 @@ public class ComputerInfo /// the System Management BIOS Reference Specification. /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public UInt16[] BiosCharacteristics { get; internal set; } + public ushort[] BiosCharacteristics { get; internal set; } /// /// Array of the complete system BIOS information. In many computers @@ -2320,12 +2320,12 @@ public class ComputerInfo /// /// Major version of the embedded controller firmware. /// - public Int16? BiosEmbeddedControllerMajorVersion { get; internal set; } + public short? BiosEmbeddedControllerMajorVersion { get; internal set; } /// /// Minor version of the embedded controller firmware. /// - public Int16? BiosEmbeddedControllerMinorVersion { get; internal set; } + public short? BiosEmbeddedControllerMinorVersion { get; internal set; } /// /// Firmware type of the local computer. @@ -2496,7 +2496,7 @@ public class ComputerInfo /// Status and Additional Data fields that identify the boot status. /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public UInt16[] CsBootStatus { get; internal set; } + public ushort[] CsBootStatus { get; internal set; } /// /// System is started. Fail-safe boot bypasses the user startup files—also called SafeBoot. @@ -2524,7 +2524,7 @@ public class ComputerInfo /// Amount of time the unitary computer system is offset from Coordinated /// Universal Time (UTC). /// - public Int16? CsCurrentTimeZone { get; internal set; } + public short? CsCurrentTimeZone { get; internal set; } /// /// If True, the daylight savings mode is ON. @@ -2675,7 +2675,7 @@ public class ComputerInfo /// and automatic system reset. A value of –1 (minus one) indicates that /// the pause value is unknown. /// - public Int64? CsPauseAfterReset { get; internal set; } + public long? CsPauseAfterReset { get; internal set; } /// /// Type of the computer in use, such as laptop, desktop, or tablet. @@ -2743,13 +2743,13 @@ public class ComputerInfo /// Number of automatic resets since the last reset. /// A value of –1 (minus one) indicates that the count is unknown. /// - public Int16? CsResetCount { get; internal set; } + public short? CsResetCount { get; internal set; } /// /// Number of consecutive times a system reset is attempted. /// A value of –1 (minus one) indicates that the limit is unknown. /// - public Int16? CsResetLimit { get; internal set; } + public short? CsResetLimit { get; internal set; } /// /// Array that specifies the roles of a system in the information @@ -2909,7 +2909,7 @@ public class ComputerInfo /// Number, in minutes, an operating system is offset from Greenwich /// mean time (GMT). The number is positive, negative, or zero. /// - public Int16? OsCurrentTimeZone { get; internal set; } + public short? OsCurrentTimeZone { get; internal set; } /// /// Language identifier used by the operating system. @@ -5099,7 +5099,7 @@ private static class PInvokeDllNames public const uint POWER_PLATFORM_ROLE_V1 = 0x1; public const uint POWER_PLATFORM_ROLE_V2 = 0x2; - public const UInt32 S_OK = 0; + public const uint S_OK = 0; /// /// Import WINAPI function PowerDeterminePlatformRoleEx. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs index 83f78ce77a2..54a5b07cf5d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs @@ -32,8 +32,8 @@ public sealed class CompareObjectCommand : ObjectCmdletBase /// /// [Parameter] - [ValidateRange(0, Int32.MaxValue)] - public int SyncWindow { get; set; } = Int32.MaxValue; + [ValidateRange(0, int.MaxValue)] + public int SyncWindow { get; set; } = int.MaxValue; /// /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs index 7d02713d801..a8ad9deb22b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs @@ -21,7 +21,7 @@ namespace Microsoft.PowerShell.Commands /// [Cmdlet(VerbsCommon.Get, "Random", DefaultParameterSetName = GetRandomCommand.RandomNumberParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097016", RemotingCapability = RemotingCapability.None)] - [OutputType(typeof(Int32), typeof(Int64), typeof(double))] + [OutputType(typeof(int), typeof(long), typeof(double))] public class GetRandomCommand : PSCmdlet { #region Parameter set handling @@ -229,7 +229,7 @@ private static bool IsInt(object o) private static bool IsInt64(object o) { - if (o == null || o is Int64) + if (o == null || o is long) { return true; } @@ -348,11 +348,11 @@ private double GetRandomDouble(double minValue, double maxValue) /// /// /// - private Int64 GetRandomInt64(Int64 minValue, Int64 maxValue) + private long GetRandomInt64(long minValue, long maxValue) { // Randomly generate eight bytes and convert the byte array to UInt64 - var buffer = new byte[sizeof(UInt64)]; - UInt64 randomUint64; + var buffer = new byte[sizeof(ulong)]; + ulong randomUint64; BigInteger bigIntegerDiff = (BigInteger)maxValue - (BigInteger)minValue; @@ -364,17 +364,17 @@ private Int64 GetRandomInt64(Int64 minValue, Int64 maxValue) } // The difference of two Int64 numbers would not exceed UInt64.MaxValue, so it can be represented by a UInt64 number. - UInt64 uint64Diff = (UInt64)bigIntegerDiff; + ulong uint64Diff = (ulong)bigIntegerDiff; // Calculate the number of bits to represent the diff in type UInt64 int bitsToRepresentDiff = 0; - UInt64 diffCopy = uint64Diff; + ulong diffCopy = uint64Diff; for (; diffCopy != 0; bitsToRepresentDiff++) { diffCopy >>= 1; } // Get the mask for the number of bits - UInt64 mask = (0xffffffffffffffff >> (64 - bitsToRepresentDiff)); + ulong mask = (0xffffffffffffffff >> (64 - bitsToRepresentDiff)); do { // Randomly fill the buffer @@ -386,7 +386,7 @@ private Int64 GetRandomInt64(Int64 minValue, Int64 maxValue) } while (uint64Diff <= randomUint64); double randomNumber = minValue * 1.0 + randomUint64 * 1.0; - return (Int64)randomNumber; + return (long)randomNumber; } /// @@ -425,8 +425,8 @@ protected override void BeginProcessing() } else if ((IsInt64(maxOperand) || IsInt(maxOperand)) && (IsInt64(minOperand) || IsInt(minOperand))) { - Int64 minValue = minOperand != null ? ((minOperand is Int64) ? (Int64)minOperand : (int)minOperand) : 0; - Int64 maxValue = maxOperand != null ? ((maxOperand is Int64) ? (Int64)maxOperand : (int)maxOperand) : Int64.MaxValue; + long minValue = minOperand != null ? ((minOperand is long) ? (long)minOperand : (int)minOperand) : 0; + long maxValue = maxOperand != null ? ((maxOperand is long) ? (long)maxOperand : (int)maxOperand) : long.MaxValue; if (minValue >= maxValue) { @@ -435,7 +435,7 @@ protected override void BeginProcessing() for (int i = 0; i < Count; i++) { - Int64 randomNumber = GetRandomInt64(minValue, maxValue); + long randomNumber = GetRandomInt64(minValue, maxValue); Debug.Assert(minValue <= randomNumber, "lower bound <= random number"); Debug.Assert(randomNumber < maxValue, "random number < upper bound"); @@ -608,7 +608,7 @@ internal double NextDouble() { // According to the CLR source: // "Including this division at the end gives us significantly improved random number distribution." - return Next() * (1.0 / Int32.MaxValue); + return Next() * (1.0 / int.MaxValue); } /// @@ -626,11 +626,11 @@ internal int Next() { randomNumber = InternalSample(); } - while (randomNumber == Int32.MaxValue); + while (randomNumber == int.MaxValue); if (randomNumber < 0) { - randomNumber += Int32.MaxValue; + randomNumber += int.MaxValue; } return randomNumber; @@ -673,7 +673,7 @@ public int Next(int minValue, int maxValue) } else { - double largeSample = InternalSampleLargeRange() * (1.0 / (2 * ((uint)Int32.MaxValue))); + double largeSample = InternalSampleLargeRange() * (1.0 / (2 * ((uint)int.MaxValue))); randomNumber = (int)((long)(largeSample * range) + minValue); } @@ -724,9 +724,9 @@ private double InternalSampleLargeRange() do { randomNumber = InternalSample(); - } while (randomNumber == Int32.MaxValue); + } while (randomNumber == int.MaxValue); - randomNumber += Int32.MaxValue; + randomNumber += int.MaxValue; return randomNumber; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs index 4252a1623d6..9a647d4c72b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs @@ -296,7 +296,7 @@ private Collection GetAliasesFromFile(bool isLiteralPath) { CSVHelper csvHelper = new(','); - Int64 lineNumber = 0; + long lineNumber = 0; string line = null; while ((line = reader.ReadLine()) != null) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index 4375e21bf91..b6b8cc9bfb6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -1376,7 +1376,7 @@ public Encoding Encoding [Parameter] [ValidateNotNullOrEmpty] [ValidateCount(1, 2)] - [ValidateRange(0, Int32.MaxValue)] + [ValidateRange(0, int.MaxValue)] public new int[] Context { get => _context; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs index 975fd68ebfa..64ee818a6bd 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs @@ -165,7 +165,7 @@ public Encoding Encoding /// Value must be greater than zero. /// [Parameter(ValueFromPipelineByPropertyName = true)] - [ValidateRange(0, Int32.MaxValue)] + [ValidateRange(0, int.MaxValue)] public int Port { get; set; } #endregion diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs index 77b0dce3470..8128c1a84ca 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs @@ -78,13 +78,13 @@ protected override void ProcessRecord() #else // build up the SystemTime struct to pass to SetSystemTime NativeMethods.SystemTime systemTime = new(); - systemTime.Year = (UInt16)dateToUse.Year; - systemTime.Month = (UInt16)dateToUse.Month; - systemTime.Day = (UInt16)dateToUse.Day; - systemTime.Hour = (UInt16)dateToUse.Hour; - systemTime.Minute = (UInt16)dateToUse.Minute; - systemTime.Second = (UInt16)dateToUse.Second; - systemTime.Milliseconds = (UInt16)dateToUse.Millisecond; + systemTime.Year = (ushort)dateToUse.Year; + systemTime.Month = (ushort)dateToUse.Month; + systemTime.Day = (ushort)dateToUse.Day; + systemTime.Hour = (ushort)dateToUse.Hour; + systemTime.Minute = (ushort)dateToUse.Minute; + systemTime.Second = (ushort)dateToUse.Second; + systemTime.Milliseconds = (ushort)dateToUse.Millisecond; #pragma warning disable 56523 if (!NativeMethods.SetLocalTime(ref systemTime)) { @@ -118,14 +118,14 @@ internal static class NativeMethods [StructLayout(LayoutKind.Sequential)] public struct SystemTime { - public UInt16 Year; - public UInt16 Month; - public UInt16 DayOfWeek; - public UInt16 Day; - public UInt16 Hour; - public UInt16 Minute; - public UInt16 Second; - public UInt16 Milliseconds; + public ushort Year; + public ushort Month; + public ushort DayOfWeek; + public ushort Day; + public ushort Hour; + public ushort Minute; + public ushort Second; + public ushort Milliseconds; } [DllImport(PinvokeDllNames.SetLocalTimeDllName, SetLastError = true)] diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs index 330716af151..60b05807d48 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs @@ -75,14 +75,14 @@ public class ShowCommandCommand : PSCmdlet, IDisposable /// Gets or sets the Width. /// [Parameter] - [ValidateRange(300, Int32.MaxValue)] + [ValidateRange(300, int.MaxValue)] public double Height { get; set; } /// /// Gets or sets the Width. /// [Parameter] - [ValidateRange(300, Int32.MaxValue)] + [ValidateRange(300, int.MaxValue)] public double Width { get; set; } /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs index 69b89e928ce..4deb6f5d50c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs @@ -188,11 +188,11 @@ public ByteCollection(byte[] value) /// Gets the Offset address to be used while displaying the bytes in the collection. /// [Obsolete("The property is deprecated, please use Offset64 instead.", true)] - public UInt32 Offset + public uint Offset { get { - return (UInt32)Offset64; + return (uint)Offset64; } private set @@ -204,7 +204,7 @@ private set /// /// Gets the Offset address to be used while displaying the bytes in the collection. /// - public UInt64 Offset64 { get; private set; } + public ulong Offset64 { get; private set; } /// /// Gets underlying bytes stored in the collection. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs index 70ac9e4ae95..a8ca247671c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs @@ -42,7 +42,7 @@ public string SourceIdentifier /// [Parameter] [Alias("TimeoutSec")] - [ValidateRangeAttribute(-1, Int32.MaxValue)] + [ValidateRangeAttribute(-1, int.MaxValue)] public int Timeout { get diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index 235aaf82773..8c1ec228bb4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -60,7 +60,7 @@ public SwitchParameter FollowRelLink /// [Parameter] [Alias("ML")] - [ValidateRange(1, Int32.MaxValue)] + [ValidateRange(1, int.MaxValue)] public int MaximumFollowRelLink { get { return base._maximumFollowRelLink; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index e4cdef24822..604582661a0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -206,7 +206,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet /// Gets or sets the TimeOut property. /// [Parameter] - [ValidateRange(0, Int32.MaxValue)] + [ValidateRange(0, int.MaxValue)] public virtual int TimeoutSec { get; set; } /// @@ -224,7 +224,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet /// Gets or sets the RedirectMax property. /// [Parameter] - [ValidateRange(0, Int32.MaxValue)] + [ValidateRange(0, int.MaxValue)] public virtual int MaximumRedirection { get { return _maximumRedirection; } @@ -238,14 +238,14 @@ public virtual int MaximumRedirection /// Gets or sets the MaximumRetryCount property, which determines the number of retries of a failed web request. /// [Parameter] - [ValidateRange(0, Int32.MaxValue)] + [ValidateRange(0, int.MaxValue)] public virtual int MaximumRetryCount { get; set; } /// /// Gets or sets the RetryIntervalSec property, which determines the number seconds between retries. /// [Parameter] - [ValidateRange(1, Int32.MaxValue)] + [ValidateRange(1, int.MaxValue)] public virtual int RetryIntervalSec { get; set; } = 5; #endregion @@ -940,7 +940,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet /// /// Maximum number of Rel Links to follow. /// - internal int _maximumFollowRelLink = Int32.MaxValue; + internal int _maximumFollowRelLink = int.MaxValue; /// /// The remote endpoint returned a 206 status code indicating successful resume. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs index 3a60e65909d..ff576c7e68f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -551,7 +551,7 @@ private static object ProcessValue(object obj, int currentDepth, in ConvertToJso // Win8:378368 Enums based on System.Int64 or System.UInt64 are not JSON-serializable // because JavaScript does not support the necessary precision. Type enumUnderlyingType = Enum.GetUnderlyingType(obj.GetType()); - if (enumUnderlyingType.Equals(typeof(Int64)) || enumUnderlyingType.Equals(typeof(UInt64))) + if (enumUnderlyingType.Equals(typeof(long)) || enumUnderlyingType.Equals(typeof(ulong))) { rv = obj.ToString(); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs index fe8fccb6e1a..fd5476751ad 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs @@ -36,7 +36,7 @@ public sealed class WriteProgressCommand : PSCmdlet /// Uniquely identifies this activity for purposes of chaining subordinate activities. /// [Parameter(Position = 2)] - [ValidateRange(0, Int32.MaxValue)] + [ValidateRange(0, int.MaxValue)] public int Id { get; set; } /// @@ -62,7 +62,7 @@ public sealed class WriteProgressCommand : PSCmdlet /// Identifies the parent Id of this activity, or -1 if none. /// [Parameter] - [ValidateRange(-1, Int32.MaxValue)] + [ValidateRange(-1, int.MaxValue)] public int ParentId { get; set; } = -1; /// diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs index f5903ded5bc..7aa0b634474 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs @@ -20,20 +20,20 @@ internal static class ComInterfaces [StructLayout(LayoutKind.Sequential)] internal readonly struct StartUpInfo { - public readonly UInt32 cb; + public readonly uint cb; private readonly IntPtr lpReserved; public readonly IntPtr lpDesktop; public readonly IntPtr lpTitle; - public readonly UInt32 dwX; - public readonly UInt32 dwY; - public readonly UInt32 dwXSize; - public readonly UInt32 dwYSize; - public readonly UInt32 dwXCountChars; - public readonly UInt32 dwYCountChars; - public readonly UInt32 dwFillAttribute; - public readonly UInt32 dwFlags; - public readonly UInt16 wShowWindow; - private readonly UInt16 cbReserved2; + public readonly uint dwX; + public readonly uint dwY; + public readonly uint dwXSize; + public readonly uint dwYSize; + public readonly uint dwXCountChars; + public readonly uint dwYCountChars; + public readonly uint dwFillAttribute; + public readonly uint dwFlags; + public readonly ushort wShowWindow; + private readonly ushort cbReserved2; private readonly IntPtr lpReserved2; public readonly IntPtr hStdInput; public readonly IntPtr hStdOutput; @@ -248,13 +248,13 @@ void AddFromArray( internal interface IShellLinkDataListW { [PreserveSig] - Int32 AddDataBlock(IntPtr pDataBlock); + int AddDataBlock(IntPtr pDataBlock); [PreserveSig] - Int32 CopyDataBlock(UInt32 dwSig, out IntPtr ppDataBlock); + int CopyDataBlock(uint dwSig, out IntPtr ppDataBlock); [PreserveSig] - Int32 RemoveDataBlock(UInt32 dwSig); + int RemoveDataBlock(uint dwSig); void GetFlags(out uint pdwFlags); diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs index ecd1918492b..93346424dc5 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs @@ -21,7 +21,7 @@ namespace Microsoft.PowerShell /// /// Property identifier (PID) /// - public Int32 PropertyId { get; } + public int PropertyId { get; } #endregion @@ -32,7 +32,7 @@ namespace Microsoft.PowerShell /// /// A unique GUID for the property. /// Property identifier (PID). - internal PropertyKey(Guid formatId, Int32 propertyId) + internal PropertyKey(Guid formatId, int propertyId) { this.FormatId = formatId; this.PropertyId = propertyId; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index 3b78674d89b..88964ea7a25 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -275,13 +275,13 @@ internal struct MouseInput /// The absolute position of the mouse, or the amount of motion since the last mouse event was generated, depending on the value of the dwFlags member. /// Absolute data is specified as the x coordinate of the mouse; relative data is specified as the number of pixels moved. /// - internal Int32 X; + internal int X; /// /// The absolute position of the mouse, or the amount of motion since the last mouse event was generated, depending on the value of the dwFlags member. /// Absolute data is specified as the y coordinate of the mouse; relative data is specified as the number of pixels moved. /// - internal Int32 Y; + internal int Y; /// /// If dwFlags contains MOUSEEVENTF_WHEEL, then mouseData specifies the amount of wheel movement. A positive value indicates that the wheel was rotated forward, away from the user; @@ -450,7 +450,7 @@ internal enum KeyboardFlag : uint /// True if it was successful. [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow); + internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); internal static void SetConsoleMode(ProcessWindowStyle style) { @@ -3175,7 +3175,7 @@ ref CHAR_INFO fill ); [DllImport(PinvokeDllNames.SendInputDllName, SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern UInt32 SendInput(UInt32 inputNumbers, INPUT[] inputs, Int32 sizeOfInput); + internal static extern UInt32 SendInput(UInt32 inputNumbers, INPUT[] inputs, int sizeOfInput); // There is no GetCurrentConsoleFontEx on Core [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index a3df2a6c390..822daa12828 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -1338,7 +1338,7 @@ public override void WriteWarningLine(string message) /// /// Invoked by CommandBase.WriteProgress to display a progress record. /// - public override void WriteProgress(Int64 sourceId, ProgressRecord record) + public override void WriteProgress(long sourceId, ProgressRecord record) { Dbg.Assert(record != null, "WriteProgress called with null ProgressRecord"); @@ -2116,20 +2116,20 @@ private static void SendLeftArrows(int length) for (int i = 0; i < length; i++) { var down = new ConsoleControl.INPUT(); - down.Type = (UInt32)ConsoleControl.InputType.Keyboard; + down.Type = (uint)ConsoleControl.InputType.Keyboard; down.Data.Keyboard = new ConsoleControl.KeyboardInput(); - down.Data.Keyboard.Vk = (UInt16)ConsoleControl.VirtualKeyCode.Left; + down.Data.Keyboard.Vk = (ushort)ConsoleControl.VirtualKeyCode.Left; down.Data.Keyboard.Scan = 0; down.Data.Keyboard.Flags = 0; down.Data.Keyboard.Time = 0; down.Data.Keyboard.ExtraInfo = IntPtr.Zero; var up = new ConsoleControl.INPUT(); - up.Type = (UInt32)ConsoleControl.InputType.Keyboard; + up.Type = (uint)ConsoleControl.InputType.Keyboard; up.Data.Keyboard = new ConsoleControl.KeyboardInput(); - up.Data.Keyboard.Vk = (UInt16)ConsoleControl.VirtualKeyCode.Left; + up.Data.Keyboard.Vk = (ushort)ConsoleControl.VirtualKeyCode.Left; up.Data.Keyboard.Scan = 0; - up.Data.Keyboard.Flags = (UInt32)ConsoleControl.KeyboardFlag.KeyUp; + up.Data.Keyboard.Flags = (uint)ConsoleControl.KeyboardFlag.KeyUp; up.Data.Keyboard.Time = 0; up.Data.Keyboard.ExtraInfo = IntPtr.Zero; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs index c2bbf74c7c8..a9b98b38934 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs @@ -63,7 +63,7 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt /// private void - HandleIncomingProgressRecord(Int64 sourceId, ProgressRecord record) + HandleIncomingProgressRecord(long sourceId, ProgressRecord record) { Dbg.Assert(record != null, "record should not be null"); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs index 08e7962204f..6bb85c64729 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs @@ -43,7 +43,7 @@ class PendingProgress /// internal void - Update(Int64 sourceId, ProgressRecord record) + Update(long sourceId, ProgressRecord record) { Dbg.Assert(record != null, "record should not be null"); @@ -357,7 +357,7 @@ internal override /// private ProgressNode - FindNodeById(Int64 sourceId, int activityId) + FindNodeById(long sourceId, int activityId) { ArrayList listWhereFound = null; int indexWhereFound = -1; @@ -368,7 +368,7 @@ internal override private sealed class FindByIdNodeVisitor : NodeVisitor { internal - FindByIdNodeVisitor(Int64 sourceIdToFind, int activityIdToFind) + FindByIdNodeVisitor(long sourceIdToFind, int activityIdToFind) { _sourceIdToFind = sourceIdToFind; _idToFind = activityIdToFind; @@ -402,7 +402,7 @@ internal override IndexWhereFound = -1; private readonly int _idToFind = -1; - private readonly Int64 _sourceIdToFind; + private readonly long _sourceIdToFind; } /// @@ -426,7 +426,7 @@ internal override /// private ProgressNode - FindNodeById(Int64 sourceId, int activityId, out ArrayList listWhereFound, out int indexWhereFound) + FindNodeById(long sourceId, int activityId, out ArrayList listWhereFound, out int indexWhereFound) { listWhereFound = null; indexWhereFound = -1; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs index 17d852f952e..f6d1538b8da 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs @@ -54,7 +54,7 @@ namespace Microsoft.PowerShell /// Constructs an instance from a ProgressRecord. /// internal - ProgressNode(Int64 sourceId, ProgressRecord record) + ProgressNode(long sourceId, ProgressRecord record) : base(record.ActivityId, record.Activity, record.StatusDescription) { Dbg.Assert(record.RecordType == ProgressRecordType.Processing, "should only create node for Processing records"); @@ -485,7 +485,7 @@ internal static bool IsMinimalProgressRenderingEnabled() /// Identifies the source of the progress record. /// internal - Int64 + long SourceId; /// diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs index c29c9e82179..293cd1faf44 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -331,10 +331,10 @@ to fill the passed in ETW data descriptor. *uintptr = (uint)data; dataDescriptor->DataPointer = (ulong)uintptr; } - else if (data is UInt64) + else if (data is ulong) { dataDescriptor->Size = (uint)sizeof(ulong); - UInt64* ulongptr = (ulong*)dataBuffer; + ulong* ulongptr = (ulong*)dataBuffer; *ulongptr = (ulong)data; dataDescriptor->DataPointer = (ulong)ulongptr; } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs index 007cf74891e..df2b064ebd5 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs @@ -307,7 +307,7 @@ public static void EvtClearLog( [System.Security.SecurityCritical] public static EventLogHandle EvtCreateRenderContext( - Int32 valuePathsCount, + int valuePathsCount, string[] valuePaths, UnsafeNativeMethods.EvtRenderContextFlags flags) { @@ -939,7 +939,7 @@ public static void EvtRenderBufferWithContextSystem(EventLogHandle contextHandle break; } - pointer = new IntPtr(((Int64)pointer + Marshal.SizeOf(varVal))); + pointer = new IntPtr(((long)pointer + Marshal.SizeOf(varVal))); } } finally @@ -984,7 +984,7 @@ public static IList EvtRenderBufferWithContextUserOrValues(EventLogHandl { UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(pointer); valuesList.Add(ConvertToObject(varVal)); - pointer = new IntPtr(((Int64)pointer + Marshal.SizeOf(varVal))); + pointer = new IntPtr(((long)pointer + Marshal.SizeOf(varVal))); } } @@ -1106,7 +1106,7 @@ public static IEnumerable EvtFormatMessageRenderKeywords(EventLogHandle break; keywordsList.Add(s); // nr of bytes = # chars * 2 + 2 bytes for character '\0'. - pointer = new IntPtr((Int64)pointer + (s.Length * 2) + 2); + pointer = new IntPtr((long)pointer + (s.Length * 2) + 2); } return keywordsList.AsReadOnly(); @@ -1270,23 +1270,23 @@ private static object ConvertToObject(UnsafeNativeMethods.EvtVariant val) Marshal.Copy(val.Reference, arByte, 0, (int)val.Count); return arByte; case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt16): - if (val.Reference == IntPtr.Zero) return Array.Empty(); - Int16[] arInt16 = new Int16[val.Count]; + if (val.Reference == IntPtr.Zero) return Array.Empty(); + short[] arInt16 = new short[val.Count]; Marshal.Copy(val.Reference, arInt16, 0, (int)val.Count); return arInt16; case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt32): - if (val.Reference == IntPtr.Zero) return Array.Empty(); - Int32[] arInt32 = new Int32[val.Count]; + if (val.Reference == IntPtr.Zero) return Array.Empty(); + int[] arInt32 = new int[val.Count]; Marshal.Copy(val.Reference, arInt32, 0, (int)val.Count); return arInt32; case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt64): - if (val.Reference == IntPtr.Zero) return Array.Empty(); - Int64[] arInt64 = new Int64[val.Count]; + if (val.Reference == IntPtr.Zero) return Array.Empty(); + long[] arInt64 = new long[val.Count]; Marshal.Copy(val.Reference, arInt64, 0, (int)val.Count); return arInt64; case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSingle): - if (val.Reference == IntPtr.Zero) return Array.Empty(); - Single[] arSingle = new Single[val.Count]; + if (val.Reference == IntPtr.Zero) return Array.Empty(); + float[] arSingle = new float[val.Count]; Marshal.Copy(val.Reference, arSingle, 0, (int)val.Count); return arSingle; case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeDouble): @@ -1297,13 +1297,13 @@ private static object ConvertToObject(UnsafeNativeMethods.EvtVariant val) case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSByte): return ConvertToArray(val, sizeof(sbyte)); // not CLS-compliant case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt16): - return ConvertToArray(val, sizeof(UInt16)); + return ConvertToArray(val, sizeof(ushort)); case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64): case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt64): - return ConvertToArray(val, sizeof(UInt64)); + return ConvertToArray(val, sizeof(ulong)); case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32): case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt32): - return ConvertToArray(val, sizeof(UInt32)); + return ConvertToArray(val, sizeof(uint)); case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString): return ConvertToStringArray(val, false); case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeAnsiString): @@ -1375,7 +1375,7 @@ public static Array ConvertToArray(UnsafeNativeMethods.EvtVariant val, int si for (int i = 0; i < val.Count; i++) { array.SetValue(Marshal.PtrToStructure(ptr), i); - ptr = new IntPtr((Int64)ptr + size); + ptr = new IntPtr((long)ptr + size); } return array; @@ -1398,7 +1398,7 @@ public static Array ConvertToBoolArray(UnsafeNativeMethods.EvtVariant val) { bool value = Marshal.ReadInt32(ptr) != 0; array[i] = value; - ptr = new IntPtr((Int64)ptr + 4); + ptr = new IntPtr((long)ptr + 4); } return array; @@ -1419,7 +1419,7 @@ public static Array ConvertToFileTimeArray(UnsafeNativeMethods.EvtVariant val) for (int i = 0; i < val.Count; i++) { array[i] = DateTime.FromFileTime(Marshal.ReadInt64(ptr)); - ptr = new IntPtr((Int64)ptr + 8 * sizeof(byte)); // FILETIME values are 8 bytes + ptr = new IntPtr((long)ptr + 8 * sizeof(byte)); // FILETIME values are 8 bytes } return array; @@ -1441,7 +1441,7 @@ public static Array ConvertToSysTimeArray(UnsafeNativeMethods.EvtVariant val) { UnsafeNativeMethods.SystemTime sysTime = Marshal.PtrToStructure(ptr); array[i] = new DateTime(sysTime.Year, sysTime.Month, sysTime.Day, sysTime.Hour, sysTime.Minute, sysTime.Second, sysTime.Milliseconds); - ptr = new IntPtr((Int64)ptr + 16 * sizeof(byte)); // SystemTime values are 16 bytes + ptr = new IntPtr((long)ptr + 16 * sizeof(byte)); // SystemTime values are 16 bytes } return array; diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs index 99163f33974..b7beee133ed 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs @@ -268,10 +268,10 @@ internal struct SystemTime internal struct EvtVariant { [FieldOffset(0)] - public UInt32 UInteger; + public uint UInteger; [FieldOffset(0)] - public Int32 Integer; + public int Integer; [FieldOffset(0)] public byte UInt8; @@ -283,7 +283,7 @@ internal struct EvtVariant public ushort UShort; [FieldOffset(0)] - public UInt32 Bool; + public uint Bool; [FieldOffset(0)] public byte ByteVal; @@ -292,13 +292,13 @@ internal struct EvtVariant public byte SByte; [FieldOffset(0)] - public UInt64 ULong; + public ulong ULong; [FieldOffset(0)] - public Int64 Long; + public long Long; [FieldOffset(0)] - public Single Single; + public float Single; [FieldOffset(0)] public double Double; @@ -325,7 +325,7 @@ internal struct EvtVariant public IntPtr GuidReference; [FieldOffset(0)] - public UInt64 FileTime; + public ulong FileTime; [FieldOffset(0)] public IntPtr SystemTime; @@ -334,10 +334,10 @@ internal struct EvtVariant public IntPtr SizeT; [FieldOffset(8)] - public UInt32 Count; // number of elements (not length) in bytes. + public uint Count; // number of elements (not length) in bytes. [FieldOffset(12)] - public UInt32 Type; + public uint Type; } internal enum EvtEventPropertyId @@ -733,7 +733,7 @@ out int publisherIdBufferUsed [SecurityCritical] internal static extern EventLogHandle EvtOpenChannelConfig( EventLogHandle session, - [MarshalAs(UnmanagedType.LPWStr)] String channelPath, + [MarshalAs(UnmanagedType.LPWStr)] string channelPath, int flags ); @@ -823,7 +823,7 @@ int flags [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] [SecurityCritical] internal static extern EventLogHandle EvtCreateRenderContext( - Int32 valuePathsCount, + int valuePathsCount, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] valuePaths, [MarshalAs(UnmanagedType.I4)] EvtRenderContextFlags flags @@ -862,10 +862,10 @@ internal struct EvtStringVariant public string StringVal; [FieldOffset(8)] - public UInt32 Count; + public uint Count; [FieldOffset(12)] - public UInt32 Type; + public uint Type; } [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] diff --git a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs index da4dcf59d47..821fe608efa 100644 --- a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs @@ -239,7 +239,7 @@ public ConvertToSecureStringCommand() : base("ConvertTo-SecureString") { } /// Gets or sets the unsecured string to be imported. /// [Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)] - public String String + public string String { get { diff --git a/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index 9e3d9bd05b1..de99812b01d 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -5607,15 +5607,15 @@ public string ApplicationName [Parameter] [ValidateNotNullOrEmpty] [Parameter(ParameterSetName = "nameSet")] - [ValidateRange(1, Int32.MaxValue)] - public Int32 Port + [ValidateRange(1, int.MaxValue)] + public int Port { get { return port; } set { port = value; } } - private Int32 port = 0; + private int port = 0; /// /// The following is the definition of the input parameter "UseSSL". diff --git a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs index 36f65e52705..16e91cceae9 100644 --- a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs +++ b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs @@ -146,15 +146,15 @@ public Hashtable OptionSet /// [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] - [ValidateRange(1, Int32.MaxValue)] - public Int32 Port + [ValidateRange(1, int.MaxValue)] + public int Port { get { return port; } set { port = value; } } - private Int32 port = 0; + private int port = 0; /// /// The following is the definition of the input parameter "SelectorSet". diff --git a/src/Microsoft.WSMan.Management/NewWSManSession.cs b/src/Microsoft.WSMan.Management/NewWSManSession.cs index 30959f3ced5..25f5bdd5989 100644 --- a/src/Microsoft.WSMan.Management/NewWSManSession.cs +++ b/src/Microsoft.WSMan.Management/NewWSManSession.cs @@ -170,8 +170,8 @@ public SwitchParameter SkipRevocationCheck /// [Parameter] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")] - [ValidateRange(0, Int32.MaxValue)] - public Int32 SPNPort + [ValidateRange(0, int.MaxValue)] + public int SPNPort { get { @@ -184,7 +184,7 @@ public Int32 SPNPort } } - private Int32 spnport; + private int spnport; /// /// The following is the definition of the input parameter "Timeout". @@ -192,8 +192,8 @@ public Int32 SPNPort /// [Parameter] [Alias("OperationTimeoutMSec")] - [ValidateRange(0, Int32.MaxValue)] - public Int32 OperationTimeout + [ValidateRange(0, int.MaxValue)] + public int OperationTimeout { get { @@ -206,7 +206,7 @@ public Int32 OperationTimeout } } - private Int32 operationtimeout; + private int operationtimeout; /// /// The following is the definition of the input parameter "UnEncrypted". diff --git a/src/Microsoft.WSMan.Management/PingWSMan.cs b/src/Microsoft.WSMan.Management/PingWSMan.cs index a04167a0f1b..b9a0e21f1f4 100644 --- a/src/Microsoft.WSMan.Management/PingWSMan.cs +++ b/src/Microsoft.WSMan.Management/PingWSMan.cs @@ -95,15 +95,15 @@ public override AuthenticationMechanism Authentication /// [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] - [ValidateRange(1, Int32.MaxValue)] - public Int32 Port + [ValidateRange(1, int.MaxValue)] + public int Port { get { return port; } set { port = value; } } - private Int32 port = 0; + private int port = 0; /// /// The following is the definition of the input parameter "UseSSL". diff --git a/src/Microsoft.WSMan.Management/WSManConnections.cs b/src/Microsoft.WSMan.Management/WSManConnections.cs index 85c5d1ba0ae..c83ed7e9e10 100644 --- a/src/Microsoft.WSMan.Management/WSManConnections.cs +++ b/src/Microsoft.WSMan.Management/WSManConnections.cs @@ -213,15 +213,15 @@ public Hashtable OptionSet [Parameter] [ValidateNotNullOrEmpty] [Parameter(ParameterSetName = "ComputerName")] - [ValidateRange(1, Int32.MaxValue)] - public Int32 Port + [ValidateRange(1, int.MaxValue)] + public int Port { get { return port; } set { port = value; } } - private Int32 port = 0; + private int port = 0; /// /// The following is the definition of the input parameter "SessionOption". diff --git a/src/Microsoft.WSMan.Management/WSManInstance.cs b/src/Microsoft.WSMan.Management/WSManInstance.cs index 733316c785f..a60ba270104 100644 --- a/src/Microsoft.WSMan.Management/WSManInstance.cs +++ b/src/Microsoft.WSMan.Management/WSManInstance.cs @@ -247,7 +247,7 @@ public Hashtable OptionSet /// [Parameter(ParameterSetName = "Enumerate")] [Parameter(ParameterSetName = "GetInstance")] - public Int32 Port + public int Port { get { @@ -260,7 +260,7 @@ public Int32 Port } } - private Int32 port = 0; + private int port = 0; /// /// The following is the definition of the input parameter "Associations". @@ -822,15 +822,15 @@ public Hashtable OptionSet /// [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] - [ValidateRange(1, Int32.MaxValue)] - public Int32 Port + [ValidateRange(1, int.MaxValue)] + public int Port { get { return port; } set { port = value; } } - private Int32 port = 0; + private int port = 0; /// /// The following is the definition of the input parameter "ResourceURI". @@ -1146,15 +1146,15 @@ public Hashtable OptionSet /// [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] - [ValidateRange(1, Int32.MaxValue)] - public Int32 Port + [ValidateRange(1, int.MaxValue)] + public int Port { get { return port; } set { port = value; } } - private Int32 port = 0; + private int port = 0; /// /// The following is the definition of the input parameter "ResourceURI". @@ -1428,15 +1428,15 @@ public Hashtable OptionSet /// [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] - [ValidateRange(1, Int32.MaxValue)] - public Int32 Port + [ValidateRange(1, int.MaxValue)] + public int Port { get { return port; } set { port = value; } } - private Int32 port = 0; + private int port = 0; /// /// The following is the definition of the input parameter "ResourceURI". From a77be13227113a46af01f8088c139637a21c18c6 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 29 Jul 2021 20:32:21 +0100 Subject: [PATCH 14/55] Partially revert changes to code style src/Microsoft.Management.UI.Internal/ (#15839) --- .../HelpWindow/HelpViewModel.cs | 3 --- .../HelpWindow/ParagraphBuilder.cs | 8 -------- .../ManagementList/Common/DismissiblePopup.cs | 2 -- .../ManagementList/Common/ListOrganizerItem.cs | 2 -- .../Common/ReadOnlyObservableAsyncCollection.cs | 5 ----- .../ManagementList/CommonControls/Resizer.cs | 3 --- .../FilterCore/DefaultFilterRuleCustomizationFactory.cs | 4 ---- .../ManagementList/FilterCore/FilterEvaluator.cs | 5 ----- .../ManagementList/FilterCore/ValidatingValue.cs | 2 -- .../FilterProviders/AddFilterRulePicker.cs | 3 --- .../FilterProviders/InputFieldBackgroundTextConverter.cs | 3 --- .../ManagementList/ManagementList/Innerlist.cs | 4 ---- .../ManagementList/PropertyValueComparer.cs | 2 -- .../ManagementList/ManagementList/PropertyValueGetter.cs | 2 -- .../ManagementList/ManagementList/managementlist.cs | 2 -- .../ShowCommand/Controls/ParameterSetControl.xaml.cs | 3 --- .../ShowCommand/ViewModel/AllModulesViewModel.cs | 9 --------- .../ShowCommand/ViewModel/ModuleViewModel.cs | 9 --------- .../commandHelpers/OutGridView.cs | 1 - .../commandHelpers/ShowCommandHelper.cs | 7 ++----- 20 files changed, 2 insertions(+), 77 deletions(-) diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs index de62923614d..7cbe4b0c74e 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs @@ -4,7 +4,6 @@ using System; using System.ComponentModel; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Management.Automation; using System.Windows.Documents; @@ -274,13 +273,11 @@ private void SetMatchesLabel() /// Property name. private void OnNotifyPropertyChanged(string propertyName) { - #pragma warning disable IDE1005 // IDE1005: Delegate invocation can be simplified. PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } - #pragma warning restore IDE1005s } } } diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs index 16b1be82f67..822e4c05026 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; using System.Text; using System.Windows.Documents; using System.Windows.Media; @@ -108,15 +107,10 @@ internal void BuildParagraph() bool newHighlighted = false; ParagraphBuilder.MoveSpanToPosition(ref currentBoldIndex, ref currentBoldSpan, i, this.boldSpans); - - #pragma warning disable IDE0075 // IDE0075: Conditional expression can be simplified newBold = currentBoldSpan == null ? false : currentBoldSpan.Value.Contains(i); - #pragma warning restore IDE0075 ParagraphBuilder.MoveSpanToPosition(ref currentHighlightedIndex, ref currentHighlightedSpan, i, this.highlightedSpans); - #pragma warning disable IDE0075 // IDE0075: Conditional expression can be simplified newHighlighted = currentHighlightedSpan == null ? false : currentHighlightedSpan.Value.Contains(i); - #pragma warning restore IDE0075 if (newBold != currentBold || newHighlighted != currentHighlighted) { @@ -307,13 +301,11 @@ private void AddHighlight(int start, int length) /// Property name. private void OnNotifyPropertyChanged(string propertyName) { - #pragma warning disable IDE1005 // IDE1005: Delegate invocation can be simplified.s PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } - #pragma warning restore IDE1005 } /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.cs index 97038e71665..582be1c7ecd 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.cs @@ -3,7 +3,6 @@ using System; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Windows; using System.Windows.Automation; using System.Windows.Controls.Primitives; @@ -80,7 +79,6 @@ protected override void OnClosed(EventArgs e) } } - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] private void SetFocus(UIElement element) { if (element.Focusable) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.cs index 276cbba283a..469ed5aec77 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.cs @@ -35,9 +35,7 @@ public bool IsInEditMode { get { - #pragma warning disable IDE0075 // IDE0075: Conditional expression can be simplified return (this.renameButton != null) ? this.renameButton.IsChecked.Value : false; - #pragma warning restore IDE0075 } } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs index 1c3e7bffb27..7734bc4903c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs @@ -6,7 +6,6 @@ using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; namespace Microsoft.Management.UI.Internal { @@ -98,8 +97,6 @@ public Exception OperationError #endregion IAsyncProgress #region Private Methods - - #pragma warning disable IDE1005 // IDE1005: Delegate invocation can be simplified. private void OnCollectionChanged(NotifyCollectionChangedEventArgs args) { NotifyCollectionChangedEventHandler eh = this.CollectionChanged; @@ -120,8 +117,6 @@ private void OnPropertyChanged(PropertyChangedEventArgs args) } } - #pragma warning restore IDE1005 - // forward CollectionChanged events from the base list to our listeners private void HandleCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.cs index 36ed7e62e3d..19c0671bf21 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.cs @@ -4,7 +4,6 @@ using System; using System.ComponentModel; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; @@ -203,7 +202,6 @@ private double GetNewWidth(ResizeGripLocation location, double horzDelta) return this.GetConstrainedValue(newWidth, this.MaxWidth, this.MinWidth); } - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] private double GetHorizontalDelta(ResizeGripLocation location, double horzDelta) { double realDelta; @@ -221,7 +219,6 @@ private double GetHorizontalDelta(ResizeGripLocation location, double horzDelta) return realDelta; } - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] private double GetConstrainedValue(double value, double max, double min) { return Math.Min(max, Math.Max(value, min)); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs index 2fa13516bde..bd5faf32d63 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; @@ -197,7 +196,6 @@ public override string GetErrorMessageForInvalidValue(string value, Type typeToP #region Helpers - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] private bool TryGetGenericParameterForComparableValueFilterRule(FilterRule rule, out Type genericParameter) { genericParameter = null; @@ -219,7 +217,6 @@ private bool TryGetGenericParameterForComparableValueFilterRule(FilterRule rule, return true; } - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] private object GetValueFromValidatingValue(FilterRule rule, string propertyName) { Debug.Assert(rule != null && !string.IsNullOrEmpty(propertyName), "rule and propertyname are not null"); @@ -239,7 +236,6 @@ private object GetValueFromValidatingValue(FilterRule rule, string propertyName) return property.GetValue(validatingValue, null); } - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] private void SetValueOnValidatingValue(FilterRule rule, string propertyName, object value) { Debug.Assert(rule != null && !string.IsNullOrEmpty(propertyName), "rule and propertyname are not null"); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs index 46ada50ebef..2b33153a983 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs @@ -5,7 +5,6 @@ using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; namespace Microsoft.Management.UI.Internal { @@ -174,8 +173,6 @@ public void RemoveFilterExpressionProvider(IFilterExpressionProvider provider) #region NotifyPropertyChanged - #pragma warning disable IDE1005 // IDE1005: Delegate invocation can be simplified. - /// /// Notifies listeners that a property has changed. /// @@ -217,8 +214,6 @@ protected virtual void NotifyFilterExpressionChanged() } } - #pragma warning restore IDE1005 - private void FilterProvider_FilterExpressionChanged(object sender, EventArgs e) { // Update HasFilterExpression \\ diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs index 62bb3ca7517..cf9c553f6b4 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs @@ -3,7 +3,6 @@ using System; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace Microsoft.Management.UI.Internal @@ -191,7 +190,6 @@ private bool TryGetCastValue(object rawValue, out T castValue) } } - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] private bool TryGetEnumValue(object rawValue, out T castValue) { Debug.Assert(rawValue != null, "rawValue not null"); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.cs index a4e13c6c9f5..d41b0a3e532 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.cs @@ -4,7 +4,6 @@ using System; using System.Collections.ObjectModel; using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; using System.Windows.Controls; namespace Microsoft.Management.UI.Internal @@ -50,11 +49,9 @@ public ObservableCollection ColumnFilterRules partial void OnOkAddFilterRulesCanExecuteImplementation(System.Windows.Input.CanExecuteRoutedEventArgs e) { - #pragma warning disable IDE0075 // IDE0075: Conditional expression can be simplified e.CanExecute = (this.AddFilterRulesCommand != null) ? CommandHelper.CanExecuteCommand(this.AddFilterRulesCommand, null, this.AddFilterRulesCommandTarget) : false; - #pragma warning restore IDE0075 } partial void OnOkAddFilterRulesExecutedImplementation(System.Windows.Input.ExecutedRoutedEventArgs e) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs index e19eae34a3e..0017f2a4340 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Windows.Data; @@ -70,7 +69,6 @@ public object ConvertBack(object value, Type targetType, object parameter, Syste #region Helpers - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] private bool IsOfTypeValidatingValue(object value) { Debug.Assert(value != null, "not null"); @@ -94,7 +92,6 @@ private Type GetGenericParameter(object value, CultureInfo culture) return value.GetType().GetGenericArguments()[0]; } - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] private object GetBackgroundTextForType(Type inputType) { if (typeof(DateTime) == inputType) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs index a01435b2414..78a8da29c65 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs @@ -8,7 +8,6 @@ using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Windows; @@ -402,14 +401,12 @@ private static void InnerList_OnViewChanged(DependencyObject obj, DependencyProp /// The exception to be thrown when using Items. private static NotSupportedException GetItemsException() { - #pragma warning disable IDE1005 // IDE1005: Delegate invocation can be simplified. return new NotSupportedException( string.Format( CultureInfo.InvariantCulture, InvariantResources.NotSupportAddingToItems, nameof(InnerList), ItemsControl.ItemsSourceProperty.Name)); - #pragma warning restore IDE1005s } #endregion static private methods @@ -608,7 +605,6 @@ private string GetClipboardTextLineForSelectedItem(object value) return entryText.ToString(); } - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] private void SetClipboardWithSelectedItemsText(string text) { if (string.IsNullOrEmpty(text)) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueComparer.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueComparer.cs index 996eb8b72de..5c9f56daa81 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueComparer.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueComparer.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Management.Automation; namespace Microsoft.Management.UI.Internal @@ -89,7 +88,6 @@ private void GetPropertyValues(string propertyName, object a, object b, out obje } } - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] private int CompareData(object firstValue, object secondValue, StringComparison stringComparison) { // If both values are null, do nothing; otherwise, if one is null promote the other \\ diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs index 8ec9e5ecb7d..61a1a71938c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs @@ -4,7 +4,6 @@ using System; using System.ComponentModel; using System.Data; -using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace Microsoft.Management.UI.Internal @@ -111,7 +110,6 @@ private PropertyDescriptor GetPropertyDescriptor(string propertyName, object val return descriptor; } - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] private bool TryGetPropertyValueInternal(PropertyDescriptor descriptor, object value, out object propertyValue) { propertyValue = null; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs index fab4e721bec..7c36244e0f1 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs @@ -5,7 +5,6 @@ using System.Collections; using System.Collections.ObjectModel; using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Windows; using System.Windows.Controls; @@ -309,7 +308,6 @@ partial void OnClearFilterExecutedImplementation(ExecutedRoutedEventArgs e) #region View Manager Callbacks - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] partial void OnSaveViewCanExecuteImplementation(CanExecuteRoutedEventArgs e) { string viewName = (string)e.Parameter; diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs index a38e4003af3..08f9df29337 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs @@ -4,7 +4,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Management.Automation; using System.Windows; @@ -345,7 +344,6 @@ private void CheckBox_Click(object sender, RoutedEventArgs e) /// Creates a RowDefinition for MainGrid. /// /// Return a RowDefinition object. - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] private RowDefinition CreateNewRow() { RowDefinition row = new RowDefinition(); @@ -384,7 +382,6 @@ private void CreateAndAddLabel(ParameterViewModel parameterViewModel, int rowNum /// DataContext object. /// Row number. /// Return a Label control. - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] private Label CreateLabel(ParameterViewModel parameterViewModel, int rowNumber) { Label label = new Label(); diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs index 8040c4cb45a..34159c8f837 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Management.Automation; @@ -80,12 +79,10 @@ public class AllModulesViewModel : INotifyPropertyChanged /// Commands to show. public AllModulesViewModel(Dictionary importedModules, IEnumerable commands) { - #pragma warning disable IDE0075 // IDE0075: Conditional expression can be simplified if (commands == null || !commands.GetEnumerator().MoveNext()) { throw new ArgumentNullException("commands"); } - #pragma warning disable IDE0075 // IDE0075: Conditional expression can be simplified this.Initialization(importedModules, commands, true); } @@ -403,13 +400,11 @@ public string GetScript() /// internal void OnRefresh() { - #pragma warning disable IDE1005 // IDE1005: Delegate invocation can be simplified. EventHandler handler = this.Refresh; if (handler != null) { handler(this, new EventArgs()); } - #pragma warning restore IDE1005s } #region Private Methods @@ -598,8 +593,6 @@ private void SelectedModule_SelectedCommandNeedsImportModule(object sender, Impo this.OnSelectedCommandInSelectedModuleNeedsImportModule(e); } - #pragma warning disable IDE1005 // IDE1005: Delegate invocation can be simplified. - /// /// Triggers SelectedCommandInSelectedModuleNeedsHelp. /// @@ -661,8 +654,6 @@ private void OnNotifyPropertyChanged(string propertyName) handler(this, new PropertyChangedEventArgs(propertyName)); } } - - #pragma warning restore IDE1005s #endregion } } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs index d6a2e57c051..38925e458a9 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; using System.Management.Automation; using System.Windows; @@ -77,8 +76,6 @@ public ModuleViewModel(string name, Dictionary im this.commands = new List(); this.filteredCommands = new ObservableCollection(); - #pragma warning disable IDE0075 // IDE0075: Conditional expression can be simplified - // This check looks to see if the given module name shows up in // the set of modules that are known to be imported in the current // session. In remote PowerShell sessions, the core cmdlet module @@ -89,8 +86,6 @@ public ModuleViewModel(string name, Dictionary im importedModules == null ? true : name.Length == 0 || importedModules.ContainsKey(name) || string.Equals("Microsoft.PowerShell.Core", name, StringComparison.OrdinalIgnoreCase); - - #pragma warning restore IDE0075 } #endregion @@ -377,8 +372,6 @@ internal void RefreshFilteredCommands(string filter) } } - #pragma warning disable IDE1005 // IDE1005: Delegate invocation can be simplified. - /// /// Callled in response to a GUI event that requires the command to be run. /// @@ -534,7 +527,5 @@ private void OnNotifyPropertyChanged(string propertyName) handler(this, new PropertyChangedEventArgs(propertyName)); } } - - #pragma warning restore IDE1005 } } diff --git a/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs b/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs index 2135877655a..f38a8a70945 100644 --- a/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs +++ b/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs @@ -246,7 +246,6 @@ private void ZoomEventHandlerMinus(object sender, ExecutedRoutedEventArgs e) /// /// Output mode of the out-gridview. /// A new ManagementList. - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] private ManagementList CreateManagementList(string outputMode) { ManagementList newList = new ManagementList(); diff --git a/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs b/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs index 5ac2321cded..873f15e2c41 100644 --- a/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs +++ b/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs @@ -643,9 +643,7 @@ internal static AllModulesViewModel GetNewAllModulesViewModel(AllModulesViewMode ModuleViewModel moduleToSelect = returnValue.Modules.Find( new Predicate((module) => { - #pragma warning disable IDE0075 // IDE0075: Conditional expression can be simplified - return module.Name.Equals(selectedModuleNeedingImportModule, StringComparison.OrdinalIgnoreCase); - #pragma warning restore IDE0075 + return module.Name.Equals(selectedModuleNeedingImportModule, StringComparison.OrdinalIgnoreCase) ? true : false; })); if (moduleToSelect == null) @@ -659,7 +657,7 @@ internal static AllModulesViewModel GetNewAllModulesViewModel(AllModulesViewMode new Predicate((command) => { return command.ModuleName.Equals(parentModuleNeedingImportModule, StringComparison.OrdinalIgnoreCase) && - command.Name.Equals(commandNeedingImportModule, StringComparison.OrdinalIgnoreCase); + command.Name.Equals(commandNeedingImportModule, StringComparison.OrdinalIgnoreCase) ? true : false; })); if (commandToSelect == null) @@ -1246,7 +1244,6 @@ private void CloseWindow() /// Showing a MessageBox when user type a invalidate command name. /// /// Error message. - [SuppressMessage("Performance", "CA1822: Mark members as static", Justification = "Potential breaking change")] private void ShowErrorString(string errorString) { if (errorString != null && errorString.Trim().Length > 0) From 881f31b4b3584e1c4efdbaa0f8d819be610f8e3b Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Thu, 29 Jul 2021 22:10:33 -0700 Subject: [PATCH 15/55] Harden logic when looking for syslog entries to be sure that we select based on PID (#15841) --- test/powershell/Host/Logging.Tests.ps1 | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/test/powershell/Host/Logging.Tests.ps1 b/test/powershell/Host/Logging.Tests.ps1 index 5159d46551f..5250d2ef5ae 100644 --- a/test/powershell/Host/Logging.Tests.ps1 +++ b/test/powershell/Host/Logging.Tests.ps1 @@ -248,12 +248,15 @@ $PID It 'Verifies logging level filtering works' -Skip:(!$IsSupportedEnvironment) { $configFile = WriteLogSettings -LogId $logId -LogLevel Warning - & $powershell -NoProfile -SettingsFile $configFile -Command '$env:PSModulePath | out-null' + $result = & $powershell -NoProfile -SettingsFile $configFile -Command '$PID' + $result | Should -Not -BeNullOrEmpty # by default, PowerShell only logs informational events on startup. With Level = Warning, nothing should - # have been logged. - $items = Get-PSSysLog -Path $SyslogFile -Id $logId -Tail 100 -TotalCount 1 - $items | Should -Be $null + # have been logged. We'll collect all the syslog entries and look for $PID (there should be none). + $items = Get-PSSysLog -Path $SyslogFile + @($items).Count | Should -BeGreaterThan 0 + $logs = $items | Where-Object { $_.ProcessId -eq $result } + $logs | Should -BeNullOrEmpty } } From 1a55208590b95a20f84406953e20e83696bcc07b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 30 Jul 2021 21:18:45 +0500 Subject: [PATCH 16/55] Bump NJsonSchema from 10.4.5 to 10.4.6 (#15822) Bumps NJsonSchema from 10.4.5 to 10.4.6. --- updated-dependencies: - dependency-name: NJsonSchema dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 823d99e5b84..eb564986285 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -34,7 +34,7 @@ - + From 1bfa1c36a7a73cf0dadb3d6a1d9ffb71bcd43a67 Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Sat, 31 Jul 2021 15:51:03 +0200 Subject: [PATCH 17/55] Forwarding progress stream changes from Foreach-Object -Parallel runspaces (#14271) --- .../engine/hostifaces/PSTask.cs | 10 ++++++++++ .../Foreach-Object-Parallel.Tests.ps1 | 13 +++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/System.Management.Automation/engine/hostifaces/PSTask.cs b/src/System.Management.Automation/engine/hostifaces/PSTask.cs index 5f05d267fcd..6e08733cc2b 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSTask.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSTask.cs @@ -68,6 +68,7 @@ protected override void InitializePowershell() _powershell.Streams.Warning.DataAdded += (sender, args) => HandleWarningData(); _powershell.Streams.Verbose.DataAdded += (sender, args) => HandleVerboseData(); _powershell.Streams.Debug.DataAdded += (sender, args) => HandleDebugData(); + _powershell.Streams.Progress.DataAdded += (sender, args) => HandleProgressData(); _powershell.Streams.Information.DataAdded += (sender, args) => HandleInformationData(); // State change handler @@ -132,6 +133,15 @@ private void HandleInformationData() } } + private void HandleProgressData() + { + foreach (var item in _powershell.Streams.Progress.ReadAll()) + { + _dataStreamWriter.Add( + new PSStreamObject(PSStreamObjectType.Progress, item)); + } + } + #endregion #region Event handlers diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Foreach-Object-Parallel.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Foreach-Object-Parallel.Tests.ps1 index 46f85b80bd4..994d71601a7 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Foreach-Object-Parallel.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Foreach-Object-Parallel.Tests.ps1 @@ -138,6 +138,19 @@ Describe 'ForEach-Object -Parallel Basic Tests' -Tags 'CI' { $actualDebug.Message | Should -BeExactly 'Debug!' } + It 'Verifies progress data streaming' { + + $ps = [Powershell]::Create([System.Management.Automation.RunspaceMode]::NewRunspace) + + $ps.Commands.AddScript("`$ProgressPreference='Continue'; 1..2 | ForEach-Object -Parallel { Write-Progress -Activity Progress -Status Running }") | Out-Null + $ps.Invoke() + $pr = $ps.Streams.Progress.ReadAll() + $pr.Count | Should -Be 2 + $pr[0].Activity | Should -Be Progress + $pr[0].StatusDescription | Should -Be Running + $ps.Dispose() + } + It 'Verifies information data streaming' { $actualInformation = 1..1 | ForEach-Object -Parallel { Write-Information "Information!" } 6>&1 From d050e677268f172cbe771cbc9226472492dbe4a3 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Tue, 3 Aug 2021 08:23:40 -0700 Subject: [PATCH 18/55] Update PowerShell team members in the change log generation script (#15817) --- tools/releaseTools.psm1 | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/releaseTools.psm1 b/tools/releaseTools.psm1 index 70c8a33e927..c900135aaee 100644 --- a/tools/releaseTools.psm1 +++ b/tools/releaseTools.psm1 @@ -36,9 +36,12 @@ $Script:powershell_team = @( "Robert Holt" "Travis Plunk" "dependabot-preview[bot]" + "dependabot[bot]" "Joey Aiello" "Tyler James Leonhardt" "Anam Navied" + "Andrew Schwartzmeyer" + "Jason Helmick" ) # They are very active contributors, so we keep their email-login mappings here to save a few queries to Github. From a6c147c1f8372a544caf9579658aee40f8e26526 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Tue, 3 Aug 2021 12:09:25 -0700 Subject: [PATCH 19/55] Update PS-Committee members (#15837) --- .spelling | 1 + docs/community/governance.md | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.spelling b/.spelling index 0784aad4ad1..cd325a98394 100644 --- a/.spelling +++ b/.spelling @@ -355,6 +355,7 @@ helpproviderwithfullcache helpsystem hemant hemantmahawar +Higinbotham himura2la hololens homebrew diff --git a/docs/community/governance.md b/docs/community/governance.md index 42e974559b1..e97985a586b 100644 --- a/docs/community/governance.md +++ b/docs/community/governance.md @@ -26,10 +26,10 @@ The PowerShell Committee and its members (aka Committee Members) are the primary ### Current Committee Members * Bruce Payette ([BrucePay](https://github.com/BrucePay)) -* Dongbo Wang ([daxian-dbw](https://github.com/daxian-dbw)) * Jim Truher ([JamesWTruher](https://github.com/JamesWTruher)) * Joey Aiello ([joeyaiello](https://github.com/joeyaiello)) -* Kenneth Hansen ([khansen00](https://github.com/khansen00)) +* Paul Higinbotham ([paulhigin](https://github.com/paulhigin)) +* Rob Holt ([rjmholt](https://github.com/rjmholt)) * Steve Lee ([SteveL-MSFT](https://github.com/SteveL-MSFT)) ### Committee Member Responsibilities From 6933c5b473c532d8f5179909a950c561ea0da3f5 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Tue, 3 Aug 2021 13:43:00 -0700 Subject: [PATCH 20/55] Only allow `-File` to accept `.ps1` scripts on Windows (#15859) Co-authored-by: Ilya Co-authored-by: Paul Higinbotham --- .../host/msh/CommandLineParameterParser.cs | 8 +++ .../host/msh/ConsoleHost.cs | 4 +- test/powershell/Host/ConsoleHost.Tests.ps1 | 32 +++++---- test/xUnit/csharp/test_CommandLineParser.cs | 65 +++++++++++++------ 4 files changed, 76 insertions(+), 33 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index a63c9193345..6908320db53 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -1159,6 +1159,14 @@ static object ConvertToBoolIfPossible(string arg) showHelp: true); return false; } +#if !UNIX + // Only do the .ps1 extension check on Windows since shebang is not supported + if (!_file.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) + { + SetCommandLineError(string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidFileArgumentExtension, args[i])); + return false; + } +#endif i++; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 167186ae0c6..e54e7b02631 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -1857,13 +1857,15 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, Pipeline tempPipeline = exec.CreatePipeline(); Command c; +#if UNIX // if file doesn't have .ps1 extension, we read the contents and treat it as a script to support shebang with no .ps1 extension usage - if (!Path.GetExtension(filePath).Equals(".ps1", StringComparison.OrdinalIgnoreCase)) + if (!filePath.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) { string script = File.ReadAllText(filePath); c = new Command(script, isScript: true, useLocalScope: false); } else +#endif { c = new Command(filePath, false, false); } diff --git a/test/powershell/Host/ConsoleHost.Tests.ps1 b/test/powershell/Host/ConsoleHost.Tests.ps1 index 28561da23ce..7b7571ce177 100644 --- a/test/powershell/Host/ConsoleHost.Tests.ps1 +++ b/test/powershell/Host/ConsoleHost.Tests.ps1 @@ -147,21 +147,32 @@ Describe "ConsoleHost unit tests" -tags "Feature" { } It "-File should be default parameter" { - Set-Content -Path $testdrive/test -Value "'hello'" - $observed = & $powershell -NoProfile $testdrive/test + Set-Content -Path $testdrive/test.ps1 -Value "'hello'" + $observed = & $powershell -NoProfile $testdrive/test.ps1 $observed | Should -Be "hello" } - It "-File accepts scripts with and without .ps1 extension: " -TestCases @( - @{Filename="test.ps1"}, - @{Filename="test"} - ) { - param($Filename) + It "-File accepts scripts with .ps1 extension" { + $Filename = 'test.ps1' + Set-Content -Path $testdrive/$Filename -Value "'hello'" + $observed = & $powershell -NoProfile -File $testdrive/$Filename + $observed | Should -Be "hello" + } + + It "-File accepts scripts without .ps1 extension to support shebang" -Skip:($IsWindows) { + $Filename = 'test.xxx' Set-Content -Path $testdrive/$Filename -Value "'hello'" $observed = & $powershell -NoProfile -File $testdrive/$Filename $observed | Should -Be "hello" } + It "-File should fail for script without .ps1 extension" -Skip:(!$IsWindows) { + $Filename = 'test.xxx' + Set-Content -Path $testdrive/$Filename -Value "'hello'" + & $powershell -NoProfile -File $testdrive/$Filename > $null + $LASTEXITCODE | Should -Be 64 + } + It "-File should pass additional arguments to script" { Set-Content -Path $testdrive/script.ps1 -Value 'foreach($arg in $args){$arg}' $observed = & $powershell -NoProfile $testdrive/script.ps1 foo bar @@ -208,11 +219,8 @@ Describe "ConsoleHost unit tests" -tags "Feature" { $observed | Should -Be $BoolValue } - It "-File '' should return exit code from script" -TestCases @( - @{Filename = "test.ps1"}, - @{Filename = "test"} - ) { - param($Filename) + It "-File should return exit code from script" { + $Filename = 'test.ps1' Set-Content -Path $testdrive/$Filename -Value 'exit 123' & $powershell $testdrive/$Filename $LASTEXITCODE | Should -Be 123 diff --git a/test/xUnit/csharp/test_CommandLineParser.cs b/test/xUnit/csharp/test_CommandLineParser.cs index 41f501688f5..cf2a1281219 100644 --- a/test/xUnit/csharp/test_CommandLineParser.cs +++ b/test/xUnit/csharp/test_CommandLineParser.cs @@ -103,18 +103,27 @@ public static void TestDefaultParameterIsFileName_Not_Exist(params string[] comm [Fact] public static void TestDefaultParameterIsFileName_Exist() { - var fileName = System.IO.Path.GetTempFileName(); + var tempFile = System.IO.Path.GetTempFileName(); + var tempPs1 = tempFile + ".ps1"; + File.Move(tempFile, tempPs1); var cpp = new CommandLineParameterParser(); - cpp.Parse(new string[] { fileName }); + cpp.Parse(new string[] { tempPs1 }); - Assert.False(cpp.AbortStartup); - Assert.False(cpp.NoExit); - Assert.False(cpp.ShowShortHelp); - Assert.False(cpp.ShowBanner); - Assert.Equal(CommandLineParameterParser.NormalizeFilePath(fileName), cpp.File); - Assert.Null(cpp.ErrorMessage); + try + { + Assert.False(cpp.AbortStartup); + Assert.False(cpp.NoExit); + Assert.False(cpp.ShowShortHelp); + Assert.False(cpp.ShowBanner); + Assert.Equal(CommandLineParameterParser.NormalizeFilePath(tempPs1), cpp.File); + Assert.Null(cpp.ErrorMessage); + } + finally + { + File.Delete(tempPs1); + } } [Theory] @@ -1212,7 +1221,16 @@ public static void TestParameter_WorkingDirectory_RemoveTrailingCharacter(params public class TestDataLastFile : IEnumerable { - private readonly string _fileName = Path.GetTempFileName(); + private static string _fileName + { + get + { + var tempFile = Path.GetTempFileName(); + var tempPs1 = tempFile + ".ps1"; + File.Move(tempFile, tempPs1); + return tempPs1; + } + } public IEnumerator GetEnumerator() { @@ -1230,21 +1248,28 @@ public static void TestParameter_LastParameterIsFileName_Exist(params string[] c cpp.Parse(commandLine); - Assert.False(cpp.AbortStartup); - Assert.False(cpp.NoExit); - Assert.False(cpp.ShowShortHelp); - Assert.False(cpp.ShowBanner); - if (Platform.IsWindows) + try { - Assert.True(cpp.StaMode); + Assert.False(cpp.AbortStartup); + Assert.False(cpp.NoExit); + Assert.False(cpp.ShowShortHelp); + Assert.False(cpp.ShowBanner); + if (Platform.IsWindows) + { + Assert.True(cpp.StaMode); + } + else + { + Assert.False(cpp.StaMode); + } + + Assert.Equal(CommandLineParameterParser.NormalizeFilePath(commandLine[commandLine.Length - 1]), cpp.File); + Assert.Null(cpp.ErrorMessage); } - else + finally { - Assert.False(cpp.StaMode); + File.Delete(cpp.File); } - - Assert.Equal(CommandLineParameterParser.NormalizeFilePath(commandLine[commandLine.Length - 1]), cpp.File); - Assert.Null(cpp.ErrorMessage); } } } From bf4740dec6e891cc326be813078b93ddc58d9dc3 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 4 Aug 2021 11:05:40 -0700 Subject: [PATCH 21/55] Update `CodeQL` workflow to use `ubuntu-18.04` (#15868) --- .github/workflows/codeql-analysis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index a3719e2d90f..903ee79cf4d 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -17,7 +17,7 @@ env: jobs: analyze: name: Analyze - runs-on: ubuntu-16.04 + runs-on: ubuntu-18.04 strategy: fail-fast: false From 5fea4c39fda1e328c8d6f44259a326035af0a35e Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Wed, 4 Aug 2021 11:22:22 -0700 Subject: [PATCH 22/55] Add more information when a syslog parsing error occurs (#15857) --- test/tools/Modules/PSSysLog/PSSysLog.psm1 | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/test/tools/Modules/PSSysLog/PSSysLog.psm1 b/test/tools/Modules/PSSysLog/PSSysLog.psm1 index 660e98226b2..00dd74be5af 100644 --- a/test/tools/Modules/PSSysLog/PSSysLog.psm1 +++ b/test/tools/Modules/PSSysLog/PSSysLog.psm1 @@ -302,7 +302,7 @@ class PSLogItem } else { - Write-Warning -Message "Could not split EventId $($item.EventId) on '[] ' Count:$($subparts.Count)" + Write-Warning -Message "Could not split EventId $($item.EventId) on '[] ' Count:$($subparts.Count) -> $content" } # (commitid:TID:ChannelID) @@ -317,7 +317,7 @@ class PSLogItem } else { - Write-Warning -Message "Could not split CommitId $($item.CommitId) on '(): ' Count:$($subparts.Count)" + Write-Warning -Message "Could not split CommitId $($item.CommitId) on '(): ' Count:$($subparts.Count) -> $content" } # nameid[PID] @@ -331,7 +331,7 @@ class PSLogItem } else { - Write-Warning -Message "Could not split LogId $($item.LogId) on '[]:' Count:$($subparts.Count)" + Write-Warning -Message "Could not split LogId $($item.LogId) on '[]:' Count:$($subparts.Count) -> $content" } return $item @@ -497,11 +497,18 @@ function ConvertFrom-SysLog { foreach ($line in $Content) { - [PSLogItem] $item = [PSLogItem]::ConvertSysLog($line, $id, $after) - if ($item -ne $null) + try { - $totalWritten++ - Write-Output $item + [PSLogItem] $item = [PSLogItem]::ConvertSysLog($line, $id, $after) + if ($item -ne $null) + { + $totalWritten++ + Write-Output $item + } + } + catch + { + Write-Warning -Message "Could not convert '$line' to PSLogItem" } } } From 3e86f9b28777cbca85ee9c25255a1a212475583b Mon Sep 17 00:00:00 2001 From: lselden <2904993+lselden@users.noreply.github.com> Date: Wed, 4 Aug 2021 17:47:57 -0400 Subject: [PATCH 23/55] `ConvertTo-Csv`: Quote fields with quotes and newlines when using `-UseQuotes AsNeeded` (#15765) Co-authored-by: Ilya Co-authored-by: lselden --- .../commands/utility/CsvCommands.cs | 5 ++- .../ConvertTo-Csv.Tests.ps1 | 39 +++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index 96659dcf7e5..19ac076deaf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -992,7 +992,8 @@ internal string ConvertPropertyNamesCSV(IList propertyNames) AppendStringWithEscapeAlways(_outputString, propertyName); break; case BaseCsvWritingCommand.QuoteKind.AsNeeded: - if (propertyName.Contains(_delimiter)) + + if (propertyName.AsSpan().IndexOfAny(_delimiter, '\n', '"') != -1) { AppendStringWithEscapeAlways(_outputString, propertyName); } @@ -1078,7 +1079,7 @@ internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyN AppendStringWithEscapeAlways(_outputString, value); break; case BaseCsvWritingCommand.QuoteKind.AsNeeded: - if (value != null && value.Contains(_delimiter)) + if (value != null && value.AsSpan().IndexOfAny(_delimiter, '\n', '"') != -1) { AppendStringWithEscapeAlways(_outputString, value); } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 index 6b744b8eb88..129da4a9fde 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 @@ -159,6 +159,45 @@ Describe "ConvertTo-Csv" -Tags "CI" { $result[0] | Should -BeExactly "`"FirstColumn`"rSecondColumn" $result[1] | Should -BeExactly "Hellor" } + + It "UseQuotes AsNeeded Escapes Delimiters" { + $testDelimitersObject = [pscustomobject]@{ "FirstColumn" = "Hello,"; "Second,Column" = "World" }; + + $result = $testDelimitersObject | ConvertTo-Csv -UseQuotes AsNeeded -Delimiter ',' + + $result[0] | Should -BeExactly "FirstColumn,`"Second,Column`"" + $result[1] | Should -BeExactly "`"Hello,`",World" + + $result = $testDelimitersObject | ConvertTo-Csv -UseQuotes AsNeeded -Delimiter "r" + + $result[0] | Should -BeExactly "`"FirstColumn`"rSecond,Column" + $result[1] | Should -BeExactly "Hello,r`"World`"" + } + + It "UseQuotes AsNeeded Escapes Newlines" { + $testCRLFObject = [pscustomobject]@{ "First`r`nColumn" = "Hello`r`nWorld" }; + $testLFObject = [pscustomobject]@{ "First`nColumn" = "Hello`nWorld" }; + + $result = $testCRLFObject | ConvertTo-Csv -UseQuotes AsNeeded + + $result[0] | Should -BeExactly "`"First`r`nColumn`"" + $result[1] | Should -BeExactly "`"Hello`r`nWorld`"" + + $result = $testLFObject | ConvertTo-Csv -UseQuotes AsNeeded + + $result[0] | Should -BeExactly "`"First`nColumn`"" + $result[1] | Should -BeExactly "`"Hello`nWorld`"" + } + + It "UseQuotes AsNeeded Escapes Quotes" { + $testQuotesObject = [pscustomobject]@{ "First`"Column" = "`"Hello`" World" }; + + $result = $testQuotesObject | ConvertTo-Csv -UseQuotes AsNeeded + + $result[0] | Should -BeExactly "`"First`"`"Column`"" + $result[1] | Should -BeExactly "`"`"`"Hello`"`" World`"" + } + } Context 'Converting IDictionary Objects' { From aaaa0f2baa7db9d0e054651d4a51273a5140968e Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 5 Aug 2021 03:00:26 +0500 Subject: [PATCH 24/55] Thread-safe `HttpKnownHeaderNames` initialization (#15519) --- .../WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs | 40 +++++++++---------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs index 80d07a54ddf..0acd7c33567 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs @@ -78,31 +78,29 @@ internal static class HttpKnownHeaderNames #endregion Known_HTTP_Header_Names - private static HashSet s_contentHeaderSet = null; + private static readonly HashSet s_contentHeaderSet; - internal static HashSet ContentHeaders + static HttpKnownHeaderNames() { - get - { - if (s_contentHeaderSet == null) - { - s_contentHeaderSet = new HashSet(StringComparer.OrdinalIgnoreCase); + // Thread-safe initialization. + s_contentHeaderSet = new HashSet(StringComparer.OrdinalIgnoreCase); - s_contentHeaderSet.Add(HttpKnownHeaderNames.Allow); - s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentDisposition); - s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentEncoding); - s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentLanguage); - s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentLength); - s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentLocation); - s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentMD5); - s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentRange); - s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentType); - s_contentHeaderSet.Add(HttpKnownHeaderNames.Expires); - s_contentHeaderSet.Add(HttpKnownHeaderNames.LastModified); - } + s_contentHeaderSet.Add(HttpKnownHeaderNames.Allow); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentDisposition); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentEncoding); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentLanguage); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentLength); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentLocation); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentMD5); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentRange); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentType); + s_contentHeaderSet.Add(HttpKnownHeaderNames.Expires); + s_contentHeaderSet.Add(HttpKnownHeaderNames.LastModified); + } - return s_contentHeaderSet; - } + internal static HashSet ContentHeaders + { + get => s_contentHeaderSet; } } } From 2ae0e4d9dd4fc734b98473fbc3174bc18ed13be0 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Wed, 4 Aug 2021 15:01:18 -0700 Subject: [PATCH 25/55] Update `ServerRemoteHost` Version to be same as `PSVersion` (#15809) --- .../remoting/common/WireDataFormat/EncodeAndDecode.cs | 3 ++- .../engine/Remoting/RemoteSession.Basic.Tests.ps1 | 11 +++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs index d99fbe21126..aa22e45682a 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs @@ -4,6 +4,7 @@ using System.Collections; using System.Collections.Generic; using System.Globalization; +using System.Management.Automation; using System.Management.Automation.Host; using System.Management.Automation.Internal; using System.Management.Automation.Remoting; @@ -73,7 +74,7 @@ public RemotingEncodingException(string message, Exception innerException, Error /// internal static class RemotingConstants { - internal static readonly Version HostVersion = new Version(1, 0, 0, 0); + internal static readonly Version HostVersion = PSVersionInfo.PSVersion; internal static readonly Version ProtocolVersionWin7RC = new Version(2, 0); internal static readonly Version ProtocolVersionWin7RTM = new Version(2, 1); diff --git a/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 b/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 index 27d2fceb454..a8054b47182 100644 --- a/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 +++ b/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 @@ -345,5 +345,16 @@ Describe "Remoting loopback tests" -Tags @('CI', 'RequireAdminOnWindows') { $result = Invoke-Command -Session $openSession -ScriptBlock { $using:number } $result | Should -Be 100 } + + It '$Host.Version should be PSVersion' { + $session = New-RemoteSession -ConfigurationName $endPoint + try { + $result = Invoke-Command -Session $session -ScriptBlock { $Host.Version } + $result | Should -Be $PSVersionTable.PSVersion + } + finally { + $session | Remove-PSSession -ErrorAction Ignore + } + } } From 61af30f3b1d61710ae614f280d884a1c5b412e57 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 5 Aug 2021 13:55:13 +0500 Subject: [PATCH 26/55] Bump NJsonSchema from 10.4.6 to 10.5.0 (#15874) Bumps NJsonSchema from 10.4.6 to 10.5.0. --- updated-dependencies: - dependency-name: NJsonSchema dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 eb564986285..ff1715f852c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -34,7 +34,7 @@ - + From 920427260cd06a26ae9519265e18bbcf64dc3544 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Thu, 5 Aug 2021 10:44:52 -0700 Subject: [PATCH 27/55] Make global tool entrypoint class static (#15880) --- src/Microsoft.PowerShell.GlobalTool.Shim/GlobalToolShim.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.GlobalTool.Shim/GlobalToolShim.cs b/src/Microsoft.PowerShell.GlobalTool.Shim/GlobalToolShim.cs index 47a66ea8767..3b253582b63 100644 --- a/src/Microsoft.PowerShell.GlobalTool.Shim/GlobalToolShim.cs +++ b/src/Microsoft.PowerShell.GlobalTool.Shim/GlobalToolShim.cs @@ -10,7 +10,7 @@ namespace Microsoft.PowerShell.GlobalTool.Shim /// /// Shim layer to chose the appropriate runtime for PowerShell DotNet Global tool. /// - public class EntryPoint + public static class EntryPoint { private const string PwshDllName = "pwsh.dll"; From 45adfee5584b9e85169ba636033a08d333d49200 Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 5 Aug 2021 23:41:55 +0500 Subject: [PATCH 28/55] Enhance Remove-Item to work with OneDrive (#15571) --- .../commands/management/Navigation.cs | 2 +- .../engine/Utils.cs | 10 +- .../namespaces/FileSystemProvider.cs | 84 ++++-- .../utils/PathUtils.cs | 108 ++++++- .../FileSystem.Tests.ps1 | 134 ++++++++- .../Remove-Item.Tests.ps1 | 277 ++++++++++-------- 6 files changed, 463 insertions(+), 152 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs index 23aa621266d..c00c374611e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs @@ -2699,7 +2699,7 @@ protected override void ProcessRecord() try { System.IO.DirectoryInfo di = new(providerPath); - if (di != null && (di.Attributes & System.IO.FileAttributes.ReparsePoint) != 0) + if (InternalSymbolicLinkLinkCodeMethods.IsReparsePointLikeSymlink(di)) { shouldRecurse = false; treatAsFile = true; diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index bc443ac10a9..8c37713234f 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1864,7 +1864,7 @@ internal static string GetFormatStyleString(FormatStyle formatStyle) if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) { - PSStyle psstyle = PSStyle.Instance; + PSStyle psstyle = PSStyle.Instance; switch (formatStyle) { case FormatStyle.Reset: @@ -2104,6 +2104,14 @@ public static class InternalTestHooks internal static bool ThrowExdevErrorOnMoveDirectory; + // To emulate OneDrive behavior we use the hard-coded symlink. + // If OneDriveTestRecurseOn is false then the symlink works as regular symlink. + // If OneDriveTestRecurseOn is true then we recurse into the symlink as OneDrive should work. + // OneDriveTestSymlinkName defines the symlink name used in tests. + internal static bool OneDriveTestOn; + internal static bool OneDriveTestRecurseOn; + internal static string OneDriveTestSymlinkName = "link-Beta"; + /// This member is used for internal test purposes. public static void SetTestHook(string property, object value) { diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index a32dc421748..2eb0de56d52 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -1891,9 +1891,14 @@ private void Dir( } bool hidden = false; + bool checkReparsePoint = true; if (!Force) { hidden = (recursiveDirectory.Attributes & FileAttributes.Hidden) != 0; + + // We've already taken the expense of initializing the Attributes property here, + // so we can use that to avoid needing to call IsReparsePointLikeSymlink() later. + checkReparsePoint = recursiveDirectory.Attributes.HasFlag(FileAttributes.ReparsePoint); } // if "Hidden" is explicitly specified anywhere in the attribute filter, then override @@ -1907,7 +1912,7 @@ private void Dir( // c) it is not a reparse point with a target (not OneDrive or an AppX link). if (tracker == null) { - if (InternalSymbolicLinkLinkCodeMethods.IsReparsePointWithTarget(recursiveDirectory)) + if (checkReparsePoint && InternalSymbolicLinkLinkCodeMethods.IsReparsePointLikeSymlink(recursiveDirectory)) { continue; } @@ -2062,7 +2067,7 @@ public static string NameString(PSObject instance) { if (instance?.BaseObject is FileSystemInfo fileInfo) { - if (InternalSymbolicLinkLinkCodeMethods.IsReparsePointWithTarget(fileInfo)) + if (InternalSymbolicLinkLinkCodeMethods.IsReparsePointLikeSymlink(fileInfo)) { return $"{PSStyle.Instance.FileInfo.SymbolicLink}{fileInfo.Name}{PSStyle.Instance.Reset} -> {InternalSymbolicLinkLinkCodeMethods.GetTarget(instance)}"; } @@ -2090,7 +2095,7 @@ public static string NameString(PSObject instance) else { return instance?.BaseObject is FileSystemInfo fileInfo - ? InternalSymbolicLinkLinkCodeMethods.IsReparsePointWithTarget(fileInfo) + ? InternalSymbolicLinkLinkCodeMethods.IsReparsePointLikeSymlink(fileInfo) ? $"{fileInfo.Name} -> {InternalSymbolicLinkLinkCodeMethods.GetTarget(instance)}" : fileInfo.Name : string.Empty; @@ -3131,22 +3136,31 @@ private void RemoveDirectoryInfoItem(DirectoryInfo directory, bool recurse, bool continueRemoval = ShouldProcess(directory.FullName, action); } - if (directory.Attributes.HasFlag(FileAttributes.ReparsePoint)) + if (InternalSymbolicLinkLinkCodeMethods.IsReparsePointLikeSymlink(directory)) { + void WriteErrorHelper(Exception exception) + { + WriteError(new ErrorRecord(exception, errorId: "DeleteSymbolicLinkFailed", ErrorCategory.WriteError, directory)); + } + try { - // TODO: - // Different symlinks seem to vary by behavior. - // In particular, OneDrive symlinks won't remove without recurse, - // but the .NET API here does not allow us to distinguish them. - // We may need to revisit using p/Invokes here to get the right behavior - directory.Delete(); + if (InternalTestHooks.OneDriveTestOn) + { + WriteErrorHelper(new IOException()); + return; + } + else + { + // Name surrogates should just be detached. + directory.Delete(); + } } catch (Exception e) { string error = StringUtil.Format(FileSystemProviderStrings.CannotRemoveItem, directory.FullName, e.Message); var exception = new IOException(error, e); - WriteError(new ErrorRecord(exception, errorId: "DeleteSymbolicLinkFailed", ErrorCategory.WriteError, directory)); + WriteErrorHelper(exception); } return; @@ -8056,8 +8070,7 @@ protected override bool ReleaseHandle() private static extern bool FindClose(IntPtr handle); } - // SetLastError is false as the use of this API doesn't not require GetLastError() to be called - [DllImport(PinvokeDllNames.FindFirstFileDllName, EntryPoint = "FindFirstFileExW", SetLastError = false, CharSet = CharSet.Unicode)] + [DllImport(PinvokeDllNames.FindFirstFileDllName, EntryPoint = "FindFirstFileExW", SetLastError = true, CharSet = CharSet.Unicode)] private static extern SafeFindHandle FindFirstFileEx(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, ref WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, int dwAdditionalFlags); internal enum FINDEX_INFO_LEVELS : uint @@ -8248,28 +8261,55 @@ internal static bool IsReparsePoint(FileSystemInfo fileInfo) return fileInfo.Attributes.HasFlag(System.IO.FileAttributes.ReparsePoint); } - internal static bool IsReparsePointWithTarget(FileSystemInfo fileInfo) + internal static bool IsReparsePointLikeSymlink(FileSystemInfo fileInfo) { - if (!IsReparsePoint(fileInfo)) +#if UNIX + // Reparse point on Unix is a symlink. + return IsReparsePoint(fileInfo); +#else + if (InternalTestHooks.OneDriveTestOn && fileInfo.Name == InternalTestHooks.OneDriveTestSymlinkName) { - return false; + return !InternalTestHooks.OneDriveTestRecurseOn; } -#if !UNIX - // It is a reparse point and we should check some reparse point tags. - var data = new WIN32_FIND_DATA(); - using (var handle = FindFirstFileEx(fileInfo.FullName, FINDEX_INFO_LEVELS.FindExInfoBasic, ref data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, 0)) + + WIN32_FIND_DATA data = default; + string fullPath = Path.TrimEndingDirectorySeparator(fileInfo.FullName); + if (fullPath.Length > MAX_PATH) + { + fullPath = PathUtils.EnsureExtendedPrefix(fullPath); + } + + using (SafeFindHandle handle = FindFirstFileEx(fullPath, FINDEX_INFO_LEVELS.FindExInfoBasic, ref data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, 0)) { + if (handle.IsInvalid) + { + // Our handle could be invalidated by something else touching the filesystem, + // so ensure we deal with that possibility here + int lastError = Marshal.GetLastWin32Error(); + throw new Win32Exception(lastError); + } + + // We already have the file attribute information from our Win32 call, + // so no need to take the expense of the FileInfo.FileAttributes call + const int FILE_ATTRIBUTE_REPARSE_POINT = 0x0400; + if ((data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0) + { + // Not a reparse point. + return false; + } + // The name surrogate bit 0x20000000 is defined in https://docs.microsoft.com/windows/win32/fileio/reparse-point-tags // Name surrogates (0x20000000) are reparse points that point to other named entities local to the filesystem // (like symlinks and mount points). // In the case of OneDrive, they are not name surrogates and would be safe to recurse into. - if (!handle.IsInvalid && (data.dwReserved0 & 0x20000000) == 0 && (data.dwReserved0 != IO_REPARSE_TAG_APPEXECLINK)) + if ((data.dwReserved0 & 0x20000000) == 0 && (data.dwReserved0 != IO_REPARSE_TAG_APPEXECLINK)) { return false; } } -#endif + return true; +#endif } internal static bool WinIsHardLink(FileSystemInfo fileInfo) diff --git a/src/System.Management.Automation/utils/PathUtils.cs b/src/System.Management.Automation/utils/PathUtils.cs index 991e3fa63b6..45ba787aee2 100644 --- a/src/System.Management.Automation/utils/PathUtils.cs +++ b/src/System.Management.Automation/utils/PathUtils.cs @@ -4,9 +4,10 @@ using System.Collections.Generic; using System.Globalization; using System.IO; +using System.Management.Automation.Internal; +using System.Runtime.CompilerServices; using System.Text; -using System.Management.Automation.Internal; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation @@ -447,5 +448,110 @@ internal static bool TryDeleteFile(string filepath) return false; } + + #region Helpers for long paths from .Net Runtime + + // Code here is copied from .NET's internal path helper implementation: + // https://github.com/dotnet/runtime/blob/dcce0f56e10f5ac9539354b049341a2d7c0cdebf/src/libraries/System.Private.CoreLib/src/System/IO/PathInternal.Windows.cs + // It has been left as a verbatim copy. + + internal static string EnsureExtendedPrefix(string path) + { + if (IsPartiallyQualified(path) || IsDevice(path)) + return path; + + // Given \\server\share in longpath becomes \\?\UNC\server\share + if (path.StartsWith(UncPathPrefix, StringComparison.OrdinalIgnoreCase)) + return path.Insert(2, UncDevicePrefixToInsert); + + return ExtendedDevicePathPrefix + path; + } + + private const string ExtendedDevicePathPrefix = @"\\?\"; + private const string UncPathPrefix = @"\\"; + private const string UncDevicePrefixToInsert = @"?\UNC\"; + private const string UncExtendedPathPrefix = @"\\?\UNC\"; + private const string DevicePathPrefix = @"\\.\"; + + // \\?\, \\.\, \??\ + private const int DevicePrefixLength = 4; + + /// + /// Returns true if the given character is a valid drive letter + /// + private static bool IsValidDriveChar(char value) + { + return ((value >= 'A' && value <= 'Z') || (value >= 'a' && value <= 'z')); + } + + private static bool IsDevice(string path) + { + return IsExtended(path) + || + ( + path.Length >= DevicePrefixLength + && IsDirectorySeparator(path[0]) + && IsDirectorySeparator(path[1]) + && (path[2] == '.' || path[2] == '?') + && IsDirectorySeparator(path[3]) + ); + } + + private static bool IsExtended(string path) + { + return path.Length >= DevicePrefixLength + && path[0] == '\\' + && (path[1] == '\\' || path[1] == '?') + && path[2] == '?' + && path[3] == '\\'; + } + + /// + /// Returns true if the path specified is relative to the current drive or working directory. + /// Returns false if the path is fixed to a specific drive or UNC path. This method does no + /// validation of the path (URIs will be returned as relative as a result). + /// + /// + /// Handles paths that use the alternate directory separator. It is a frequent mistake to + /// assume that rooted paths (Path.IsPathRooted) are not relative. This isn't the case. + /// "C:a" is drive relative- meaning that it will be resolved against the current directory + /// for C: (rooted, but relative). "C:\a" is rooted and not relative (the current directory + /// will not be used to modify the path). + /// + private static bool IsPartiallyQualified(string path) + { + if (path.Length < 2) + { + // It isn't fixed, it must be relative. There is no way to specify a fixed + // path with one character (or less). + return true; + } + + if (IsDirectorySeparator(path[0])) + { + // There is no valid way to specify a relative path with two initial slashes or + // \? as ? isn't valid for drive relative paths and \??\ is equivalent to \\?\ + return !(path[1] == '?' || IsDirectorySeparator(path[1])); + } + + // The only way to specify a fixed path that doesn't begin with two slashes + // is the drive, colon, slash format- i.e. C:\ + return !((path.Length >= 3) + && (path[1] == Path.VolumeSeparatorChar) + && IsDirectorySeparator(path[2]) + // To match old behavior we'll check the drive character for validity as the path is technically + // not qualified if you don't have a valid drive. "=:\" is the "=" file's default data stream. + && IsValidDriveChar(path[0])); + } + /// + /// True if the given character is a directory separator. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool IsDirectorySeparator(char c) + { + return c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar; + } + + #endregion } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 index f1b352a16bc..70a18ff604f 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 @@ -92,6 +92,22 @@ Describe "Basic FileSystem Provider Tests" -Tags "CI" { $existsAfter | Should -BeFalse } + It "Verify Remove-Item for file" { + $longDir = 'a' * 250 + $longSubDir = 'b' * 250 + $fileName = "file1.txt" + $topPath = Join-Path $TestDrive $longDir + $longDirPath = Join-Path $topPath $longSubDir + $longFilePath = Join-Path $longDirPath $fileName + $null = New-Item -itemtype file -path $longFilePath -force + + $longFilePath | Should -Exist + + Remove-Item -Path $longFilePath -Force + + $longFilePath | Should -Not -Exist + } + It "Verify Rename-Item for file" { Rename-Item -Path $testFile -NewName $newTestFile -ErrorAction Stop $testFile | Should -Not -Exist @@ -570,7 +586,7 @@ Describe "Hard link and symbolic link tests" -Tags "CI", "RequireAdminOnWindows" $omegaFile1 = Join-Path $omegaDir "OmegaFile1" $omegaFile2 = Join-Path $omegaDir "OmegaFile2" $betaDir = Join-Path $alphaDir "sub-Beta" - $betaLink = Join-Path $alphaDir "link-Beta" + $betaLink = Join-Path $alphaDir "link-Beta" # Don't change! The name is hard-coded in PowerShell for OneDrive tests. $betaFile1 = Join-Path $betaDir "BetaFile1.txt" $betaFile2 = Join-Path $betaDir "BetaFile2.txt" $betaFile3 = Join-Path $betaDir "BetaFile3.txt" @@ -1529,3 +1545,119 @@ Describe "Windows admin tests" -Tag 'RequireAdminOnWindows' { } } } + +Describe "OneDrive filesystem manipulation" -Tags @('CI', 'RequireAdminOnWindows') { + BeforeAll { + # on macOS, the /tmp directory is a symlink, so we'll resolve it here + $TestPath = $TestDrive + if ($IsMacOS) + { + $item = Get-Item $TestPath + $dirName = $item.BaseName + $item = Get-Item $item.PSParentPath -Force + if ($item.LinkType -eq "SymbolicLink") + { + $TestPath = Join-Path $item.Target $dirName + } + } + + $realFile = Join-Path $TestPath "file.txt" + $nonFile = Join-Path $TestPath "not-a-file" + $fileContent = "some text" + $realDir = Join-Path $TestPath "subdir" + $nonDir = Join-Path $TestPath "not-a-dir" + $hardLinkToFile = Join-Path $TestPath "hard-to-file.txt" + $symLinkToFile = Join-Path $TestPath "sym-link-to-file.txt" + $symLinkToDir = Join-Path $TestPath "sym-link-to-dir" + $symLinkToNothing = Join-Path $TestPath "sym-link-to-nowhere" + $dirSymLinkToDir = Join-Path $TestPath "symd-link-to-dir" + $junctionToDir = Join-Path $TestPath "junction-to-dir" + + New-Item -ItemType File -Path $realFile -Value $fileContent > $null + New-Item -ItemType Directory -Path $realDir > $null + + $alphaDir = Join-Path $TestDrive "sub-alpha" + $alphaLink = Join-Path $TestDrive "link-alpha" + $alphaFile1 = Join-Path $alphaDir "AlphaFile1.txt" + $alphaFile2 = Join-Path $alphaDir "AlphaFile2.txt" + $omegaDir = Join-Path $TestDrive "sub-omega" + $omegaFile1 = Join-Path $omegaDir "OmegaFile1" + $omegaFile2 = Join-Path $omegaDir "OmegaFile2" + $betaDir = Join-Path $alphaDir "sub-Beta" + $betaLink = Join-Path $alphaDir "link-Beta" # Don't change! The name is hard-coded in PowerShell for OneDrive tests. + $betaFile1 = Join-Path $betaDir "BetaFile1.txt" + $betaFile2 = Join-Path $betaDir "BetaFile2.txt" + $betaFile3 = Join-Path $betaDir "BetaFile3.txt" + $gammaDir = Join-Path $betaDir "sub-gamma" + $uponeLink = Join-Path $gammaDir "upone-link" + $uptwoLink = Join-Path $gammaDir "uptwo-link" + $omegaLink = Join-Path $gammaDir "omegaLink" + + New-Item -ItemType Directory -Path $alphaDir + New-Item -ItemType File -Path $alphaFile1 + New-Item -ItemType File -Path $alphaFile2 + New-Item -ItemType Directory -Path $betaDir + New-Item -ItemType File -Path $betaFile1 + New-Item -ItemType File -Path $betaFile2 + New-Item -ItemType File -Path $betaFile3 + New-Item -ItemType Directory $omegaDir + New-Item -ItemType File -Path $omegaFile1 + New-Item -ItemType File -Path $omegaFile2 + } + + AfterAll { + Remove-Item -Path $alphaLink -Force -ErrorAction SilentlyContinue + Remove-Item -Path $betaLink -Force -ErrorAction SilentlyContinue + } + + BeforeEach { + [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('OneDriveTestOn', $true) + [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('OneDriveTestRecurseOn', $false) + } + + AfterEach { + [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('OneDriveTestRecurseOn', $false) + [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('OneDriveTestOn', $false) + } + + It "Get-ChildItem will recurse into emulated OneDrive directory" -Skip:(-not $IsWindows) { + New-Item -ItemType SymbolicLink -Path $alphaLink -Value $alphaDir -Force + New-Item -ItemType SymbolicLink -Path $betaLink -Value $betaDir -Force + + # '$betaDir' is a symlink - we don't follow symlinks + # This emulates PowerShell 6.2 and below behavior. + $ci = Get-ChildItem -Path $alphaDir -Recurse + $ci.Count | Should -BeExactly 7 + + # Now we follow the symlink like on OneDrive. + [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('OneDriveTestRecurseOn', $true) + $ci = Get-ChildItem -Path $alphaDir -Recurse + $ci.Count | Should -BeExactly 10 + } + + It "Remove-Item will recurse into emulated OneDrive directory" -Skip:(-not $IsWindows) { + $alphaDir = Join-Path $TestDrive "sub-alpha2" + $alphaLink = Join-Path $TestDrive "link-alpha2" + $alphaFile1 = Join-Path $alphaDir "AlphaFile1.txt" + $betaDir = Join-Path $alphaDir "sub-Beta" + $betaLink = Join-Path $alphaDir "link-Beta" + $betaFile1 = Join-Path $betaDir "BetaFile1.txt" + + New-Item -ItemType Directory -Path $alphaDir > $null + New-Item -ItemType File -Path $alphaFile1 > $null + New-Item -ItemType Directory -Path $betaDir > $null + New-Item -ItemType File -Path $betaFile1 > $null + + New-Item -ItemType SymbolicLink -Path $alphaLink -Value $alphaDir > $null + New-Item -ItemType SymbolicLink -Path $betaLink -Value $betaDir > $null + + # With the test hook turned on we don't remove '$betaDir' symlink. + # This emulates PowerShell 7.1 and below behavior. + { Remove-Item -Path $betaLink -Recurse -ErrorAction Stop } | Should -Throw -ErrorId "DeleteSymbolicLinkFailed,Microsoft.PowerShell.Commands.RemoveItemCommand" + + # Now we emulate OneDrive and follow the symlink like on OneDrive. + [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('OneDriveTestRecurseOn', $true) + Remove-Item -Path $betaLink -Recurse + Test-Path -Path $betaLink | Should -BeFalse + } +} diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Remove-Item.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Remove-Item.Tests.ps1 index 3e8ccb8fa91..28c5ed6052d 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Remove-Item.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Remove-Item.Tests.ps1 @@ -1,170 +1,195 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. + Describe "Remove-Item" -Tags "CI" { - $testpath = $TestDrive - $testfile = "testfile.txt" - $testfilepath = Join-Path -Path $testpath -ChildPath $testfile + BeforeAll { + $testpath = $TestDrive + $testfile = "testfile.txt" + $testfilepath = Join-Path -Path $testpath -ChildPath $testfile + } + Context "File removal Tests" { - BeforeEach { - New-Item -Name $testfile -Path $testpath -ItemType "file" -Value "lorem ipsum" -Force - Test-Path $testfilepath | Should -BeTrue - } + BeforeEach { + New-Item -Name $testfile -Path $testpath -ItemType "file" -Value "lorem ipsum" -Force + Test-Path $testfilepath | Should -BeTrue + } - It "Should be able to be called on a regular file without error using the Path parameter" { - { Remove-Item -Path $testfilepath } | Should -Not -Throw + It "Should be able to be called on a regular file without error using the Path parameter" { + { Remove-Item -Path $testfilepath } | Should -Not -Throw - Test-Path $testfilepath | Should -BeFalse - } + Test-Path $testfilepath | Should -BeFalse + } - It "Should be able to be called on a file without the Path parameter" { - { Remove-Item $testfilepath } | Should -Not -Throw + It "Should be able to be called on a file without the Path parameter" { + { Remove-Item $testfilepath } | Should -Not -Throw - Test-Path $testfilepath | Should -BeFalse - } + Test-Path $testfilepath | Should -BeFalse + } - It "Should be able to call the rm alias" { - { rm $testfilepath } | Should -Not -Throw + It "Should be able to call the rm alias" { + { rm $testfilepath } | Should -Not -Throw - Test-Path $testfilepath | Should -BeFalse - } + Test-Path $testfilepath | Should -BeFalse + } - It "Should be able to call the del alias" { - { del $testfilepath } | Should -Not -Throw + It "Should be able to call the del alias" { + { del $testfilepath } | Should -Not -Throw - Test-Path $testfilepath | Should -BeFalse - } + Test-Path $testfilepath | Should -BeFalse + } - It "Should be able to call the erase alias" { - { erase $testfilepath } | Should -Not -Throw + It "Should be able to call the erase alias" { + { erase $testfilepath } | Should -Not -Throw - Test-Path $testfilepath | Should -BeFalse - } + Test-Path $testfilepath | Should -BeFalse + } + + It "Should be able to call the ri alias" { + { ri $testfilepath } | Should -Not -Throw + + Test-Path $testfilepath | Should -BeFalse + } - It "Should be able to call the ri alias" { - { ri $testfilepath } | Should -Not -Throw + It "Should not be able to remove a read-only document without using the force switch" { + # Set to read only + Set-ItemProperty -Path $testfilepath -Name IsReadOnly -Value $true - Test-Path $testfilepath | Should -BeFalse - } + # attempt to remove the file + { Remove-Item $testfilepath -ErrorAction SilentlyContinue } | Should -Not -Throw - It "Should not be able to remove a read-only document without using the force switch" { - # Set to read only - Set-ItemProperty -Path $testfilepath -Name IsReadOnly -Value $true + # validate + Test-Path $testfilepath | Should -BeTrue - # attempt to remove the file - { Remove-Item $testfilepath -ErrorAction SilentlyContinue } | Should -Not -Throw + # remove using the -force switch on the readonly object + Remove-Item $testfilepath -Force - # validate - Test-Path $testfilepath | Should -BeTrue + # Validate + Test-Path $testfilepath | Should -BeFalse + } + + It "Should be able to remove all files matching a regular expression with the include parameter" { + # Create multiple files with specific string + New-Item -Name file1.txt -Path $testpath -ItemType "file" -Value "lorem ipsum" + New-Item -Name file2.txt -Path $testpath -ItemType "file" -Value "lorem ipsum" + New-Item -Name file3.txt -Path $testpath -ItemType "file" -Value "lorem ipsum" + # Create a single file that does not match that string - already done in BeforeEach + + # Delete the specific string + Remove-Item (Join-Path -Path $testpath -ChildPath "*") -Include file*.txt + # validate that the string under test was deleted, and the nonmatching strings still exist + Test-Path (Join-Path -Path $testpath -ChildPath file1.txt) | Should -BeFalse + Test-Path (Join-Path -Path $testpath -ChildPath file2.txt) | Should -BeFalse + Test-Path (Join-Path -Path $testpath -ChildPath file3.txt) | Should -BeFalse + Test-Path $testfilepath | Should -BeTrue + + # Delete the non-matching strings + Remove-Item $testfilepath + + Test-Path $testfilepath | Should -BeFalse + } - # remove using the -force switch on the readonly object - Remove-Item $testfilepath -Force + It "Should be able to not remove any files matching a regular expression with the exclude parameter" { + # Create multiple files with specific string + New-Item -Name file1.wav -Path $testpath -ItemType "file" -Value "lorem ipsum" + New-Item -Name file2.wav -Path $testpath -ItemType "file" -Value "lorem ipsum" - # Validate - Test-Path $testfilepath | Should -BeFalse - } + # Create a single file that does not match that string + New-Item -Name file1.txt -Path $testpath -ItemType "file" -Value "lorem ipsum" - It "Should be able to remove all files matching a regular expression with the include parameter" { - # Create multiple files with specific string - New-Item -Name file1.txt -Path $testpath -ItemType "file" -Value "lorem ipsum" - New-Item -Name file2.txt -Path $testpath -ItemType "file" -Value "lorem ipsum" - New-Item -Name file3.txt -Path $testpath -ItemType "file" -Value "lorem ipsum" - # Create a single file that does not match that string - already done in BeforeEach + # Delete the specific string + Remove-Item (Join-Path -Path $testpath -ChildPath "file*") -Exclude *.wav -Include *.txt - # Delete the specific string - Remove-Item (Join-Path -Path $testpath -ChildPath "*") -Include file*.txt - # validate that the string under test was deleted, and the nonmatching strings still exist - Test-Path (Join-Path -Path $testpath -ChildPath file1.txt) | Should -BeFalse - Test-Path (Join-Path -Path $testpath -ChildPath file2.txt) | Should -BeFalse - Test-Path (Join-Path -Path $testpath -ChildPath file3.txt) | Should -BeFalse - Test-Path $testfilepath | Should -BeTrue + # validate that the string under test was deleted, and the nonmatching strings still exist + Test-Path (Join-Path -Path $testpath -ChildPath file1.wav) | Should -BeTrue + Test-Path (Join-Path -Path $testpath -ChildPath file2.wav) | Should -BeTrue + Test-Path (Join-Path -Path $testpath -ChildPath file1.txt) | Should -BeFalse - # Delete the non-matching strings - Remove-Item $testfilepath + # Delete the non-matching strings + Remove-Item (Join-Path -Path $testpath -ChildPath file1.wav) + Remove-Item (Join-Path -Path $testpath -ChildPath file2.wav) - Test-Path $testfilepath | Should -BeFalse - } + Test-Path (Join-Path -Path $testpath -ChildPath file1.wav) | Should -BeFalse + Test-Path (Join-Path -Path $testpath -ChildPath file2.wav) | Should -BeFalse + } + } - It "Should be able to not remove any files matching a regular expression with the exclude parameter" { - # Create multiple files with specific string - New-Item -Name file1.wav -Path $testpath -ItemType "file" -Value "lorem ipsum" - New-Item -Name file2.wav -Path $testpath -ItemType "file" -Value "lorem ipsum" + Context "Directory Removal Tests" { + BeforeAll { + $testdirectory = Join-Path -Path $testpath -ChildPath testdir + $testsubdirectory = Join-Path -Path $testdirectory -ChildPath subd + } - # Create a single file that does not match that string - New-Item -Name file1.txt -Path $testpath -ItemType "file" -Value "lorem ipsum" + BeforeEach { + New-Item -Name "testdir" -Path $testpath -ItemType "directory" -Force - # Delete the specific string - Remove-Item (Join-Path -Path $testpath -ChildPath "file*") -Exclude *.wav -Include *.txt + Test-Path $testdirectory | Should -BeTrue + } - # validate that the string under test was deleted, and the nonmatching strings still exist - Test-Path (Join-Path -Path $testpath -ChildPath file1.wav) | Should -BeTrue - Test-Path (Join-Path -Path $testpath -ChildPath file2.wav) | Should -BeTrue - Test-Path (Join-Path -Path $testpath -ChildPath file1.txt) | Should -BeFalse + It "Should be able to remove a directory" { + { Remove-Item $testdirectory -ErrorAction Stop } | Should -Not -Throw - # Delete the non-matching strings - Remove-Item (Join-Path -Path $testpath -ChildPath file1.wav) - Remove-Item (Join-Path -Path $testpath -ChildPath file2.wav) + Test-Path $testdirectory | Should -BeFalse + } - Test-Path (Join-Path -Path $testpath -ChildPath file1.wav) | Should -BeFalse - Test-Path (Join-Path -Path $testpath -ChildPath file2.wav) | Should -BeFalse - } - } + It "Should be able to recursively delete subfolders" { + New-Item -Name "subd" -Path $testdirectory -ItemType "directory" + New-Item -Name $testfile -Path $testsubdirectory -ItemType "file" -Value "lorem ipsum" - Context "Directory Removal Tests" { - $testdirectory = Join-Path -Path $testpath -ChildPath testdir - $testsubdirectory = Join-Path -Path $testdirectory -ChildPath subd - BeforeEach { - New-Item -Name "testdir" -Path $testpath -ItemType "directory" -Force + $complexDirectory = Join-Path -Path $testsubdirectory -ChildPath $testfile + Test-Path $complexDirectory | Should -BeTrue - Test-Path $testdirectory | Should -BeTrue - } + { Remove-Item $testdirectory -Recurse -ErrorAction Stop } | Should -Not -Throw - It "Should be able to remove a directory" { - { Remove-Item $testdirectory } | Should -Not -Throw + Test-Path $testdirectory | Should -BeFalse + } - Test-Path $testdirectory | Should -BeFalse - } + It "Should be able to recursively delete a directory with a trailing backslash" { + New-Item -Name "subd" -Path $testdirectory -ItemType "directory" + New-Item -Name $testfile -Path $testsubdirectory -ItemType "file" -Value "lorem ipsum" - It "Should be able to recursively delete subfolders" { - New-Item -Name "subd" -Path $testdirectory -ItemType "directory" - New-Item -Name $testfile -Path $testsubdirectory -ItemType "file" -Value "lorem ipsum" + $complexDirectory = Join-Path -Path $testsubdirectory -ChildPath $testfile + Test-Path $complexDirectory | Should -BeTrue - $complexDirectory = Join-Path -Path $testsubdirectory -ChildPath $testfile - Test-Path $complexDirectory | Should -BeTrue + $testdirectoryWithBackSlash = Join-Path -Path $testdirectory -ChildPath ([IO.Path]::DirectorySeparatorChar) + Test-Path $testdirectoryWithBackSlash | Should -BeTrue - { Remove-Item $testdirectory -Recurse} | Should -Not -Throw + { Remove-Item $testdirectoryWithBackSlash -Recurse -ErrorAction Stop } | Should -Not -Throw - Test-Path $testdirectory | Should -BeFalse - } + Test-Path $testdirectoryWithBackSlash | Should -BeFalse + Test-Path $testdirectory | Should -BeFalse + } } Context "Alternate Data Streams should be supported on Windows" { - BeforeAll { - if (!$IsWindows) { - return - } - $fileName = "ADStest.txt" - $streamName = "teststream" - $dirName = "ADStestdir" - $fileContent =" This is file content." - $streamContent = "datastream content here" - $streamfile = Join-Path -Path $testpath -ChildPath $fileName - $streamdir = Join-Path -Path $testpath -ChildPath $dirName - - $null = New-Item -Path $streamfile -ItemType "File" -force - Add-Content -Path $streamfile -Value $fileContent - Add-Content -Path $streamfile -Stream $streamName -Value $streamContent - $null = New-Item -Path $streamdir -ItemType "Directory" -Force - Add-Content -Path $streamdir -Stream $streamName -Value $streamContent - } - It "Should completely remove a datastream from a file" -Skip:(!$IsWindows) { - Get-Item -Path $streamfile -Stream $streamName | Should -Not -BeNullOrEmpty - Remove-Item -Path $streamfile -Stream $streamName - Get-Item -Path $streamfile -Stream $streamName -ErrorAction SilentlyContinue | Should -BeNullOrEmpty - } - It "Should completely remove a datastream from a directory" -Skip:(!$IsWindows) { - Get-Item -Path $streamdir -Stream $streamName | Should -Not -BeNullOrEmpty - Remove-Item -Path $streamdir -Stream $streamName - Get-Item -Path $streamdir -Stream $streamname -ErrorAction SilentlyContinue | Should -BeNullOrEmpty - } + BeforeAll { + if (!$IsWindows) { + return + } + $fileName = "ADStest.txt" + $streamName = "teststream" + $dirName = "ADStestdir" + $fileContent =" This is file content." + $streamContent = "datastream content here" + $streamfile = Join-Path -Path $testpath -ChildPath $fileName + $streamdir = Join-Path -Path $testpath -ChildPath $dirName + + $null = New-Item -Path $streamfile -ItemType "File" -force + Add-Content -Path $streamfile -Value $fileContent + Add-Content -Path $streamfile -Stream $streamName -Value $streamContent + $null = New-Item -Path $streamdir -ItemType "Directory" -Force + Add-Content -Path $streamdir -Stream $streamName -Value $streamContent + } + + It "Should completely remove a datastream from a file" -Skip:(!$IsWindows) { + Get-Item -Path $streamfile -Stream $streamName | Should -Not -BeNullOrEmpty + Remove-Item -Path $streamfile -Stream $streamName + Get-Item -Path $streamfile -Stream $streamName -ErrorAction SilentlyContinue | Should -BeNullOrEmpty + } + + It "Should completely remove a datastream from a directory" -Skip:(!$IsWindows) { + Get-Item -Path $streamdir -Stream $streamName | Should -Not -BeNullOrEmpty + Remove-Item -Path $streamdir -Stream $streamName + Get-Item -Path $streamdir -Stream $streamname -ErrorAction SilentlyContinue | Should -BeNullOrEmpty + } } } From ce6f04aa8a5331e99502a99b4d087de25856ab7c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 5 Aug 2021 15:23:54 -0700 Subject: [PATCH 29/55] Bump `Microsoft.ApplicationInsights` from `2.17.0` to `2.18.0` (#15842) Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .../System.Management.Automation.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index f11ab82db0d..37d3686dbaa 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -14,7 +14,7 @@ - + From 44595a40ecb162dd865af00fc1580a09a5e72499 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Fri, 6 Aug 2021 00:21:46 +0100 Subject: [PATCH 30/55] Fix `CA1052` in `TypeCatalogGen` (#15840) --- src/TypeCatalogGen/TypeCatalogGen.cs | 2 +- src/TypeCatalogGen/TypeCatalogGen.csproj | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/TypeCatalogGen/TypeCatalogGen.cs b/src/TypeCatalogGen/TypeCatalogGen.cs index 543d5931e39..8749c19814b 100644 --- a/src/TypeCatalogGen/TypeCatalogGen.cs +++ b/src/TypeCatalogGen/TypeCatalogGen.cs @@ -27,7 +27,7 @@ namespace Microsoft.PowerShell.CoreCLR { - public class TypeCatalogGen + public static class TypeCatalogGen { // Help messages private const string Param_TargetCSharpFilePath = "TargetCSharpFilePath"; diff --git a/src/TypeCatalogGen/TypeCatalogGen.csproj b/src/TypeCatalogGen/TypeCatalogGen.csproj index c7966c37b79..e81e027ea75 100644 --- a/src/TypeCatalogGen/TypeCatalogGen.csproj +++ b/src/TypeCatalogGen/TypeCatalogGen.csproj @@ -3,6 +3,7 @@ Generates CorePsTypeCatalog.cs given powershell.inc net6.0 + true TypeCatalogGen Exe true From 01a4714b762de1736d0a019570ae527d365d1f0c Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Fri, 6 Aug 2021 00:32:33 +0100 Subject: [PATCH 31/55] Enable `CA1067`: Override `Object.Equals(object)` when implementing `IEquatable` (#13871) * Enable CA1067: Override Object.Equals(object) when implementing IEquatable * Group Equals methods * Reformat xml documentation * Update src/System.Management.Automation/engine/EventManager.cs Co-authored-by: Joel Sallow (/u/ta11ow) <32407840+vexx32@users.noreply.github.com> Co-authored-by: Joel Sallow (/u/ta11ow) <32407840+vexx32@users.noreply.github.com> --- .globalconfig | 4 ++-- .../engine/EventManager.cs | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/.globalconfig b/.globalconfig index d7fb942772c..fb0a7e89abd 100644 --- a/.globalconfig +++ b/.globalconfig @@ -198,8 +198,8 @@ dotnet_diagnostic.CA1065.severity = warning dotnet_diagnostic.CA1066.severity = none # CA1067: Override Object.Equals(object) when implementing IEquatable -# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1067 -dotnet_diagnostic.CA1067.severity = suggestion +# # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1067 +dotnet_diagnostic.CA1067.severity = warning # CA1068: CancellationToken parameters must come last # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1068 diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index fd30298669e..3df9153f4e7 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -2042,6 +2042,19 @@ private ScriptBlock CreateBoundScriptBlock(ScriptBlock scriptAction) #region IComparable Members + /// + /// Determines whether the specified object is equal to the current object. + /// + /// The object to compare with the current object. + /// + /// if the specified object is equal to the current object; + /// otherwise, . + /// + public override bool Equals(object obj) + { + return obj is PSEventSubscriber es && Equals(es); + } + /// /// Determines if two PSEventSubscriber instances are equal /// From 58483e1366c5de5ffce2fbfcdb9b84aed2cb16af Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Fri, 6 Aug 2021 00:35:38 +0100 Subject: [PATCH 32/55] Replace `GetFiles` in `CompletionCompleters` (#14329) --- .../engine/Modules/ModuleUtils.cs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs index 5288afbc483..26d3174ca3b 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs @@ -81,8 +81,7 @@ internal static IEnumerable GetAllAvailableModuleFiles(string topDirecto string directoryToCheck = directoriesToCheck.Dequeue(); try { - string[] subDirectories = Directory.GetDirectories(directoryToCheck, "*", options); - foreach (string toAdd in subDirectories) + foreach (string toAdd in Directory.EnumerateDirectories(directoryToCheck, "*", options)) { if (firstSubDirs || !IsPossibleResourceDirectory(toAdd)) { @@ -94,8 +93,7 @@ internal static IEnumerable GetAllAvailableModuleFiles(string topDirecto catch (UnauthorizedAccessException) { } firstSubDirs = false; - string[] files = Directory.GetFiles(directoryToCheck, "*", options); - foreach (string moduleFile in files) + foreach (string moduleFile in Directory.EnumerateFiles(directoryToCheck, "*", options)) { foreach (string ext in ModuleIntrinsics.PSModuleExtensions) { @@ -332,14 +330,14 @@ internal static List GetModuleVersionSubfolders(string moduleBase) if (!string.IsNullOrWhiteSpace(moduleBase) && Directory.Exists(moduleBase)) { var options = Utils.PathIsUnc(moduleBase) ? s_uncPathEnumerationOptions : s_defaultEnumerationOptions; - string[] subdirectories = Directory.GetDirectories(moduleBase, "*", options); + IEnumerable subdirectories = Directory.EnumerateDirectories(moduleBase, "*", options); ProcessPossibleVersionSubdirectories(subdirectories, versionFolders); } return versionFolders; } - private static void ProcessPossibleVersionSubdirectories(string[] subdirectories, List versionFolders) + private static void ProcessPossibleVersionSubdirectories(IEnumerable subdirectories, List versionFolders) { foreach (string subdir in subdirectories) { From a4181ab57eb5f2caafbfc8995a8b1e60622ba43a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 6 Aug 2021 13:09:51 +0500 Subject: [PATCH 33/55] Bump NJsonSchema from 10.5.0 to 10.5.1 (#15883) Bumps NJsonSchema from 10.5.0 to 10.5.1. --- updated-dependencies: - dependency-name: NJsonSchema dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 ff1715f852c..f19e9d748fd 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -34,7 +34,7 @@ - + From 40b2ad59cf6b8116cae81006b896a6eee3a7f901 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Mon, 9 Aug 2021 12:36:45 +0100 Subject: [PATCH 34/55] Update `Microsoft.CodeAnalysis.NetAnalyzers` (#15812) --- .globalconfig | 8 ++++++++ Analyzers.props | 3 ++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.globalconfig b/.globalconfig index fb0a7e89abd..80a1131796f 100644 --- a/.globalconfig +++ b/.globalconfig @@ -506,6 +506,10 @@ dotnet_diagnostic.CA1845.severity = warning # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1846 dotnet_diagnostic.CA1846.severity = warning +# CA1847: Use char literal for a single character lookup +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1847 +dotnet_diagnostic.CA1847.severity = warning + # CA2000: Dispose objects before losing scope # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2000 dotnet_diagnostic.CA2000.severity = none @@ -704,6 +708,10 @@ dotnet_diagnostic.CA2250.severity = warning # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2251 dotnet_diagnostic.CA2251.severity = warning +# CA2252: This API requires opting into preview features +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2252 +dotnet_diagnostic.CA2251.severity = none + # CA2300: Do not use insecure deserializer BinaryFormatter # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2300 dotnet_diagnostic.CA2300.severity = none diff --git a/Analyzers.props b/Analyzers.props index 4e6ed0381ff..3251e0fe846 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,6 +1,7 @@ - + + From 0a342601c8ce9527dac560a9e6709e7f70f2cd9c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Aug 2021 17:37:37 +0500 Subject: [PATCH 35/55] Bump NJsonSchema from 10.5.1 to 10.5.2 (#15891) Bumps NJsonSchema from 10.5.1 to 10.5.2. --- updated-dependencies: - dependency-name: NJsonSchema dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 f19e9d748fd..be3bf2892e9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -34,7 +34,7 @@ - + From 2ebac33a784ef0bd401b65a7c448b314390db924 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Mon, 9 Aug 2021 12:21:14 -0700 Subject: [PATCH 36/55] Update Language Version to 10 and fix related issues (#15886) --- PowerShell.Common.props | 4 +++- build.psm1 | 8 ++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/PowerShell.Common.props b/PowerShell.Common.props index 45e1f2788c1..ba5e6e2dffe 100644 --- a/PowerShell.Common.props +++ b/PowerShell.Common.props @@ -136,7 +136,7 @@ (c) Microsoft Corporation. net6.0 - 9.0 + 10.0 true true @@ -144,6 +144,8 @@ true true en-US + true + true true ../signing/visualstudiopublic.snk diff --git a/build.psm1 b/build.psm1 index 6028c5fdc3c..f9887250490 100644 --- a/build.psm1 +++ b/build.psm1 @@ -437,6 +437,14 @@ Fix steps: $Arguments += "--output", (Split-Path $Options.Output) } + # Add --self-contained due to "warning NETSDK1179: One of '--self-contained' or '--no-self-contained' options are required when '--runtime' is used." + if ($Options.Runtime -like 'fxdependent*') { + $Arguments += "--no-self-contained" + } + else { + $Arguments += "--self-contained" + } + if ($Options.Runtime -like 'win*' -or ($Options.Runtime -like 'fxdependent*' -and $environment.IsWindows)) { $Arguments += "/property:IsWindows=true" } From 427830843b98c73e031698723962d06885fc846f Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Mon, 9 Aug 2021 13:36:40 -0700 Subject: [PATCH 37/55] Add disable implicit namespace addition from test projects (#15895) --- test/Test.Common.props | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/Test.Common.props b/test/Test.Common.props index d965a3779a0..a1b4b8686d6 100644 --- a/test/Test.Common.props +++ b/test/Test.Common.props @@ -12,6 +12,8 @@ true true true + true + true From cced56d75a7f36ca28273f31636a9e434e8a2d41 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 9 Aug 2021 14:01:57 -0700 Subject: [PATCH 38/55] Make PS-Committee reviewed experimental features stable (#15864) --- .../commands/utility/DebugRunspaceCommand.cs | 1 - .../utility/ImportPowerShellDataFile.cs | 1 - .../utility/PSBreakpointCommandBase.cs | 1 - .../host/msh/ConsoleHostUserInterface.cs | 47 +++++---- .../msh/ConsoleHostUserInterfaceProgress.cs | 6 +- .../host/msh/ProgressNode.cs | 2 +- .../host/msh/ProgressPane.cs | 2 +- .../FileSystem_format_ps1xml.cs | 39 ++++---- .../FormatAndOutput/common/ListWriter.cs | 18 +--- .../FormatAndOutput/common/TableWriter.cs | 24 +---- .../ExperimentalFeature.cs | 18 ---- .../engine/MshCommandRuntime.cs | 2 +- .../engine/TypeTable_Types_Ps1Xml.cs | 75 +++++++------- .../engine/Utils.cs | 99 +++++++++---------- .../engine/hostifaces/MshHostUserInterface.cs | 9 +- .../engine/lang/parserutils.cs | 10 +- .../engine/remoting/commands/DebugJob.cs | 1 - .../namespaces/FileSystemProvider.cs | 2 +- .../namespaces/ProviderBase.cs | 2 +- test/powershell/Host/ConsoleHost.Tests.ps1 | 2 - .../TabCompletion/TabCompletion.Tests.ps1 | 2 +- .../Operators/ReplaceOperator.Tests.ps1 | 19 +--- .../NativeCommandProcessor.Tests.ps1 | 2 +- .../UnixStat.Tests.ps1 | 37 +++---- .../Format-List.Tests.ps1 | 2 - .../Format-Table.Tests.ps1 | 8 -- .../Get-Error.Tests.ps1 | 2 +- .../Get-FormatData.Tests.ps1 | 12 ++- .../PowerShellData.tests.ps1 | 6 +- .../RunspaceBreakpointManagement.Tests.ps1 | 14 --- .../powershell/engine/ETS/TypeTable.Tests.ps1 | 5 +- .../Formatting/OutputRendering.Tests.ps1 | 5 - .../engine/Formatting/PSStyle.Tests.ps1 | 5 - 33 files changed, 172 insertions(+), 308 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs index aa370c12ba1..f6ba764662f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs @@ -103,7 +103,6 @@ public Guid InstanceId /// /// Gets or sets a flag that tells PowerShell to automatically perform a BreakAll when the debugger is attached to the remote target. /// - [Experimental("Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace", ExperimentAction.Show)] [Parameter] public SwitchParameter BreakAll { get; set; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs index 036a7ae579c..5661df24fa9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs @@ -42,7 +42,6 @@ public string[] LiteralPath /// /// Gets or sets switch that determines if built-in limits are applied to the data. /// - [Experimental("Microsoft.PowerShell.Utility.PSImportPSDataFileSkipLimitCheck", ExperimentAction.Show)] [Parameter] public SwitchParameter SkipLimitCheck { get; set; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointCommandBase.cs index bc01f341861..e3590e380d4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointCommandBase.cs @@ -16,7 +16,6 @@ public abstract class PSBreakpointCommandBase : PSCmdlet /// /// Gets or sets the runspace where the breakpoints will be used. /// - [Experimental("Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace", ExperimentAction.Show)] [Parameter] [ValidateNotNull] [Runspace] diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index 822daa12828..756e294b226 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -63,29 +63,26 @@ internal ConsoleHostUserInterface(ConsoleHost parent) SupportsVirtualTerminal = true; _isInteractiveTestToolListening = false; - if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) + // check if TERM env var is set + // `dumb` means explicitly don't use VT + // `xterm-mono` and `xtermm` means support VT, but emit plaintext + switch (Environment.GetEnvironmentVariable("TERM")) { - // check if TERM env var is set - // `dumb` means explicitly don't use VT - // `xterm-mono` and `xtermm` means support VT, but emit plaintext - switch (Environment.GetEnvironmentVariable("TERM")) - { - case "dumb": - SupportsVirtualTerminal = false; - break; - case "xterm-mono": - case "xtermm": - PSStyle.Instance.OutputRendering = OutputRendering.PlainText; - break; - default: - break; - } - - // widely supported by CLI tools via https://no-color.org/ - if (Environment.GetEnvironmentVariable("NO_COLOR") != null) - { + case "dumb": + SupportsVirtualTerminal = false; + break; + case "xterm-mono": + case "xtermm": PSStyle.Instance.OutputRendering = OutputRendering.PlainText; - } + break; + default: + break; + } + + // widely supported by CLI tools via https://no-color.org/ + if (Environment.GetEnvironmentVariable("NO_COLOR") != null) + { + PSStyle.Instance.OutputRendering = OutputRendering.PlainText; } if (SupportsVirtualTerminal) @@ -1216,7 +1213,7 @@ public override void WriteDebugLine(string message) } else { - if (SupportsVirtualTerminal && ExperimentalFeature.IsEnabled("PSAnsiRendering")) + if (SupportsVirtualTerminal) { WriteLine(Utils.GetFormatStyleString(Utils.FormatStyle.Debug) + StringUtil.Format(ConsoleHostUserInterfaceStrings.DebugFormatString, message) + PSStyle.Instance.Reset); } @@ -1277,7 +1274,7 @@ public override void WriteVerboseLine(string message) } else { - if (SupportsVirtualTerminal && ExperimentalFeature.IsEnabled("PSAnsiRendering")) + if (SupportsVirtualTerminal) { WriteLine(Utils.GetFormatStyleString(Utils.FormatStyle.Verbose) + StringUtil.Format(ConsoleHostUserInterfaceStrings.VerboseFormatString, message) + PSStyle.Instance.Reset); } @@ -1321,7 +1318,7 @@ public override void WriteWarningLine(string message) } else { - if (SupportsVirtualTerminal && ExperimentalFeature.IsEnabled("PSAnsiRendering")) + if (SupportsVirtualTerminal) { WriteLine(Utils.GetFormatStyleString(Utils.FormatStyle.Warning) + StringUtil.Format(ConsoleHostUserInterfaceStrings.WarningFormatString, message) + PSStyle.Instance.Reset); } @@ -1393,7 +1390,7 @@ public override void WriteErrorLine(string value) { if (writer == _parent.ConsoleTextWriter) { - if (SupportsVirtualTerminal && ExperimentalFeature.IsEnabled("PSAnsiRendering")) + if (SupportsVirtualTerminal) { WriteLine(value); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs index a9b98b38934..ff0117c6e99 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs @@ -48,7 +48,7 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt _pendingProgress = null; - if (SupportsVirtualTerminal && ExperimentalFeature.IsEnabled(ExperimentalFeature.PSAnsiProgressFeatureName) && PSStyle.Instance.Progress.UseOSCIndicator) + if (SupportsVirtualTerminal && PSStyle.Instance.Progress.UseOSCIndicator) { // OSC sequence to turn off progress indicator // https://github.com/microsoft/terminal/issues/6700 @@ -99,7 +99,7 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt { // Update the progress pane only when the timer set up the update flag or WriteProgress is completed. // As a result, we do not block WriteProgress and whole script and eliminate unnecessary console locks and updates. - if (SupportsVirtualTerminal && ExperimentalFeature.IsEnabled(ExperimentalFeature.PSAnsiProgressFeatureName) && PSStyle.Instance.Progress.UseOSCIndicator) + if (SupportsVirtualTerminal && PSStyle.Instance.Progress.UseOSCIndicator) { int percentComplete = record.PercentComplete; if (percentComplete < 0) @@ -115,7 +115,7 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt } // If VT is not supported, we change ProgressView to classic - if (!SupportsVirtualTerminal && ExperimentalFeature.IsEnabled(ExperimentalFeature.PSAnsiProgressFeatureName)) + if (!SupportsVirtualTerminal) { PSStyle.Instance.Progress.View = ProgressView.Classic; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs index f6d1538b8da..c8f542052a1 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs @@ -353,7 +353,7 @@ private static void RenderFullDescription(string description, string indent, int internal static bool IsMinimalProgressRenderingEnabled() { - return ExperimentalFeature.IsEnabled(ExperimentalFeature.PSAnsiProgressFeatureName) && PSStyle.Instance.Progress.View == ProgressView.Minimal; + return PSStyle.Instance.Progress.View == ProgressView.Minimal; } /// diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs index f0cdadc73eb..a3be724b7c4 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs @@ -115,7 +115,7 @@ class ProgressPane // create cleared region to clear progress bar later _savedRegion = tempProgressRegion; - if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSAnsiProgressFeatureName) && PSStyle.Instance.Progress.View != ProgressView.Minimal) + if (PSStyle.Instance.Progress.View != ProgressView.Minimal) { for (int row = 0; row < rows; row++) { diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/FileSystem_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/FileSystem_format_ps1xml.cs index 374cadf31d8..01cba83cd00 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/FileSystem_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/FileSystem_format_ps1xml.cs @@ -42,27 +42,24 @@ internal static IEnumerable GetFormatData() private static IEnumerable ViewsOf_FileSystemTypes(CustomControl[] sharedControls) { #if UNIX - if (ExperimentalFeature.IsEnabled("PSUnixFileStat")) - { - yield return new FormatViewDefinition("childrenWithUnixStat", - TableControl.Create() - .GroupByProperty("PSParentPath", customControl: sharedControls[0]) - .AddHeader(Alignment.Left, label: "UnixMode", width: 10) - .AddHeader(Alignment.Left, label: "User", width: 16) - .AddHeader(Alignment.Left, label: "Group", width: 16) - .AddHeader(Alignment.Right, label: "LastWriteTime", width: 18) - .AddHeader(Alignment.Right, label: "Size", width: 14) - .AddHeader(Alignment.Left, label: "Name") - .StartRowDefinition(wrap: true) - .AddPropertyColumn("UnixMode") - .AddPropertyColumn("User") - .AddPropertyColumn("Group") - .AddScriptBlockColumn(scriptBlock: @"'{0:d} {0:HH}:{0:mm}' -f $_.LastWriteTime") - .AddPropertyColumn("Size") - .AddPropertyColumn("NameString") - .EndRowDefinition() - .EndTable()); - } + yield return new FormatViewDefinition("childrenWithUnixStat", + TableControl.Create() + .GroupByProperty("PSParentPath", customControl: sharedControls[0]) + .AddHeader(Alignment.Left, label: "UnixMode", width: 10) + .AddHeader(Alignment.Left, label: "User", width: 16) + .AddHeader(Alignment.Left, label: "Group", width: 16) + .AddHeader(Alignment.Right, label: "LastWriteTime", width: 18) + .AddHeader(Alignment.Right, label: "Size", width: 14) + .AddHeader(Alignment.Left, label: "Name") + .StartRowDefinition(wrap: true) + .AddPropertyColumn("UnixMode") + .AddPropertyColumn("User") + .AddPropertyColumn("Group") + .AddScriptBlockColumn(scriptBlock: @"'{0:d} {0:HH}:{0:mm}' -f $_.LastWriteTime") + .AddPropertyColumn("Size") + .AddPropertyColumn("NameString") + .EndRowDefinition() + .EndTable()); #endif yield return new FormatViewDefinition("children", diff --git a/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs index 99b0893135d..b5c97c3d85d 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs @@ -222,25 +222,11 @@ private void WriteSingleLineHelper(string prependString, string line, LineOutput { if (k == 0) { - if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) - { - lo.WriteLine(PSStyle.Instance.Formatting.FormatAccent + prependString + PSStyle.Instance.Reset + sc[k]); - } - else - { - lo.WriteLine(prependString + sc[k]); - } + lo.WriteLine(PSStyle.Instance.Formatting.FormatAccent + prependString + PSStyle.Instance.Reset + sc[k]); } else { - if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) - { - lo.WriteLine(padding + PSStyle.Instance.Formatting.FormatAccent + PSStyle.Instance.Reset + sc[k]); - } - else - { - lo.WriteLine(padding + sc[k]); - } + lo.WriteLine(padding + PSStyle.Instance.Formatting.FormatAccent + PSStyle.Instance.Reset + sc[k]); } } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs index 309d36182d8..74d5f543e07 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs @@ -43,7 +43,6 @@ private sealed class ScreenInfo private ScreenInfo _si; private const char ESC = '\u001b'; - private const string ResetConsoleVt100Code = "\u001b[m"; private List _header; @@ -156,14 +155,7 @@ internal int GenerateHeader(string[] values, LineOutput lo) { foreach (string line in _header) { - if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) - { - lo.WriteLine(PSStyle.Instance.Formatting.TableHeader + line + PSStyle.Instance.Reset); - } - else - { - lo.WriteLine(line); - } + lo.WriteLine(PSStyle.Instance.Formatting.TableHeader + line + PSStyle.Instance.Reset); } return _header.Count; @@ -241,7 +233,7 @@ internal void GenerateRow(string[] values, LineOutput lo, bool multiLine, ReadOn foreach (string line in GenerateTableRow(values, currentAlignment, lo.DisplayCells)) { generatedRows?.Add(line); - if (ExperimentalFeature.IsEnabled("PSAnsiRendering") && isHeader) + if (isHeader) { lo.WriteLine(PSStyle.Instance.Formatting.TableHeader + line + PSStyle.Instance.Reset); } @@ -255,7 +247,7 @@ internal void GenerateRow(string[] values, LineOutput lo, bool multiLine, ReadOn { string line = GenerateRow(values, currentAlignment, dc); generatedRows?.Add(line); - if (ExperimentalFeature.IsEnabled("PSAnsiRendering") && isHeader) + if (isHeader) { lo.WriteLine(PSStyle.Instance.Formatting.TableHeader + line + PSStyle.Instance.Reset); } @@ -469,15 +461,7 @@ private string GenerateRow(string[] values, ReadOnlySpan alignment, Display if (values[k].Contains(ESC)) { // Reset the console output if the content of this column contains ESC - if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) - { - // Remove definition of `ResetConsoleVt10Code` when PSAnsiRendering is not experimental - sb.Append(PSStyle.Instance.Reset); - } - else - { - sb.Append(ResetConsoleVt100Code); - } + sb.Append(PSStyle.Instance.Reset); } } diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 84aa78534aa..2fbf9eb623e 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -21,7 +21,6 @@ public class ExperimentalFeature #region Const Members internal const string EngineSource = "PSEngine"; - internal const string PSAnsiProgressFeatureName = "PSAnsiProgress"; internal const string PSNativeCommandArgumentPassingFeatureName = "PSNativeCommandArgumentPassing"; #endregion @@ -111,29 +110,12 @@ static ExperimentalFeature() new ExperimentalFeature( name: "PSCommandNotFoundSuggestion", description: "Recommend potential commands based on fuzzy search on a CommandNotFoundException"), -#if UNIX - new ExperimentalFeature( - name: "PSUnixFileStat", - description: "Provide unix permission information for files and directories"), -#endif - new ExperimentalFeature( - name: "PSCultureInvariantReplaceOperator", - description: "Use culture invariant to-string convertor for lval in replace operator"), new ExperimentalFeature( name: "PSNativePSPathResolution", description: "Convert PSPath to filesystem path, if possible, for native commands"), - new ExperimentalFeature( - name: "PSNotApplyErrorActionToStderr", - description: "Don't have $ErrorActionPreference affect stderr output"), new ExperimentalFeature( name: "PSSubsystemPluginModel", description: "A plugin model for registering and un-registering PowerShell subsystems"), - new ExperimentalFeature( - name: "PSAnsiRendering", - description: "Enable $PSStyle variable to control ANSI rendering of strings"), - new ExperimentalFeature( - name: PSAnsiProgressFeatureName, - description: "Enable lightweight progress bar that leverages ANSI codes for rendering"), new ExperimentalFeature( name: PSNativeCommandArgumentPassingFeatureName, description: "Use ArgumentList when invoking a native command"), diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index c9a83a8bb32..3a440478d1a 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -2839,7 +2839,7 @@ internal void _WriteErrorSkipAllowCheck(ErrorRecord errorRecord, ActionPreferenc this.PipelineProcessor.LogExecutionError(_thisCommand.MyInvocation, errorRecord); } - if (!(ExperimentalFeature.IsEnabled("PSNotApplyErrorActionToStderr") && isNativeError)) + if (!isNativeError) { this.PipelineProcessor.ExecutionFailed = true; diff --git a/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs b/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs index a8bec98469f..7113c0953cb 100644 --- a/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs @@ -9227,45 +9227,42 @@ private void Process_Types_Ps1Xml(string filePath, ConcurrentBag errors) #if UNIX #region UnixStat - if (ExperimentalFeature.IsEnabled("PSUnixFileStat")) - { - typeName = @"System.IO.FileSystemInfo"; - typeMembers = _extendedMembers.GetOrAdd(typeName, GetValueFactoryBasedOnInitCapacity(capacity: 1)); - - // Where we have a method to invoke below, first check to be sure that the object is present - // to avoid null reference issues - newMembers.Add(@"UnixMode"); - AddMember( - errors, - typeName, - new PSScriptProperty(@"UnixMode", GetScriptBlock(@"if ($this.UnixStat) { $this.UnixStat.GetModeString() }")), - typeMembers, - isOverride: false); - - newMembers.Add(@"User"); - AddMember( - errors, - typeName, - new PSScriptProperty(@"User", GetScriptBlock(@" if ($this.UnixStat) { $this.UnixStat.GetUserName() } ")), - typeMembers, - isOverride: false); - - newMembers.Add(@"Group"); - AddMember( - errors, - typeName, - new PSScriptProperty(@"Group", GetScriptBlock(@" if ($this.UnixStat) { $this.UnixStat.GetGroupName() } ")), - typeMembers, - isOverride: false); - - newMembers.Add(@"Size"); - AddMember( - errors, - typeName, - new PSScriptProperty(@"Size", GetScriptBlock(@"$this.UnixStat.Size")), - typeMembers, - isOverride: false); - } + typeName = @"System.IO.FileSystemInfo"; + typeMembers = _extendedMembers.GetOrAdd(typeName, GetValueFactoryBasedOnInitCapacity(capacity: 1)); + + // Where we have a method to invoke below, first check to be sure that the object is present + // to avoid null reference issues + newMembers.Add(@"UnixMode"); + AddMember( + errors, + typeName, + new PSScriptProperty(@"UnixMode", GetScriptBlock(@"if ($this.UnixStat) { $this.UnixStat.GetModeString() }")), + typeMembers, + isOverride: false); + + newMembers.Add(@"User"); + AddMember( + errors, + typeName, + new PSScriptProperty(@"User", GetScriptBlock(@" if ($this.UnixStat) { $this.UnixStat.GetUserName() } ")), + typeMembers, + isOverride: false); + + newMembers.Add(@"Group"); + AddMember( + errors, + typeName, + new PSScriptProperty(@"Group", GetScriptBlock(@" if ($this.UnixStat) { $this.UnixStat.GetGroupName() } ")), + typeMembers, + isOverride: false); + + newMembers.Add(@"Size"); + AddMember( + errors, + typeName, + new PSScriptProperty(@"Size", GetScriptBlock(@"$this.UnixStat.Size")), + typeMembers, + isOverride: false); #endregion #endif diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 8c37713234f..42b387cb6b9 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1791,22 +1791,19 @@ internal static bool ShouldOutputPlainText(bool isHost, bool? supportsVirtualTer { var outputRendering = OutputRendering.Ansi; - if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) + if (supportsVirtualTerminal != false) { - if (supportsVirtualTerminal != false) + switch (PSStyle.Instance.OutputRendering) { - switch (PSStyle.Instance.OutputRendering) - { - case OutputRendering.Automatic: - outputRendering = OutputRendering.Ansi; - break; - case OutputRendering.Host: - outputRendering = isHost ? OutputRendering.Ansi : OutputRendering.PlainText; - break; - default: - outputRendering = PSStyle.Instance.OutputRendering; - break; - } + case OutputRendering.Automatic: + outputRendering = OutputRendering.Ansi; + break; + case OutputRendering.Host: + outputRendering = isHost ? OutputRendering.Ansi : OutputRendering.PlainText; + break; + default: + outputRendering = PSStyle.Instance.OutputRendering; + break; } } @@ -1815,25 +1812,22 @@ internal static bool ShouldOutputPlainText(bool isHost, bool? supportsVirtualTer internal static string GetOutputString(string s, bool isHost, bool? supportsVirtualTerminal = null, bool isOutputRedirected = false) { - if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) - { - var sd = new ValueStringDecorated(s); + var sd = new ValueStringDecorated(s); - if (sd.IsDecorated) + if (sd.IsDecorated) + { + var outputRendering = OutputRendering.Ansi; + if (InternalTestHooks.BypassOutputRedirectionCheck) { - var outputRendering = OutputRendering.Ansi; - if (InternalTestHooks.BypassOutputRedirectionCheck) - { - isOutputRedirected = false; - } - - if (isOutputRedirected || ShouldOutputPlainText(isHost, supportsVirtualTerminal)) - { - outputRendering = OutputRendering.PlainText; - } + isOutputRedirected = false; + } - s = sd.ToString(outputRendering); + if (isOutputRedirected || ShouldOutputPlainText(isHost, supportsVirtualTerminal)) + { + outputRendering = OutputRendering.PlainText; } + + s = sd.ToString(outputRendering); } return s; @@ -1862,33 +1856,28 @@ internal static string GetFormatStyleString(FormatStyle formatStyle) return string.Empty; } - if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) - { - PSStyle psstyle = PSStyle.Instance; - switch (formatStyle) - { - case FormatStyle.Reset: - return psstyle.Reset; - case FormatStyle.FormatAccent: - return psstyle.Formatting.FormatAccent; - case FormatStyle.TableHeader: - return psstyle.Formatting.TableHeader; - case FormatStyle.ErrorAccent: - return psstyle.Formatting.ErrorAccent; - case FormatStyle.Error: - return psstyle.Formatting.Error; - case FormatStyle.Warning: - return psstyle.Formatting.Warning; - case FormatStyle.Verbose: - return psstyle.Formatting.Verbose; - case FormatStyle.Debug: - return psstyle.Formatting.Debug; - default: - return string.Empty; - } + PSStyle psstyle = PSStyle.Instance; + switch (formatStyle) + { + case FormatStyle.Reset: + return psstyle.Reset; + case FormatStyle.FormatAccent: + return psstyle.Formatting.FormatAccent; + case FormatStyle.TableHeader: + return psstyle.Formatting.TableHeader; + case FormatStyle.ErrorAccent: + return psstyle.Formatting.ErrorAccent; + case FormatStyle.Error: + return psstyle.Formatting.Error; + case FormatStyle.Warning: + return psstyle.Formatting.Warning; + case FormatStyle.Verbose: + return psstyle.Formatting.Verbose; + case FormatStyle.Debug: + return psstyle.Formatting.Debug; + default: + return string.Empty; } - - return string.Empty; } #endregion diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index df30439f344..2d8c16f2b7b 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -620,13 +620,10 @@ internal void TranscribeResult(Runspace sourceRunspace, string resultText) resultText = resultText.TrimEnd(); - if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) + var text = new ValueStringDecorated(resultText); + if (text.IsDecorated) { - var text = new ValueStringDecorated(resultText); - if (text.IsDecorated) - { - resultText = text.ToString(OutputRendering.PlainText); - } + resultText = text.ToString(OutputRendering.PlainText); } foreach (TranscriptionOption transcript in TranscriptionData.Transcripts.Prepend(TranscriptionData.SystemTranscript)) diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs index 52c64400ccd..865f3530d71 100644 --- a/src/System.Management.Automation/engine/lang/parserutils.cs +++ b/src/System.Management.Automation/engine/lang/parserutils.cs @@ -969,15 +969,7 @@ internal static object ReplaceOperator(ExecutionContext context, IScriptExtent e IEnumerator list = LanguagePrimitives.GetEnumerator(lval); if (list == null) { - string lvalString; - if (ExperimentalFeature.IsEnabled("PSCultureInvariantReplaceOperator")) - { - lvalString = PSObject.ToStringParser(context, lval) ?? string.Empty; - } - else - { - lvalString = lval?.ToString() ?? string.Empty; - } + string lvalString = PSObject.ToStringParser(context, lval) ?? string.Empty; return replacer.Replace(lvalString); } diff --git a/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs b/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs index 777f56807fe..8e5732304e9 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs @@ -100,7 +100,6 @@ public Guid InstanceId /// /// Gets or sets a flag that tells PowerShell to automatically perform a BreakAll when the debugger is attached to the remote target. /// - [Experimental("Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace", ExperimentAction.Show)] [Parameter] public SwitchParameter BreakAll { get; set; } diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 2eb0de56d52..02d9708d045 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -2063,7 +2063,7 @@ string ToModeString(FileSystemInfo fileSystemInfo) /// Name if a file or directory, Name -> Target if symlink. public static string NameString(PSObject instance) { - if (ExperimentalFeature.IsEnabled("PSAnsiRendering") && ExperimentalFeature.IsEnabled("PSAnsiRenderingFileInfo")) + if (ExperimentalFeature.IsEnabled("PSAnsiRenderingFileInfo")) { if (instance?.BaseObject is FileSystemInfo fileInfo) { diff --git a/src/System.Management.Automation/namespaces/ProviderBase.cs b/src/System.Management.Automation/namespaces/ProviderBase.cs index 2d8c35c7fc9..d3fad54bdd7 100644 --- a/src/System.Management.Automation/namespaces/ProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ProviderBase.cs @@ -1823,7 +1823,7 @@ private PSObject WrapOutputInPSObject( #if UNIX // Add a commonstat structure to file system objects - if (ExperimentalFeature.IsEnabled("PSUnixFileStat") && ProviderInfo.ImplementingType == typeof(Microsoft.PowerShell.Commands.FileSystemProvider)) + if (ProviderInfo.ImplementingType == typeof(Microsoft.PowerShell.Commands.FileSystemProvider)) { try { diff --git a/test/powershell/Host/ConsoleHost.Tests.ps1 b/test/powershell/Host/ConsoleHost.Tests.ps1 index 7b7571ce177..5c903f53745 100644 --- a/test/powershell/Host/ConsoleHost.Tests.ps1 +++ b/test/powershell/Host/ConsoleHost.Tests.ps1 @@ -1033,12 +1033,10 @@ Describe 'Console host name' -Tag CI { Describe 'TERM env var' -Tag CI { BeforeAll { $oldTERM = $env:TERM - $PSDefaultParameterValues.Add('It:Skip', (-not $EnabledExperimentalFeatures.Contains('PSAnsiRendering'))) } AfterAll { $env:TERM = $oldTERM - $PSDefaultParameterValues.Remove('It:Skip') } It 'TERM = "dumb"' { diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 39ab4968b5e..2674a74a21a 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -367,7 +367,7 @@ Describe "TabCompletion" -Tags CI { } It 'Should complete Get-ChildItem | -View' -TestCases ( - @{ cmd = 'Format-Table'; expected = "children childrenWithHardlink$(if ($EnabledExperimentalFeatures.Contains('PSUnixFileStat')) { ' childrenWithUnixStat' })" }, + @{ cmd = 'Format-Table'; expected = "children childrenWithHardlink$(if (!$IsWindows) { ' childrenWithUnixStat' })" }, @{ cmd = 'Format-List'; expected = 'children' }, @{ cmd = 'Format-Wide'; expected = 'children' }, @{ cmd = 'Format-Custom'; expected = '' } diff --git a/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 b/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 index b72779f59c4..074351d3414 100644 --- a/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 +++ b/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 @@ -85,24 +85,13 @@ Describe "Replace Operator" -Tags CI { Describe "Culture-invariance tests for -split and -replace" -Tags CI { BeforeAll { - $skipTest = -not [ExperimentalFeature]::IsEnabled("PSCultureInvariantReplaceOperator") - if ($skipTest) { - Write-Verbose "Test Suite Skipped. The test suite requires the experimental feature 'PSCultureInvariantReplaceOperator' to be enabled." -Verbose - $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() - $PSDefaultParameterValues["it:skip"] = $true - } else { - $prevCulture = [cultureinfo]::CurrentCulture - # The French culture uses "," as the decimal mark. - [cultureinfo]::CurrentCulture = 'fr' - } + $prevCulture = [cultureinfo]::CurrentCulture + # The French culture uses "," as the decimal mark. + [cultureinfo]::CurrentCulture = 'fr' } AfterAll { - if ($skipTest) { - $global:PSDefaultParameterValues = $originalDefaultParameterValues - } else { - [cultureinfo]::CurrentCulture = $prevCulture - } + [cultureinfo]::CurrentCulture = $prevCulture } It "-split: LHS stringification is not culture-sensitive" { diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 index 8bef53a9523..6888f5cba77 100644 --- a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 +++ b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 @@ -147,7 +147,7 @@ Describe "Native Command Processor" -tags "Feature" { } } - It '$ErrorActionPreference does not apply to redirected stderr output' -Skip:(!$EnabledExperimentalFeatures.Contains('PSNotApplyErrorActionToStderr')) { + It '$ErrorActionPreference does not apply to redirected stderr output' { pwsh -noprofile -command '$ErrorActionPreference = ''Stop''; testexe -stderr stop 2>$null; ''hello''; $error; $?' | Should -BeExactly 'hello','True' } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/UnixStat.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/UnixStat.Tests.ps1 index 1fe6113c92b..b14df30e7e2 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/UnixStat.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/UnixStat.Tests.ps1 @@ -1,25 +1,13 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "UnixFileSystem additions" -Tag "CI" { - # if PSUnixFileStat is converted from an experimental feature, these tests will need to be changed - BeforeAll { - $experimentalFeatureName = "PSUnixFileStat" - $skipTest = -not $EnabledExperimentalFeatures.Contains($experimentalFeatureName) - $PSDefaultParameterValues.Add('It:Skip', $skipTest) - } - AfterAll { - $PSDefaultParameterValues.Remove('It:Skip') - } Context "Basic Validation" { + BeforeAll { + $PSDefaultParameterValues.Add('It:Skip', $IsWindows) + } - It "Should be an experimental feature on non-Windows systems" { - $feature = Get-ExperimentalFeature -Name $experimentalFeatureName - if ( $IsWindows ) { - $feature | Should -BeNullOrEmpty - } - else { - $feature.Name | Should -Be $experimentalFeatureName - } + AfterAll { + $PSDefaultParameterValues.Remove('It:Skip') } It "Should include a UnixStat property" { @@ -36,9 +24,7 @@ Describe "UnixFileSystem additions" -Tag "CI" { Context "Validation of additional properties on file system objects" { BeforeAll { - if ( $IsWindows ) { - return - } + $PSDefaultParameterValues.Add('It:Skip', $IsWindows) $testDir = "${TestDrive}/TestDir" $testFile = "${testDir}/TestFile" @@ -55,6 +41,10 @@ Describe "UnixFileSystem additions" -Tag "CI" { @{ Mode = '1777'; Perm = 'drwxrwxrwt'; Item = "${testDir}" } } + AfterAll { + $PSDefaultParameterValues.Remove('It:Skip') + } + BeforeEach { $null = New-Item -ItemType Directory -Path "${testDir}" $null = New-Item -ItemType File -Path "${testFile}" @@ -87,7 +77,8 @@ Describe "UnixFileSystem additions" -Tag "CI" { Context "Other properties of UnixStat object" { BeforeAll { - if ( $IsWindows ) { + $PSDefaultParameterValues.Add('It:Skip', $IsWindows) + if ($IsWindows) { return } @@ -115,6 +106,10 @@ Describe "UnixFileSystem additions" -Tag "CI" { @{ Expected = $expectedDirSize; Observed = $Dir.UnixStat.Size; Title = "DirSize" } } + AfterAll { + $PSDefaultParameterValues.Remove('It:Skip') + } + It "Should have correct values in UnixStat property for ''" -TestCases $testCases { param ( $Title, $expected, $observed ) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-List.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-List.Tests.ps1 index bab70dae9e7..11f2297997b 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-List.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-List.Tests.ps1 @@ -213,12 +213,10 @@ dbda : KM Describe 'Format-List color tests' { BeforeAll { - $PSDefaultParameterValues.Add('It:Skip', (-not $EnabledExperimentalFeatures.Contains('PSAnsiRendering'))) [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('ForceFormatListFixedLabelWidth', $true) } AfterAll { - $PSDefaultParameterValues.Remove('It:Skip') [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('ForceFormatListFixedLabelWidth', $false) } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 index 5a003db9b69..277ca8d2d8e 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 @@ -848,14 +848,6 @@ A Name B } Describe 'Table color tests' { - BeforeAll { - $PSDefaultParameterValues.Add('It:Skip', (-not $EnabledExperimentalFeatures.Contains('PSAnsiRendering'))) - } - - AfterAll { - $PSDefaultParameterValues.Remove('It:Skip') - } - It 'Table header should use FormatAccent' { ([pscustomobject]@{foo = 1} | Format-Table | Out-String).Trim() | Should -BeExactly @" $($PSStyle.Formatting.FormatAccent)foo$($PSStyle.Reset) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 index 260f1f00aea..9581b3a8fd0 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 @@ -126,7 +126,7 @@ Describe 'Get-Error tests' -Tag CI { $out | Should -BeLikeExactly "*$expectedExceptionType*" } - It 'Get-Error uses Error color for Message and PositionMessage members' -Skip:(!$EnabledExperimentalFeatures.Contains("PSAnsiRendering")) { + It 'Get-Error uses Error color for Message and PositionMessage members' { $suppressVT = $false if (Test-Path env:/__SuppressAnsiEscapeSequences) { $suppressVT = $true diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-FormatData.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-FormatData.Tests.ps1 index 04bffe8df82..d420e6ce085 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-FormatData.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-FormatData.Tests.ps1 @@ -21,13 +21,19 @@ Describe "Get-FormatData" -Tags "CI" { } It "Can get format data requiring v5.1+ with <cmd>" -TestCases $cmds { param([scriptblock] $cmd) + + if ($IsWindows) { + $expectedCount = 4 + } else { + # UnixStat addes extra one + $expectedCount = 5 + } + $format = & $cmd $format.TypeNames | Should -HaveCount 2 $format.TypeNames[0] | Should -BeExactly "System.IO.DirectoryInfo" $format.TypeNames[1] | Should -BeExactly "System.IO.FileInfo" - - $isUnixStatEnabled = $EnabledExperimentalFeatures -contains 'PSUnixFileStat' - $format.FormatViewDefinition | Should -HaveCount ($isUnixStatEnabled ? 5 : 4) + $format.FormatViewDefinition | Should -HaveCount $expectedCount } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/PowerShellData.tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/PowerShellData.tests.ps1 index 222bbf7e900..cfba4a4cbed 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/PowerShellData.tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/PowerShellData.tests.ps1 @@ -9,10 +9,6 @@ Describe "Tests for the Import-PowerShellDataFile cmdlet" -Tags "CI" { } $largePsd1Builder.Append('}') Set-Content -Path $largePsd1Path -Value $largePsd1Builder.ToString() - - if ((Get-ExperimentalFeature Microsoft.PowerShell.Utility.PSImportPSDataFileSkipLimitCheck).Enabled -ne $true) { - $skipTest = $true - } } It "Validates error on a missing path" { @@ -49,7 +45,7 @@ Describe "Tests for the Import-PowerShellDataFile cmdlet" -Tags "CI" { { Import-PowerShellDataFile $largePsd1Path } | Should -Throw -ErrorId 'System.InvalidOperationException,Microsoft.PowerShell.Commands.ImportPowerShellDataFileCommand' } - It 'Succeeds if -NoLimit is used and has more than 500 keys' -Skip:$skipTest { + It 'Succeeds if -NoLimit is used and has more than 500 keys' { $result = Import-PowerShellDataFile $largePsd1Path -SkipLimitCheck $result.Keys.Count | Should -Be 501 } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceBreakpointManagement.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceBreakpointManagement.Tests.ps1 index fe131f99117..75fb0d98358 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceBreakpointManagement.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceBreakpointManagement.Tests.ps1 @@ -1,18 +1,9 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -$FeatureEnabled = $EnabledExperimentalFeatures.Contains('Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace') - Describe 'Runspace Breakpoint Unit Tests - Feature-Enabled' -Tags 'CI' { BeforeAll { - if (!$FeatureEnabled) { - Write-Verbose 'Test series skipped. This series of tests requires the experimental feature ''Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace'' to be enabled.' -Verbose - $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() - $PSDefaultParameterValues['it:skip'] = $true - return - } - # Start a job; this will create a runspace in which we can manage breakpoints $job = Start-Job -ScriptBlock { Set-PSBreakpoint -Command Start-Sleep @@ -37,11 +28,6 @@ Describe 'Runspace Breakpoint Unit Tests - Feature-Enabled' -Tags 'CI' { } AfterAll { - if (!$FeatureEnabled) { - $global:PSDefaultParameterValues = $originalDefaultParameterValues - return - } - # Remove the running job forcibly (whether it has finished or not) Remove-Job -Job $job -Force } diff --git a/test/powershell/engine/ETS/TypeTable.Tests.ps1 b/test/powershell/engine/ETS/TypeTable.Tests.ps1 index 37e8f08686d..55b909145a8 100644 --- a/test/powershell/engine/ETS/TypeTable.Tests.ps1 +++ b/test/powershell/engine/ETS/TypeTable.Tests.ps1 @@ -18,13 +18,10 @@ Describe "Built-in type information tests" -Tag "CI" { } It "Should have correct number of built-in type items in type table" { - $isUnixStatEnabled = $EnabledExperimentalFeatures -contains 'PSUnixFileStat' $expected = if ($IsWindows) { 273 - } elseif ($isUnixStatEnabled) { - 272 } else { - 271 + 272 } $types.Count | Should -BeExactly $expected } diff --git a/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 index 7feb978bd9d..1ca13cb138b 100644 --- a/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 +++ b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 @@ -3,7 +3,6 @@ Describe 'OutputRendering tests' { BeforeAll { - $PSDefaultParameterValues.Add('It:Skip', (-not $EnabledExperimentalFeatures.Contains('PSAnsiRendering'))) $th = New-TestHost $rs = [runspacefactory]::Createrunspace($th) $rs.open() @@ -11,10 +10,6 @@ Describe 'OutputRendering tests' { $ps.Runspace = $rs } - AfterAll { - $PSDefaultParameterValues.Remove('It:Skip') - } - BeforeEach { if ($null -ne $PSStyle) { $oldOutputRendering = $PSStyle.OutputRendering diff --git a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 index b4d966b8b21..f6cde2a4a01 100644 --- a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 +++ b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 @@ -3,7 +3,6 @@ Describe 'Tests for $PSStyle automatic variable' { BeforeAll { - $PSDefaultParameterValues.Add('It:Skip', (-not $EnabledExperimentalFeatures.Contains('PSAnsiRendering'))) $styleDefaults = @{ Reset = "`e[0m" BlinkOff = "`e[25m" @@ -82,10 +81,6 @@ Describe 'Tests for $PSStyle automatic variable' { } } - AfterAll { - $PSDefaultParameterValues.Remove('It:Skip') - } - It '$PSStyle has correct default for OutputRendering' { $PSStyle | Should -Not -BeNullOrEmpty $PSStyle.OutputRendering | Should -BeExactly 'Automatic' From 2f5150f5e5fdce74e22b8697329c5e5d63287f0d Mon Sep 17 00:00:00 2001 From: Robert Holt <rjmholt_msft@outlook.com> Date: Mon, 9 Aug 2021 15:27:09 -0700 Subject: [PATCH 39/55] Make Measure-Object property test independent of the filesystem (#15879) --- .../Measure-Object.Tests.ps1 | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Measure-Object.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Measure-Object.Tests.ps1 index ea96741de3a..b1cf1b36d39 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Measure-Object.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Measure-Object.Tests.ps1 @@ -64,10 +64,13 @@ Describe "Measure-Object" -Tags "CI" { } It "Should be able to count using the Property switch" { - $expected = $(Get-ChildItem $TestDrive).Length - $actual = $(Get-ChildItem $TestDrive | Measure-Object -Property Length).Count + $items = @( + [pscustomobject]@{ X = 'a'; Y = 'b' } + [pscustomobject]@{ X = 'c' } + [pscustomobject]@{ X = 'e'; Y = 'f' } + ) - $actual | Should -Be $expected + ($items | Measure-Object -Property Y).Count | Should -Be 2 } It "Should be able to use wildcards for the Property argument" { From 7c7526a3a11a6f59eeef2aa693d1b11495a37242 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Aug 2021 13:01:49 +0500 Subject: [PATCH 40/55] Bump Microsoft.CodeAnalysis.NetAnalyzers (#15904) Bumps [Microsoft.CodeAnalysis.NetAnalyzers](https://github.com/dotnet/roslyn-analyzers) from 6.0.0-rc1.21366.2 to 6.0.0-rc1.21406.1. - [Release notes](https://github.com/dotnet/roslyn-analyzers/releases) - [Changelog](https://github.com/dotnet/roslyn-analyzers/blob/main/PostReleaseActivities.md) - [Commits](https://github.com/dotnet/roslyn-analyzers/commits) --- updated-dependencies: - dependency-name: Microsoft.CodeAnalysis.NetAnalyzers dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index 3251e0fe846..f5ac2ffbbcd 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,7 @@ <Project> <ItemGroup> <PackageReference Include="DotNetAnalyzers.DocumentationAnalyzers" Version="1.0.0-beta.59" PrivateAssets="all" /> - <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="6.0.0-rc1.21366.2" PrivateAssets="all" /> + <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="6.0.0-rc1.21406.1" PrivateAssets="all" /> <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.354" PrivateAssets="all" /> </ItemGroup> </Project> From e2c23fc5bd035251bed71413ad7c467c99dafd76 Mon Sep 17 00:00:00 2001 From: Paul Higinbotham <paulhi@microsoft.com> Date: Tue, 10 Aug 2021 11:03:53 -0700 Subject: [PATCH 41/55] Add error catch for unauthorized access when removing `AppLocker` test files (#15881) --- src/System.Management.Automation/utils/PathUtils.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/System.Management.Automation/utils/PathUtils.cs b/src/System.Management.Automation/utils/PathUtils.cs index 45ba787aee2..0034681e126 100644 --- a/src/System.Management.Automation/utils/PathUtils.cs +++ b/src/System.Management.Automation/utils/PathUtils.cs @@ -444,6 +444,10 @@ internal static bool TryDeleteFile(string filepath) { // file is in use on Windows } + catch (UnauthorizedAccessException) + { + // user does not have permissions + } } return false; From b70f06ccc6041281b0f4dc6eaeefdbe5c649636d Mon Sep 17 00:00:00 2001 From: Armaan Mcleod <armaan_mcleod@outlook.com> Date: Fri, 13 Aug 2021 02:06:58 +1000 Subject: [PATCH 42/55] Fix issue with Get-Process -Module failing to stop when piped to Select-Object (#15682) --- .../commands/management/Process.cs | 4 ++++ .../Microsoft.PowerShell.Management/Get-Process.Tests.ps1 | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index fe291da8eb1..ef4f5b1a7b4 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -640,6 +640,10 @@ protected override void ProcessRecord() WriteNonTerminatingError(process, ex, ProcessResources.CouldNotEnumerateModules, "CouldNotEnumerateModules", ErrorCategory.PermissionDenied); } } + catch (PipelineStoppedException) + { + throw; + } catch (Exception exception) { WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateModules, "CouldNotEnumerateModules", ErrorCategory.PermissionDenied); diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Process.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Process.Tests.ps1 index 6143ddca0be..2169c23b705 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Process.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Process.Tests.ps1 @@ -87,6 +87,11 @@ Describe "Get-Process" -Tags "CI" { { Get-Process -Module -ErrorAction Stop } | Should -Throw -ErrorId "CouldNotEnumerateModules,Microsoft.PowerShell.Commands.GetProcessCommand" } + It "Should not fail to stop Get-Process with -Module when piped to Select-Object" { + Get-Process -Module -Id $PID -ErrorVariable errs | Select-Object -First 1 + $errs | Should -HaveCount 0 + } + It "Should fail to run Get-Process with -FileVersionInfo without admin" -Skip:(!$IsWindows) { { Get-Process -FileVersionInfo -ErrorAction Stop } | Should -Throw -ErrorId "CouldNotEnumerateFileVer,Microsoft.PowerShell.Commands.GetProcessCommand" } From e42343ba84e586af7a3b2d350d75edd7001ef100 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan <adityap@microsoft.com> Date: Thu, 12 Aug 2021 15:57:04 -0700 Subject: [PATCH 43/55] Update `README.md` and `metadata.json` for next releases (#15910) --- README.md | 56 ++++++++++++++++++++++----------------------- tools/metadata.json | 8 +++---- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 6a4bab807cf..d30953d7d5b 100644 --- a/README.md +++ b/README.md @@ -64,34 +64,34 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu | Windows (Arm) | [64-bit][rl-winarm64] (preview) | [64-bit][pv-winarm64] | [Instructions][in-arm] | | Raspbian (Arm) | [32-bit][rl-arm32]/[64-bit][rl-arm64] | [32-bit][pv-arm32]/[64-bit][pv-arm64] | [Instructions][in-raspbian] | -[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/PowerShell-7.0.6-win-x86.msi -[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/PowerShell-7.0.6-win-x64.msi -[lts-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/powershell-lts_7.0.6-1.ubuntu.18.04_amd64.deb -[lts-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/powershell-lts_7.0.6-1.ubuntu.16.04_amd64.deb -[lts-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/powershell-lts_7.0.6-1.debian.9_amd64.deb -[lts-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/powershell-lts_7.0.6-1.debian.10_amd64.deb -[lts-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/powershell-lts-7.0.6-1.rhel.7.x86_64.rpm -[lts-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/powershell-lts-7.0.6-1.centos.8.x86_64.rpm -[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/powershell-lts-7.0.6-osx-x64.pkg - -[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/PowerShell-7.1.3-win-x64.msi -[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/PowerShell-7.1.3-win-x86.msi -[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell_7.1.3-1.ubuntu.20.04_amd64.deb -[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell_7.1.3-1.ubuntu.18.04_amd64.deb -[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell_7.1.3-1.ubuntu.16.04_amd64.deb -[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell_7.1.3-1.debian.9_amd64.deb -[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell_7.1.3-1.debian.10_amd64.deb -[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell_7.1.3-1.debian.11_amd64.deb -[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell-7.1.3-1.rhel.7.x86_64.rpm -[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell-7.1.3-1.centos.8.x86_64.rpm -[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell-7.1.3-osx-x64.pkg -[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/PowerShell-7.1.3-win-arm64.zip -[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/PowerShell-7.1.3-win-x86.zip -[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/PowerShell-7.1.3-win-x64.zip -[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell-7.1.3-osx-x64.tar.gz -[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell-7.1.3-linux-x64.tar.gz -[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell-7.1.3-linux-arm32.tar.gz -[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell-7.1.3-linux-arm64.tar.gz +[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.7/PowerShell-7.0.7-win-x86.msi +[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.7/PowerShell-7.0.7-win-x64.msi +[lts-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.7/powershell-lts_7.0.7-1.ubuntu.18.04_amd64.deb +[lts-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.7/powershell-lts_7.0.7-1.ubuntu.16.04_amd64.deb +[lts-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.7/powershell-lts_7.0.7-1.debian.9_amd64.deb +[lts-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.7/powershell-lts_7.0.7-1.debian.10_amd64.deb +[lts-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.7/powershell-lts-7.0.7-1.rhel.7.x86_64.rpm +[lts-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.7/powershell-lts-7.0.7-1.centos.8.x86_64.rpm +[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.7/powershell-lts-7.0.7-osx-x64.pkg + +[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/PowerShell-7.1.4-win-x64.msi +[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/PowerShell-7.1.4-win-x86.msi +[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/powershell_7.1.4-1.ubuntu.20.04_amd64.deb +[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/powershell_7.1.4-1.ubuntu.18.04_amd64.deb +[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/powershell_7.1.4-1.ubuntu.16.04_amd64.deb +[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/powershell_7.1.4-1.debian.9_amd64.deb +[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/powershell_7.1.4-1.debian.10_amd64.deb +[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/powershell_7.1.4-1.debian.11_amd64.deb +[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/powershell-7.1.4-1.rhel.7.x86_64.rpm +[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/powershell-7.1.4-1.centos.8.x86_64.rpm +[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/powershell-7.1.4-osx-x64.pkg +[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/PowerShell-7.1.4-win-arm64.zip +[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/PowerShell-7.1.4-win-x86.zip +[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/PowerShell-7.1.4-win-x64.zip +[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/powershell-7.1.4-osx-x64.tar.gz +[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/powershell-7.1.4-linux-x64.tar.gz +[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/powershell-7.1.4-linux-arm32.tar.gz +[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/powershell-7.1.4-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell [pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.8/PowerShell-7.2.0-preview.8-win-x64.msi diff --git a/tools/metadata.json b/tools/metadata.json index e8e37b57379..0a2ce2ebffd 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,9 +1,9 @@ { - "StableReleaseTag": "v7.1.3", + "StableReleaseTag": "v7.1.4", "PreviewReleaseTag": "v7.2.0-preview.8", - "ServicingReleaseTag": "v7.0.6", - "ReleaseTag": "v7.1.3", - "LTSReleaseTag" : ["v7.0.6"], + "ServicingReleaseTag": "v7.0.7", + "ReleaseTag": "v7.1.4", + "LTSReleaseTag" : ["v7.0.7"], "NextReleaseTag": "v7.2.0-preview.9", "LTSRelease": false } From 1ec61d955c5f7e1e62a83d6a0d1dab3882bd73c9 Mon Sep 17 00:00:00 2001 From: Paul Higinbotham <paulhi@microsoft.com> Date: Thu, 12 Aug 2021 20:34:31 -0700 Subject: [PATCH 44/55] Remove implicit remoting batch experimental feature (#15863) It was decided by committee (#15862) to remove this experimental feature. It was an interesting idea but the implementation did not cover important cases, and could not be updated easily to do so. --- .../utility/ImplicitRemotingCommands.cs | 4 +- .../host/msh/Executor.cs | 16 - .../ExperimentalFeature.cs | 3 - .../engine/Modules/ModuleCmdletBase.cs | 22 - .../engine/Modules/ModuleIntrinsics.cs | 9 - .../engine/Utils.cs | 407 +----------------- .../resources/ParserStrings.resx | 21 - .../ImplicitRemotingBatching.Tests.ps1 | 168 -------- .../InvokeCommandRemoteDebug.Tests.ps1 | 2 +- .../HelpersRemoting/HelpersRemoting.psm1 | 4 +- 10 files changed, 5 insertions(+), 651 deletions(-) delete mode 100644 test/powershell/engine/Remoting/ImplicitRemotingBatching.Tests.ps1 diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index d772258227b..325632c44ce 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -2024,7 +2024,6 @@ private static void GenerateSectionSeparator(TextWriter writer) PrivateData = @{{ ImplicitRemoting = $true - ImplicitSessionId = '{4}' }} }} "; @@ -2043,8 +2042,7 @@ private void GenerateManifest(TextWriter writer, string psm1fileName, string for CodeGeneration.EscapeSingleQuotedStringContent(_moduleGuid.ToString()), CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.ProxyModuleDescription, this.GetConnectionString())), CodeGeneration.EscapeSingleQuotedStringContent(Path.GetFileName(psm1fileName)), - CodeGeneration.EscapeSingleQuotedStringContent(Path.GetFileName(formatPs1xmlFileName)), - _remoteRunspaceInfo.InstanceId); + CodeGeneration.EscapeSingleQuotedStringContent(Path.GetFileName(formatPs1xmlFileName))); } #endregion diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs index e6f597b94b8..25eca0d5fd6 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs @@ -321,22 +321,6 @@ internal Collection<PSObject> ExecuteCommand(string command, out Exception excep { Dbg.Assert(!string.IsNullOrEmpty(command), "command should have a value"); - // Experimental: - // Check for implicit remoting commands that can be batched, and execute as batched if able. - if (ExperimentalFeature.IsEnabled("PSImplicitRemotingBatching")) - { - var addOutputter = ((options & ExecutionOptions.AddOutputter) > 0); - if (addOutputter && - !_parent.RunspaceRef.IsRunspaceOverridden && - _parent.RunspaceRef.Runspace.ExecutionContext.Modules != null && - _parent.RunspaceRef.Runspace.ExecutionContext.Modules.IsImplicitRemotingModuleLoaded && - Utils.TryRunAsImplicitBatch(command, _parent.RunspaceRef.Runspace)) - { - exceptionThrown = null; - return null; - } - } - Pipeline tempPipeline = CreatePipeline(command, (options & ExecutionOptions.AddToHistory) > 0); return ExecuteCommandHelper(tempPipeline, out exceptionThrown, options); diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 2fbf9eb623e..9268003ee87 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -104,9 +104,6 @@ static ExperimentalFeature() name: "PSFileSystemProviderV2", description: "Replace the old FileSystemProvider with cleaner design and faster code"), */ - new ExperimentalFeature( - name: "PSImplicitRemotingBatching", - description: "Batch implicit remoting proxy commands to improve performance"), new ExperimentalFeature( name: "PSCommandNotFoundSuggestion", description: "Recommend potential commands based on fuzzy search on a CommandNotFoundException"), diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index d8ed2bc6537..90019e3bfed 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -5177,21 +5177,6 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC // And the appdomain level module path cache. PSModuleInfo.RemoveFromAppDomainLevelCache(module.Name); - - // Update implicit module loaded property - if (Context.Modules.IsImplicitRemotingModuleLoaded) - { - Context.Modules.IsImplicitRemotingModuleLoaded = false; - foreach (var modInfo in Context.Modules.ModuleTable.Values) - { - var privateData = modInfo.PrivateData as Hashtable; - if ((privateData != null) && privateData.ContainsKey("ImplicitRemoting")) - { - Context.Modules.IsImplicitRemotingModuleLoaded = true; - break; - } - } - } } } } @@ -6924,13 +6909,6 @@ internal static void AddModuleToModuleTables(ExecutionContext context, SessionSt { targetSessionState.Module.AddNestedModule(module); } - - var privateDataHashTable = module.PrivateData as Hashtable; - if (!context.Modules.IsImplicitRemotingModuleLoaded && - privateDataHashTable != null && privateDataHashTable.ContainsKey("ImplicitRemoting")) - { - context.Modules.IsImplicitRemotingModuleLoaded = true; - } } /// <summary> diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index d52374f9b63..1d8fe6bc8b5 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -54,15 +54,6 @@ internal ModuleIntrinsics(ExecutionContext context) private const int MaxModuleNestingDepth = 10; - /// <summary> - /// Gets and sets boolean that indicates when an implicit remoting module is loaded. - /// </summary> - internal bool IsImplicitRemotingModuleLoaded - { - get; - set; - } - internal void IncrementModuleNestingDepth(PSCmdlet cmdlet, string path) { if (++ModuleNestingDepth > MaxModuleNestingDepth) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 42b387cb6b9..8115ebbabcf 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -13,9 +13,7 @@ using System.Linq; using System.Management.Automation.Configuration; using System.Management.Automation.Internal; -using System.Management.Automation.Language; using System.Management.Automation.Remoting; -using System.Management.Automation.Runspaces; using System.Management.Automation.Security; using System.Numerics; using System.Reflection; @@ -1562,230 +1560,7 @@ internal static bool IsComObject(object obj) return oldMode; } - #region Implicit Remoting Batching - - // Commands allowed to run on target remote session along with implicit remote commands - private static readonly HashSet<string> AllowedCommands = new HashSet<string>(StringComparer.OrdinalIgnoreCase) - { - "ForEach-Object", - "Measure-Command", - "Measure-Object", - "Sort-Object", - "Where-Object" - }; - - // Determines if the typed command invokes implicit remoting module proxy functions in such - // a way as to allow simple batching, to reduce round trips between client and server sessions. - // Requirements: - // a. All commands must be implicit remoting module proxy commands targeted to the same remote session - // b. Except for *allowed* commands that can be safely run on remote session rather than client session - // c. Commands must be in a simple pipeline - internal static bool TryRunAsImplicitBatch(string command, Runspace runspace) - { - using (var ps = System.Management.Automation.PowerShell.Create()) - { - ps.Runspace = runspace; - - try - { - var scriptBlock = ScriptBlock.Create(command); - if (!(scriptBlock.Ast is ScriptBlockAst scriptBlockAst)) - { - return false; - } - - // Make sure that this is a simple pipeline - string errorId; - string errorMsg; - scriptBlockAst.GetSimplePipeline(true, out errorId, out errorMsg); - if (errorId != null) - { - WriteVerbose(ps, ParserStrings.ImplicitRemotingPipelineBatchingNotASimplePipeline); - return false; - } - - // Run checker - var checker = new PipelineForBatchingChecker { ScriptBeingConverted = scriptBlockAst }; - scriptBlockAst.InternalVisit(checker); - - // If this is just a single command, there is no point in batching it - if (checker.Commands.Count < 2) - { - return false; - } - - // We have a valid batching candidate - - // Check commands - if (!TryGetCommandInfoList(ps, checker.Commands, out Collection<CommandInfo> cmdInfoList)) - { - return false; - } - - // All command modules must be implicit remoting modules from the same PSSession - var success = true; - var psSessionId = Guid.Empty; - foreach (var cmdInfo in cmdInfoList) - { - // Check for allowed command - string cmdName = (cmdInfo is AliasInfo aliasInfo) ? aliasInfo.ReferencedCommand.Name : cmdInfo.Name; - if (AllowedCommands.Contains(cmdName)) - { - continue; - } - - // Commands must be from implicit remoting module - if (cmdInfo.Module == null || string.IsNullOrEmpty(cmdInfo.ModuleName)) - { - WriteVerbose(ps, string.Format(CultureInfo.CurrentCulture, ParserStrings.ImplicitRemotingPipelineBatchingNotImplicitCommand, cmdInfo.Name)); - success = false; - break; - } - - // Commands must be from modules imported into the same remote session - if (cmdInfo.Module.PrivateData is System.Collections.Hashtable privateData) - { - var sessionIdString = privateData["ImplicitSessionId"] as string; - if (string.IsNullOrEmpty(sessionIdString)) - { - WriteVerbose(ps, string.Format(CultureInfo.CurrentCulture, ParserStrings.ImplicitRemotingPipelineBatchingNotImplicitCommand, cmdInfo.Name)); - success = false; - break; - } - - var sessionId = new Guid(sessionIdString); - if (psSessionId == Guid.Empty) - { - psSessionId = sessionId; - } - else if (psSessionId != sessionId) - { - WriteVerbose(ps, string.Format(CultureInfo.CurrentCulture, ParserStrings.ImplicitRemotingPipelineBatchingWrongSession, cmdInfo.Name)); - success = false; - break; - } - } - else - { - WriteVerbose(ps, string.Format(CultureInfo.CurrentCulture, ParserStrings.ImplicitRemotingPipelineBatchingNotImplicitCommand, cmdInfo.Name)); - success = false; - break; - } - } - - if (success) - { - // - // Invoke command pipeline as entire pipeline on remote session - // - - // Update script to declare variables via Using keyword - if (checker.ValidVariables.Count > 0) - { - foreach (var variableName in checker.ValidVariables) - { - command = command.Replace(variableName, ("Using:" + variableName), StringComparison.OrdinalIgnoreCase); - } - - scriptBlock = ScriptBlock.Create(command); - } - - // Retrieve the PSSession runspace in which to run the batch script on - ps.Commands.Clear(); - ps.Commands.AddCommand("Get-PSSession").AddParameter("InstanceId", psSessionId); - var psSession = ps.Invoke<System.Management.Automation.Runspaces.PSSession>().FirstOrDefault(); - if (psSession == null || (ps.Streams.Error.Count > 0) || (psSession.Availability != RunspaceAvailability.Available)) - { - WriteVerbose(ps, ParserStrings.ImplicitRemotingPipelineBatchingNoPSSession); - return false; - } - - WriteVerbose(ps, ParserStrings.ImplicitRemotingPipelineBatchingSuccess); - - // Create and invoke implicit remoting command pipeline - ps.Commands.Clear(); - ps.AddCommand("Invoke-Command").AddParameter("Session", psSession).AddParameter("ScriptBlock", scriptBlock).AddParameter("HideComputerName", true) - .AddCommand("Out-Default"); - foreach (var cmd in ps.Commands.Commands) - { - cmd.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); - } - - try - { - ps.Invoke(); - } - catch (Exception ex) - { - var errorRecord = new ErrorRecord(ex, "ImplicitRemotingBatchExecutionTerminatingError", ErrorCategory.InvalidOperation, null); - - ps.Commands.Clear(); - ps.AddCommand("Write-Error").AddParameter("InputObject", errorRecord).Invoke(); - } - - return true; - } - } - catch (ImplicitRemotingBatchingNotSupportedException ex) - { - WriteVerbose(ps, string.Format(CultureInfo.CurrentCulture, "{0} : {1}", ex.Message, ex.ErrorId)); - } - catch (Exception ex) - { - WriteVerbose(ps, string.Format(CultureInfo.CurrentCulture, ParserStrings.ImplicitRemotingPipelineBatchingException, ex.Message)); - } - } - - return false; - } - - private static void WriteVerbose(PowerShell ps, string msg) - { - ps.Commands.Clear(); - ps.AddCommand("Write-Verbose").AddParameter("Message", msg).Invoke(); - } - - private const string WhereObjectCommandAlias = "?"; - - private static bool TryGetCommandInfoList(PowerShell ps, HashSet<string> commandNames, out Collection<CommandInfo> cmdInfoList) - { - if (commandNames.Count == 0) - { - cmdInfoList = null; - return false; - } - - bool specialCaseWhereCommandAlias = commandNames.Contains(WhereObjectCommandAlias); - if (specialCaseWhereCommandAlias) - { - commandNames.Remove(WhereObjectCommandAlias); - } - - // Use Get-Command to collect CommandInfo from candidate commands, with correct precedence so - // that implicit remoting proxy commands will appear when available. - ps.Commands.Clear(); - ps.Commands.AddCommand("Get-Command").AddParameter("Name", commandNames.ToArray()); - cmdInfoList = ps.Invoke<CommandInfo>(); - if (ps.Streams.Error.Count > 0) - { - return false; - } - - // For special case '?' alias don't use Get-Command to retrieve command info, and instead - // use the GetCommand API. - if (specialCaseWhereCommandAlias) - { - var cmdInfo = ps.Runspace.ExecutionContext.SessionState.InvokeCommand.GetCommand(WhereObjectCommandAlias, CommandTypes.Alias); - if (cmdInfo == null) - { - return false; - } - - cmdInfoList.Add(cmdInfo); - } - - return true; - } + #region PSAnsiRendering internal static bool ShouldOutputPlainText(bool isHost, bool? supportsVirtualTerminal) { @@ -1882,173 +1657,6 @@ internal static string GetFormatStyleString(FormatStyle formatStyle) #endregion } - - #region ImplicitRemotingBatching - - // A visitor to walk an AST and validate that it is a candidate for implicit remoting batching. - // Based on ScriptBlockToPowerShellChecker. - internal class PipelineForBatchingChecker : AstVisitor - { - internal readonly HashSet<string> ValidVariables = new HashSet<string>(StringComparer.OrdinalIgnoreCase); - internal readonly HashSet<string> Commands = new HashSet<string>(StringComparer.OrdinalIgnoreCase); - - internal ScriptBlockAst ScriptBeingConverted { get; set; } - - public override AstVisitAction VisitVariableExpression(VariableExpressionAst variableExpressionAst) - { - if (!variableExpressionAst.VariablePath.IsAnyLocal()) - { - ThrowError( - new ImplicitRemotingBatchingNotSupportedException( - "VariableTypeNotSupported"), - variableExpressionAst); - } - - if (variableExpressionAst.VariablePath.UnqualifiedPath != "_") - { - ValidVariables.Add(variableExpressionAst.VariablePath.UnqualifiedPath); - } - - return AstVisitAction.Continue; - } - - public override AstVisitAction VisitPipeline(PipelineAst pipelineAst) - { - if (pipelineAst.PipelineElements[0] is CommandExpressionAst) - { - // If the first element is a CommandExpression, this pipeline should be the value - // of a parameter. We want to avoid a scriptblock that contains only a pure expression. - // The check "pipelineAst.Parent.Parent == ScriptBeingConverted" guarantees we throw - // error on that kind of scriptblock. - - // Disallow pure expressions at the "top" level, but allow them otherwise. - // We want to catch: - // 1 | echo - // But we don't want to error out on: - // echo $(1) - // See the comment in VisitCommand on why it's safe to check Parent.Parent, we - // know that we have at least: - // * a NamedBlockAst (the end block) - // * a ScriptBlockAst (the ast we're comparing to) - if (pipelineAst.GetPureExpression() == null || pipelineAst.Parent.Parent == ScriptBeingConverted) - { - ThrowError( - new ImplicitRemotingBatchingNotSupportedException( - "PipelineStartingWithExpressionNotSupported"), - pipelineAst); - } - } - - return AstVisitAction.Continue; - } - - public override AstVisitAction VisitCommand(CommandAst commandAst) - { - if (commandAst.InvocationOperator == TokenKind.Dot) - { - ThrowError( - new ImplicitRemotingBatchingNotSupportedException( - "DotSourcingNotSupported"), - commandAst); - } - - /* - // Up front checking ensures that we have a simple script block, - // so we can safely assume that the parents are: - // * a PipelineAst - // * a NamedBlockAst (the end block) - // * a ScriptBlockAst (the ast we're comparing to) - // If that isn't the case, the conversion isn't allowed. It - // is also safe to assume that we have at least 3 parents, a script block can't be simpler. - if (commandAst.Parent.Parent.Parent != ScriptBeingConverted) - { - ThrowError( - new ImplicitRemotingBatchingNotSupportedException( - "CantConvertWithCommandInvocations not supported"), - commandAst); - } - */ - - if (commandAst.CommandElements[0] is ScriptBlockExpressionAst) - { - ThrowError( - new ImplicitRemotingBatchingNotSupportedException( - "ScriptBlockInvocationNotSupported"), - commandAst); - } - - var commandName = commandAst.GetCommandName(); - if (commandName != null) - { - Commands.Add(commandName); - } - - return AstVisitAction.Continue; - } - - public override AstVisitAction VisitMergingRedirection(MergingRedirectionAst redirectionAst) - { - if (redirectionAst.ToStream != RedirectionStream.Output) - { - ThrowError( - new ImplicitRemotingBatchingNotSupportedException( - "MergeRedirectionNotSupported"), - redirectionAst); - } - - return AstVisitAction.Continue; - } - - public override AstVisitAction VisitFileRedirection(FileRedirectionAst redirectionAst) - { - ThrowError( - new ImplicitRemotingBatchingNotSupportedException( - "FileRedirectionNotSupported"), - redirectionAst); - - return AstVisitAction.Continue; - } - - /* - public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) - { - ThrowError(new ImplicitRemotingBatchingNotSupportedException( - "ScriptBlocks not supported"), - scriptBlockExpressionAst); - - return AstVisitAction.SkipChildren; - } - */ - - public override AstVisitAction VisitUsingExpression(UsingExpressionAst usingExpressionAst) - { - // Using expressions are not expected in Implicit remoting commands. - ThrowError(new ImplicitRemotingBatchingNotSupportedException( - "UsingExpressionNotSupported"), - usingExpressionAst); - - return AstVisitAction.SkipChildren; - } - - internal static void ThrowError(ImplicitRemotingBatchingNotSupportedException ex, Ast ast) - { - InterpreterError.UpdateExceptionErrorRecordPosition(ex, ast.Extent); - throw ex; - } - } - - internal class ImplicitRemotingBatchingNotSupportedException : Exception - { - internal string ErrorId { get; } - - internal ImplicitRemotingBatchingNotSupportedException(string errorId) : base( - ParserStrings.ImplicitRemotingPipelineBatchingNotSupported) - { - ErrorId = errorId; - } - } - - #endregion } namespace System.Management.Automation.Internal @@ -2111,19 +1719,6 @@ public static void SetTestHook(string property, object value) } } - /// <summary> - /// Test hook used to test implicit remoting batching. A local runspace must be provided that has imported a - /// remote session, i.e., has run the Import-PSSession cmdlet. This hook will return true if the provided commandPipeline - /// is successfully batched and run in the remote session, and false if it is rejected for batching. - /// </summary> - /// <param name="commandPipeline">Command pipeline to test.</param> - /// <param name="runspace">Runspace with imported remote session.</param> - /// <returns>True if commandPipeline is batched successfully.</returns> - public static bool TestImplicitRemotingBatching(string commandPipeline, System.Management.Automation.Runspaces.Runspace runspace) - { - return Utils.TryRunAsImplicitBatch(commandPipeline, runspace); - } - /// <summary> /// Constructs a custom PSSenderInfo instance that can be assigned to $PSSenderInfo /// in order to simulate a remoting session with respect to the $PSSenderInfo.ConnectionString (connection URL) diff --git a/src/System.Management.Automation/resources/ParserStrings.resx b/src/System.Management.Automation/resources/ParserStrings.resx index dd9ce1b8c55..d21719157ac 100644 --- a/src/System.Management.Automation/resources/ParserStrings.resx +++ b/src/System.Management.Automation/resources/ParserStrings.resx @@ -1461,27 +1461,6 @@ ModuleVersion : Version of module to import. If used, ModuleName must represent <data name="ParserError" xml:space="preserve"> <value>{0}</value> </data> - <data name="ImplicitRemotingPipelineBatchingNotSupported" xml:space="preserve"> - <value>Command pipeline not supported for implicit remoting batching.</value> - </data> - <data name="ImplicitRemotingPipelineBatchingNotASimplePipeline" xml:space="preserve"> - <value>Command is not a simple pipeline and cannot be batched.</value> - </data> - <data name="ImplicitRemotingPipelineBatchingNotImplicitCommand" xml:space="preserve"> - <value>The pipeline command '{0}' is not an implicit remoting command or an approved batching command.</value> - </data> - <data name="ImplicitRemotingPipelineBatchingWrongSession" xml:space="preserve"> - <value>The pipeline command '{0}' is for a different remote session and cannot be batched.</value> - </data> - <data name="ImplicitRemotingPipelineBatchingNoPSSession" xml:space="preserve"> - <value>The implicit remoting PSSession for batching could not be retrieved.</value> - </data> - <data name="ImplicitRemotingPipelineBatchingException" xml:space="preserve"> - <value>Exception while checking the command for implicit remoting batching: {0}</value> - </data> - <data name="ImplicitRemotingPipelineBatchingSuccess" xml:space="preserve"> - <value>Implicit remoting command pipeline has been batched for execution on remote target.</value> - </data> <data name="ScriptHasAdminBlockedContent" xml:space="preserve"> <value>This script contains content that has been flagged as suspicious through a policy setting and has been blocked with error code {0}. Contact your administrator for more information.</value> </data> diff --git a/test/powershell/engine/Remoting/ImplicitRemotingBatching.Tests.ps1 b/test/powershell/engine/Remoting/ImplicitRemotingBatching.Tests.ps1 deleted file mode 100644 index 62c72790622..00000000000 --- a/test/powershell/engine/Remoting/ImplicitRemotingBatching.Tests.ps1 +++ /dev/null @@ -1,168 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -Describe "TestImplicitRemotingBatching hook should correctly batch simple remote command pipelines" -Tag 'Feature','RequireAdminOnWindows' { - - BeforeAll { - - if (! $IsWindows) { return } - - function ThrowSetupError - { - param ( - [string] $errorMessage, - [System.Management.Automation.ErrorRecord[]] $eRecords - ) - - $msg = @() - foreach ($err in $powerShell.Streams.Error) - { - $msg += $err.ToString() + "`n" - } - - throw "$errorMessage : '$msg'" - } - - # Make sure we can create a remote session - $remotePSSession = New-RemoteSession - if ($remotePSSession -eq $null) - { - Write-Verbose "Unable to create a remote session in test." - } - else - { - Remove-PSSession $remotePSSession - } - - [powershell] $powerShell = [powershell]::Create([System.Management.Automation.RunspaceMode]::NewRunspace) - - # Create remote session in new PowerShell session - $powerShell.AddScript('Import-Module -Name HelpersRemoting; $remoteSession = New-RemoteSession').Invoke() - if ($powerShell.Streams.Error.Count -gt 0) - { - ThrowSetupError -errorMessage "Unable to create remote session for test with error" -eRecords $powerShell.Streams.Error - } - - # Import implicit commands from remote session - $powerShell.Commands.Clear() - $powerShell.AddScript('Import-PSSession -Session $remoteSession -CommandName Get-Process,Write-Output -AllowClobber').Invoke() - if ($powerShell.Streams.Error.Count -gt 0) - { - ThrowSetupError -errorMessage "Unable to import pssession for test" -eRecords $powerShell.Streams.Error - } - - # Define $filter variable in local session - $powerShell.Commands.Clear() - $powerShell.AddScript('$filter = "pwsh","powershell"').Invoke() - $localRunspace = $powerShell.Runspace - - [powershell] $psInvoke = [powershell]::Create([System.Management.Automation.RunspaceMode]::NewRunspace) - - $testCases = @( - @{ - Name = 'Two implicit commands should be successfully batched' - CommandLine = 'Get-Process -Name "pwsh" | Write-Output' - ExpectedOutput = $true - }, - @{ - Name = 'Two implicit commands with Where-Object should be successfully batched' - CommandLine = 'Get-Process | Write-Output | Where-Object { $_.Name -like "*pwsh*" }' - ExpectedOutput = $true - }, - @{ - Name = 'Two implicit commands with Where-Object alias (?) should be successfully batched' - CommandLine = 'Get-Process | Write-Output | ? { $_.Name -like "*pwsh*" }' - ExpectedOutput = $true - }, - @{ - Name = 'Two implicit commands with Where-Object alias (where) should be successfully batched' - CommandLine = 'Get-Process | Write-Output | where { $_.Name -like "*pwsh*" }' - ExpectedOutput = $true - }, - @{ - Name = 'Two implicit commands with Sort-Object should be successfully batched' - CommandLine = 'Get-Process -Name "pwsh" | Sort-Object -Property Name | Write-Output' - ExpectedOutput = $true - }, - @{ - Name = 'Two implicit commands with Sort-Object alias (sort) should be successfully batched' - CommandLine = 'Get-Process -Name "pwsh" | sort -Property Name | Write-Output' - ExpectedOutput = $true - }, - @{ - Name = 'Two implicit commands with ForEach-Object should be successfully batched' - CommandLine = 'Get-Process -Name "pwsh" | Write-Output | ForEach-Object { $_ }' - ExpectedOutput = $true - }, - @{ - Name = 'Two implicit commands with ForEach-Object alias (%) should be successfully batched' - CommandLine = 'Get-Process -Name "pwsh" | Write-Output | % { $_ }' - ExpectedOutput = $true - }, - @{ - Name = 'Two implicit commands with ForEach-Object alias (foreach) should be successfully batched' - CommandLine = 'Get-Process -Name "pwsh" | Write-Output | foreach { $_ }' - ExpectedOutput = $true - }, - @{ - Name = 'Two implicit commands with Measure-Command should be successfully batched' - CommandLine = 'Measure-Command { Get-Process | Write-Output }' - ExpectedOutput = $true - }, - @{ - Name = 'Two implicit commands with Measure-Object should be successfully batched' - CommandLine = 'Get-Process | Write-Output | Measure-Object' - ExpectedOutput = $true - }, - @{ - Name = 'Two implicit commands with Measure-Object alias (measure) should be successfully batched' - CommandLine = 'Get-Process | Write-Output | measure' - ExpectedOutput = $true - }, - @{ - Name = 'Implicit commands with variable arguments should be successfully batched' - CommandLine = 'Get-Process -Name $filter | Write-Output' - ExpectedOutput = $true - }, - @{ - Name = 'Pipeline with non-implicit command should not be batched' - CommandLine = 'Get-Process | Write-Output | Select-Object -Property Name' - ExpectedOutput = $false - }, - @{ - Name = 'Non-simple pipeline should not be batched' - CommandLine = '1..2 | % { Get-Process pwsh | Write-Output }' - ExpectedOutput = $false - } - @{ - Name = 'Pipeline with single command should not be batched' - CommandLine = 'Get-Process pwsh' - ExpectedOutput = $false - }, - @{ - Name = 'Pipeline without any implicit commands should not be batched' - CommandLine = 'Get-PSSession | Out-Default' - ExpectedOutput = $false - } - ) - } - - AfterAll { - - if (! $IsWindows) { return } - - if ($remoteSession -ne $null) { Remove-PSSession $remoteSession -ErrorAction Ignore } - if ($powershell -ne $null) { $powershell.Dispose() } - if ($psInvoke -ne $null) { $psInvoke.Dispose() } - } - - It "<Name>" -TestCases $testCases -Skip:(! $IsWindows) { - param ($CommandLine, $ExpectedOutput) - - $psInvoke.Commands.Clear() - $psInvoke.Commands.AddScript('param ($cmdLine, $runspace) [System.Management.Automation.Internal.InternalTestHooks]::TestImplicitRemotingBatching($cmdLine, $runspace)').AddArgument($CommandLine).AddArgument($localRunspace) - - $result = $psInvoke.Invoke() - $result | Should -Be $ExpectedOutput - } -} diff --git a/test/powershell/engine/Remoting/InvokeCommandRemoteDebug.Tests.ps1 b/test/powershell/engine/Remoting/InvokeCommandRemoteDebug.Tests.ps1 index 7829aa38770..fef7da0e75e 100644 --- a/test/powershell/engine/Remoting/InvokeCommandRemoteDebug.Tests.ps1 +++ b/test/powershell/engine/Remoting/InvokeCommandRemoteDebug.Tests.ps1 @@ -174,7 +174,7 @@ Describe "Invoke-Command remote debugging tests" -Tags 'Feature','RequireAdminOn $ps.Commands.Clear() $ps2.Commands.Clear() - Remove-PSSession $remoteSession -ErrorAction SilentlyContinue + if ($null -ne $remoteSession) { Remove-PSSession $remoteSession -ErrorAction SilentlyContinue } $remoteSession = $null } diff --git a/test/tools/Modules/HelpersRemoting/HelpersRemoting.psm1 b/test/tools/Modules/HelpersRemoting/HelpersRemoting.psm1 index 96461bd5fb0..b5544364260 100644 --- a/test/tools/Modules/HelpersRemoting/HelpersRemoting.psm1 +++ b/test/tools/Modules/HelpersRemoting/HelpersRemoting.psm1 @@ -18,7 +18,7 @@ function Get-DefaultEndPointName if ($endPoint -eq $null) { - Enable-PSRemoting -SkipNetworkProfileCheck + $null = Enable-PSRemoting -SkipNetworkProfileCheck $endPoint = Get-PSSessionConfiguration -Name $endPointName -ErrorAction SilentlyContinue if ($endPoint -eq $null) @@ -30,7 +30,7 @@ function Get-DefaultEndPointName if ($endPoint.Permission -like "*NT AUTHORITY\NETWORK AccessDenied*") { - Enable-PSRemoting -SkipNetworkProfileCheck + $null = Enable-PSRemoting -SkipNetworkProfileCheck $endPoint = Get-PSSessionConfiguration -Name $endPointName -ErrorAction SilentlyContinue if ($endPoint.Permission -like "*NT AUTHORITY\NETWORK AccessDenied*") From dda6c156d2d7037ff819f413d53323d5c3e45448 Mon Sep 17 00:00:00 2001 From: Steve Lee <slee@microsoft.com> Date: Fri, 13 Aug 2021 15:40:07 -0700 Subject: [PATCH 45/55] Fix `$PSStyle` list output to correctly show `TableHeader` (#15928) --- .../DefaultFormatters/PowerShellCore_format_ps1xml.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index 2d9cab7b0c2..4e359c3acf9 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -2067,7 +2067,7 @@ private static IEnumerable<FormatViewDefinition> ViewsOf_System_Management_Autom .AddItemScriptBlock(@"""$($_.Strikethrough)$($_.Strikethrough.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Strikethrough") .AddItemProperty(@"OutputRendering") .AddItemScriptBlock(@"""$($_.Formatting.FormatAccent)$($_.Formatting.FormatAccent.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.FormatAccent") - .AddItemScriptBlock(@"""$($_.Formatting.TableHeaader)$($_.Formatting.TableHeaader.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.TableHeaader") + .AddItemScriptBlock(@"""$($_.Formatting.TableHeader)$($_.Formatting.TableHeader.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.TableHeader") .AddItemScriptBlock(@"""$($_.Formatting.ErrorAccent)$($_.Formatting.ErrorAccent.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.ErrorAccent") .AddItemScriptBlock(@"""$($_.Formatting.Error)$($_.Formatting.Error.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Error") .AddItemScriptBlock(@"""$($_.Formatting.Warning)$($_.Formatting.Warning.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Warning") From 05e64135d2a70b84499890224887ace9ffd391e0 Mon Sep 17 00:00:00 2001 From: Dongbo Wang <dongbow@microsoft.com> Date: Sat, 14 Aug 2021 07:32:51 -0700 Subject: [PATCH 46/55] Don't use `ArgumentList` when creating COM object as it's not applicable to the COM parameter set (#15915) --- .../commands/utility/New-Object.cs | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs index 0ca9ad7b90e..370f4574b5c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs @@ -238,7 +238,7 @@ protected override void BeginProcessing() WriteObject(_newObject); return; } - else if (type.GetTypeInfo().IsValueType) + else if (type.IsValueType) { // This is for default parameterless struct ctor which is not returned by // Type.GetConstructor(System.Type.EmptyTypes). @@ -351,12 +351,12 @@ protected override void BeginProcessing() #if !UNIX #region Com - private object SafeCreateInstance(Type t, object[] args) + private object SafeCreateInstance(Type t) { object result = null; try { - result = Activator.CreateInstance(t, args); + result = Activator.CreateInstance(t); } // Does not catch InvalidComObjectException because ComObject is obtained from GetTypeFromProgID catch (ArgumentException e) @@ -430,13 +430,10 @@ private void STAComCreateThreadProc(object createstruct) ComCreateInfo info = (ComCreateInfo)createstruct; try { - Type type = null; - PSArgumentException mshArgE = null; - - type = Type.GetTypeFromCLSID(_comObjectClsId); + Type type = Type.GetTypeFromCLSID(_comObjectClsId); if (type == null) { - mshArgE = PSTraceSource.NewArgumentException( + PSArgumentException mshArgE = PSTraceSource.NewArgumentException( "ComObject", NewObjectStrings.CannotLoadComObjectType, ComObject); @@ -446,7 +443,7 @@ private void STAComCreateThreadProc(object createstruct) return; } - info.objectCreated = SafeCreateInstance(type, ArgumentList); + info.objectCreated = SafeCreateInstance(type); info.success = true; } catch (Exception e) @@ -458,20 +455,25 @@ private void STAComCreateThreadProc(object createstruct) private object CreateComObject() { - Type type = null; - PSArgumentException mshArgE = null; - try { - type = Marshal.GetTypeFromCLSID(_comObjectClsId); + Type type = Marshal.GetTypeFromCLSID(_comObjectClsId); if (type == null) { - mshArgE = PSTraceSource.NewArgumentException("ComObject", NewObjectStrings.CannotLoadComObjectType, ComObject); + PSArgumentException mshArgE = PSTraceSource.NewArgumentException( + "ComObject", + NewObjectStrings.CannotLoadComObjectType, + ComObject); + ThrowTerminatingError( - new ErrorRecord(mshArgE, "CannotLoadComObjectType", ErrorCategory.InvalidType, null)); + new ErrorRecord( + mshArgE, + "CannotLoadComObjectType", + ErrorCategory.InvalidType, + targetObject: null)); } - return SafeCreateInstance(type, ArgumentList); + return SafeCreateInstance(type); } catch (COMException e) { From 286f12a37c710006f75a2e6df70b5bfc3289fe39 Mon Sep 17 00:00:00 2001 From: Dongbo Wang <dongbow@microsoft.com> Date: Sat, 14 Aug 2021 07:56:14 -0700 Subject: [PATCH 47/55] Update .NET adapter to handle interface static members properly (#15908) --- .../engine/CoreAdapter.cs | 282 +++++++----------- .../engine/LanguagePrimitives.cs | 9 - .../engine/runtime/Binding/Binders.cs | 14 +- .../Language/Scripting/Adapter.Tests.ps1 | 110 +++++++ 4 files changed, 212 insertions(+), 203 deletions(-) create mode 100644 test/powershell/Language/Scripting/Adapter.Tests.ps1 diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index bf9775b35ef..1a623e92f1e 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -2616,7 +2616,7 @@ internal class MethodCacheEntry : CacheEntry /// </summary> internal Func<string, DotNetAdapter, object, DotNetAdapter.MethodCacheEntry, bool, bool, PSMethod> PSMethodCtor; - internal MethodCacheEntry(MethodBase[] methods) + internal MethodCacheEntry(IList<MethodBase> methods) { methodInformationStructures = DotNetAdapter.GetMethodInformationArray(methods); } @@ -3075,9 +3075,8 @@ private static void AddOverload(List<MethodBase> previousMethodEntry, MethodInfo private static void PopulateMethodReflectionTable(Type type, MethodInfo[] methods, CacheTable typeMethods) { - for (int i = 0; i < methods.Length; i++) + foreach (MethodInfo method in methods) { - MethodInfo method = methods[i]; if (method.DeclaringType == type) { string methodName = method.Name; @@ -3102,7 +3101,7 @@ private static void PopulateMethodReflectionTable(Type type, MethodInfo[] method private static void PopulateMethodReflectionTable(ConstructorInfo[] ctors, CacheTable typeMethods) { - foreach (var ctor in ctors) + foreach (ConstructorInfo ctor in ctors) { var previousMethodEntry = (List<MethodBase>)typeMethods["new"]; if (previousMethodEntry == null) @@ -3127,26 +3126,14 @@ private static void PopulateMethodReflectionTable(ConstructorInfo[] ctors, Cache /// <param name="bindingFlags">BindingFlags to use.</param> private static void PopulateMethodReflectionTable(Type type, CacheTable typeMethods, BindingFlags bindingFlags) { - Type typeToGetMethod = type; + bool isStatic = bindingFlags.HasFlag(BindingFlags.Static); - // Assemblies in CoreCLR might not allow reflection execution on their internal types. In such case, we walk up - // the derivation chain to find the first public parent, and use reflection methods on the public parent. - if (!TypeResolver.IsPublic(type) && DisallowPrivateReflection(type)) - { - typeToGetMethod = GetFirstPublicParentType(type); - } - - // In CoreCLR, "GetFirstPublicParentType" may return null if 'type' is an interface - if (typeToGetMethod != null) - { - MethodInfo[] methods = typeToGetMethod.GetMethods(bindingFlags); - PopulateMethodReflectionTable(typeToGetMethod, methods, typeMethods); - } + MethodInfo[] methods = type.GetMethods(bindingFlags); + PopulateMethodReflectionTable(type, methods, typeMethods); Type[] interfaces = type.GetInterfaces(); - for (int interfaceIndex = 0; interfaceIndex < interfaces.Length; interfaceIndex++) + foreach (Type interfaceType in interfaces) { - var interfaceType = interfaces[interfaceIndex]; if (!TypeResolver.IsPublic(interfaceType)) { continue; @@ -3154,41 +3141,50 @@ private static void PopulateMethodReflectionTable(Type type, CacheTable typeMeth if (interfaceType.IsGenericType && type.IsArray) { - continue; // GetInterfaceMap is not supported in this scenario... not sure if we need to do something special here... + // A bit of background: Array doesn't directly support any generic interface at all. Instead, a stub class + // named 'SZArrayHelper' provides these generic interfaces at runtime for zero-based one-dimension arrays. + // This is why '[object[]].GetInterfaceMap([ICollection[object]])' throws 'ArgumentException'. + // (see https://stackoverflow.com/a/31883327) + // + // We had always been skipping generic interfaces for array types because 'GetInterfaceMap' doesn't work + // for it. Today, even though we don't use 'GetInterfaceMap' anymore, the same code is kept here because + // methods from generic interfaces of an array type could cause ambiguity in method overloads resolution. + // For example, "$objs = @(1,2,3,4); $objs.Contains(1)" would fail because there would be 2 overloads of + // the 'Contains' methods which are equally good matches for the call. + // bool IList.Contains(System.Object value) + // bool ICollection[Object].Contains(System.Object item) + continue; } - MethodInfo[] methods; - if (type.IsInterface) - { - methods = interfaceType.GetMethods(bindingFlags); - } - else - { - InterfaceMapping interfaceMapping = type.GetInterfaceMap(interfaceType); - methods = interfaceMapping.InterfaceMethods; - } + methods = interfaceType.GetMethods(bindingFlags); - for (int methodIndex = 0; methodIndex < methods.Length; methodIndex++) + foreach (MethodInfo interfaceMethod in methods) { - MethodInfo interfaceMethodDefinition = methods[methodIndex]; - - if ((!interfaceMethodDefinition.IsPublic) || - (interfaceMethodDefinition.IsStatic != ((BindingFlags.Static & bindingFlags) != 0))) + if (isStatic && interfaceMethod.IsVirtual) { + // Ignore static virtual/abstract methods on an interface because: + // 1. if it's implicitly implemented, which will be mostly the case, then the corresponding + // methods were already retrieved from the 'type.GetMethods' step above; + // 2. if it's explicitly implemented, we cannot call 'Invoke(null, args)' on the static method, + // but have to use 'type.GetInterfaceMap(interfaceType)' to get the corresponding target + // methods, and call 'Invoke(null, args)' on them. The target methods will be non-public + // in this case, which we always ignore. + // 3. The recommendation from .NET team is to ignore the static virtuals on interfaces, + // especially given that the APIs may change in .NET 7. continue; } - var previousMethodEntry = (List<MethodBase>)typeMethods[interfaceMethodDefinition.Name]; + var previousMethodEntry = (List<MethodBase>)typeMethods[interfaceMethod.Name]; if (previousMethodEntry == null) { - var methodEntry = new List<MethodBase> { interfaceMethodDefinition }; - typeMethods.Add(interfaceMethodDefinition.Name, methodEntry); + var methodEntry = new List<MethodBase> { interfaceMethod }; + typeMethods.Add(interfaceMethod.Name, methodEntry); } else { - if (!previousMethodEntry.Contains(interfaceMethodDefinition)) + if (!previousMethodEntry.Contains(interfaceMethod)) { - previousMethodEntry.Add(interfaceMethodDefinition); + previousMethodEntry.Add(interfaceMethod); } } } @@ -3211,7 +3207,7 @@ private static void PopulateMethodReflectionTable(Type type, CacheTable typeMeth for (int i = 0; i < typeMethods.memberCollection.Count; i++) { typeMethods.memberCollection[i] = - new MethodCacheEntry(((List<MethodBase>)typeMethods.memberCollection[i]).ToArray()); + new MethodCacheEntry((List<MethodBase>)typeMethods.memberCollection[i]); } } @@ -3224,38 +3220,24 @@ private static void PopulateMethodReflectionTable(Type type, CacheTable typeMeth /// <param name="bindingFlags">BindingFlags to use.</param> private static void PopulateEventReflectionTable(Type type, Dictionary<string, EventCacheEntry> typeEvents, BindingFlags bindingFlags) { - // Assemblies in CoreCLR might not allow reflection execution on their internal types. In such case, we walk up - // the derivation chain to find the first public parent, and use reflection events on the public parent. - if (!TypeResolver.IsPublic(type) && DisallowPrivateReflection(type)) - { - type = GetFirstPublicParentType(type); - } + EventInfo[] events = type.GetEvents(bindingFlags); + var tempTable = new Dictionary<string, List<EventInfo>>(StringComparer.OrdinalIgnoreCase); - // In CoreCLR, "GetFirstPublicParentType" may return null if 'type' is an interface - if (type != null) + foreach (EventInfo typeEvent in events) { - EventInfo[] events = type.GetEvents(bindingFlags); - var tempTable = new Dictionary<string, List<EventInfo>>(StringComparer.OrdinalIgnoreCase); - for (int i = 0; i < events.Length; i++) + string eventName = typeEvent.Name; + if (!tempTable.TryGetValue(eventName, out List<EventInfo> entryList)) { - var typeEvent = events[i]; - string eventName = typeEvent.Name; - List<EventInfo> previousEntry; - if (!tempTable.TryGetValue(eventName, out previousEntry)) - { - var eventEntry = new List<EventInfo> { typeEvent }; - tempTable.Add(eventName, eventEntry); - } - else - { - previousEntry.Add(typeEvent); - } + entryList = new List<EventInfo>(); + tempTable.Add(eventName, entryList); } - foreach (var entry in tempTable) - { - typeEvents.Add(entry.Key, new EventCacheEntry(entry.Value.ToArray())); - } + entryList.Add(typeEvent); + } + + foreach (KeyValuePair<string, List<EventInfo>> entry in tempTable) + { + typeEvents.Add(entry.Key, new EventCacheEntry(entry.Value.ToArray())); } } @@ -3270,9 +3252,8 @@ private static bool PropertyAlreadyPresent(List<PropertyInfo> previousProperties ParameterInfo[] propertyParameters = property.GetIndexParameters(); int propertyIndexLength = propertyParameters.Length; - for (int propertyIndex = 0; propertyIndex < previousProperties.Count; propertyIndex++) + foreach (PropertyInfo previousProperty in previousProperties) { - var previousProperty = previousProperties[propertyIndex]; ParameterInfo[] previousParameters = previousProperty.GetIndexParameters(); if (previousParameters.Length == propertyIndexLength) { @@ -3308,79 +3289,81 @@ private static bool PropertyAlreadyPresent(List<PropertyInfo> previousProperties /// <param name="bindingFlags">BindingFlags to use.</param> private static void PopulatePropertyReflectionTable(Type type, CacheTable typeProperties, BindingFlags bindingFlags) { + bool isStatic = bindingFlags.HasFlag(BindingFlags.Static); var tempTable = new Dictionary<string, List<PropertyInfo>>(StringComparer.OrdinalIgnoreCase); - Type typeToGetPropertyAndField = type; - // Assemblies in CoreCLR might not allow reflection execution on their internal types. In such case, we walk up the - // derivation chain to find the first public parent, and use reflection properties/fields on the public parent. - if (!TypeResolver.IsPublic(type) && DisallowPrivateReflection(type)) + PropertyInfo[] properties = type.GetProperties(bindingFlags); + foreach (PropertyInfo property in properties) { - typeToGetPropertyAndField = GetFirstPublicParentType(type); - } - - // In CoreCLR, "GetFirstPublicParentType" may return null if 'type' is an interface - PropertyInfo[] properties; - if (typeToGetPropertyAndField != null) - { - properties = typeToGetPropertyAndField.GetProperties(bindingFlags); - for (int i = 0; i < properties.Length; i++) - { - PopulateSingleProperty(type, properties[i], tempTable, properties[i].Name); - } + PopulateSingleProperty(type, property, tempTable, property.Name); } Type[] interfaces = type.GetInterfaces(); - for (int interfaceIndex = 0; interfaceIndex < interfaces.Length; interfaceIndex++) + foreach (Type interfaceType in interfaces) { - Type interfaceType = interfaces[interfaceIndex]; if (!TypeResolver.IsPublic(interfaceType)) { continue; } properties = interfaceType.GetProperties(bindingFlags); - for (int propertyIndex = 0; propertyIndex < properties.Length; propertyIndex++) + foreach (PropertyInfo property in properties) { - PopulateSingleProperty(type, properties[propertyIndex], tempTable, properties[propertyIndex].Name); + if (isStatic && + (property.GetMethod?.IsVirtual == true || property.SetMethod?.IsVirtual == true)) + { + // Ignore static virtual/abstract properties on an interface because: + // 1. if it's implicitly implemented, which will be mostly the case, then the corresponding + // properties were already retrieved from the 'type.GetProperties' step above; + // 2. if it's explicitly implemented, we cannot call 'GetValue(null)' on the static property, + // but have to use 'type.GetInterfaceMap(interfaceType)' to get the corresponding target + // get/set accessor methods, and call 'Invoke(null, args)' on them. The target methods will + // be non-public in this case, which we always ignore. + // 3. The recommendation from .NET team is to ignore the static virtuals on interfaces, + // especially given that the APIs may change in .NET 7. + continue; + } + + PopulateSingleProperty(type, property, tempTable, property.Name); } } - foreach (var pairs in tempTable) + foreach (KeyValuePair<string, List<PropertyInfo>> entry in tempTable) { - var propertiesList = pairs.Value; + List<PropertyInfo> propertiesList = entry.Value; PropertyInfo firstProperty = propertiesList[0]; if ((propertiesList.Count > 1) || (firstProperty.GetIndexParameters().Length != 0)) { - typeProperties.Add(pairs.Key, new ParameterizedPropertyCacheEntry(propertiesList)); + typeProperties.Add(entry.Key, new ParameterizedPropertyCacheEntry(propertiesList)); } else { - typeProperties.Add(pairs.Key, new PropertyCacheEntry(firstProperty)); + typeProperties.Add(entry.Key, new PropertyCacheEntry(firstProperty)); } } - // In CoreCLR, "GetFirstPublicParentType" may return null if 'type' is an interface - if (typeToGetPropertyAndField != null) + FieldInfo[] fields = type.GetFields(bindingFlags); + foreach (FieldInfo field in fields) { - FieldInfo[] fields = typeToGetPropertyAndField.GetFields(bindingFlags); - for (int i = 0; i < fields.Length; i++) + string fieldName = field.Name; + var previousMember = (PropertyCacheEntry)typeProperties[fieldName]; + if (previousMember == null) { - FieldInfo field = fields[i]; - string fieldName = field.Name; - var previousMember = (PropertyCacheEntry)typeProperties[fieldName]; - if (previousMember == null) - { - typeProperties.Add(fieldName, new PropertyCacheEntry(field)); - } - else - { - // A property/field declared with new in a derived class might appear twice - if (!string.Equals(previousMember.member.Name, fieldName)) - { - throw new ExtendedTypeSystemException("NotACLSComplaintField", null, - ExtendedTypeSystem.NotAClsCompliantFieldProperty, fieldName, type.FullName, previousMember.member.Name); - } - } + typeProperties.Add(fieldName, new PropertyCacheEntry(field)); + } + else if (!string.Equals(previousMember.member.Name, fieldName)) + { + // A property/field declared with 'new' in a derived class might appear twice, and it's OK to ignore + // the second property/field in that case. + // However, if the names of two properties/fields are different only in letter casing, then it's not + // CLS complaint and we throw an exception. + throw new ExtendedTypeSystemException( + "NotACLSComplaintField", + innerException: null, + ExtendedTypeSystem.NotAClsCompliantFieldProperty, + fieldName, + type.FullName, + previousMember.member.Name); } } } @@ -3411,68 +3394,6 @@ private static void PopulateSingleProperty(Type type, PropertyInfo property, Dic } } - #region Handle_Internal_Type_Reflection_In_CoreCLR - - /// <summary> - /// The dictionary cache about if an assembly supports reflection execution on its internal types. - /// </summary> - private static readonly ConcurrentDictionary<string, bool> s_disallowReflectionCache = - new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase); - - /// <summary> - /// Check if the type is defined in an assembly that disallows reflection execution on internal types. - /// - .NET Framework assemblies don't support reflection execution on their internal types. - /// </summary> - internal static bool DisallowPrivateReflection(Type type) - { - bool disallowReflection = false; - Assembly assembly = type.Assembly; - if (s_disallowReflectionCache.TryGetValue(assembly.FullName, out disallowReflection)) - { - return disallowReflection; - } - - var productAttribute = assembly.GetCustomAttribute<AssemblyProductAttribute>(); - if (productAttribute != null && string.Equals(productAttribute.Product, "Microsoft® .NET Framework", StringComparison.OrdinalIgnoreCase)) - { - disallowReflection = true; - } - else - { - #pragma warning disable SYSLIB0015 - // Check for 'DisablePrivateReflectionAttribute'. It's applied at the assembly level, and allow an assembly to opt-out of private/internal reflection. - var disablePrivateReflectionAttribute = assembly.GetCustomAttribute<System.Runtime.CompilerServices.DisablePrivateReflectionAttribute>(); - disallowReflection = disablePrivateReflectionAttribute != null; - #pragma warning restore SYSLIB0015 - } - - s_disallowReflectionCache.TryAdd(assembly.FullName, disallowReflection); - return disallowReflection; - } - - /// <summary> - /// Walk up the derivation chain to find the first public parent type. - /// </summary> - internal static Type GetFirstPublicParentType(Type type) - { - Dbg.Assert(!TypeResolver.IsPublic(type), "type should not be public."); - Type parent = type.BaseType; - while (parent != null) - { - if (parent.IsPublic) - { - return parent; - } - - parent = parent.BaseType; - } - - // Return null when type is an interface - return null; - } - - #endregion Handle_Internal_Type_Reflection_In_CoreCLR - /// <summary> /// Called from GetProperty and GetProperties to populate the /// typeTable with all public properties and fields @@ -4286,11 +4207,10 @@ internal static object AuxiliaryMethodInvoke(object target, object[] arguments, /// </summary> /// <param name="methods">The methods to be converted.</param> /// <returns>The MethodInformation[] corresponding to methods.</returns> - internal static MethodInformation[] GetMethodInformationArray(MethodBase[] methods) + internal static MethodInformation[] GetMethodInformationArray(IList<MethodBase> methods) { - int methodCount = methods.Length; - MethodInformation[] returnValue = new MethodInformation[methodCount]; - for (int i = 0; i < methods.Length; i++) + var returnValue = new MethodInformation[methods.Count]; + for (int i = 0; i < methods.Count; i++) { returnValue[i] = new MethodInformation(methods[i], 0); } diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 3caceb40bb5..3176fbbead1 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -5651,15 +5651,6 @@ internal static IConversionData FigureConversion(Type fromType, Type toType) } } - // Assemblies in CoreCLR might not allow reflection execution on their internal types. - if (!TypeResolver.IsPublic(toType) && DotNetAdapter.DisallowPrivateReflection(toType)) - { - // If the type is non-public and reflection execution is not allowed on it, then we return - // 'ConvertNoConversion', because we won't be able to invoke constructor, methods or set - // properties on an instance of this type through reflection. - return CacheConversion(fromType, toType, ConvertNoConversion, ConversionRank.None); - } - PSConverter<object> valueDependentConversion = null; ConversionRank valueDependentRank = ConversionRank.None; IConversionData conversionData = FigureLanguageConversion(fromType, toType, out valueDependentConversion, out valueDependentRank); diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index 6cfc72fd169..a4917d5af6b 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -5407,18 +5407,6 @@ internal static Expression GetTargetExpr(DynamicMetaObject target, Type castToTy var type = castToType ?? ((value != null) ? value.GetType() : typeof(object)); - // Assemblies in CoreCLR might not allow reflection execution on their internal types. In such case, we walk up - // the derivation chain to find the first public parent, and use reflection methods on the public parent. - if (!TypeResolver.IsPublic(type) && DotNetAdapter.DisallowPrivateReflection(type)) - { - var publicType = DotNetAdapter.GetFirstPublicParentType(type); - if (publicType != null) - { - type = publicType; - } - // else we'll probably fail, but the error message might be more helpful than NullReferenceException - } - if (expr.Type != type) { // Unbox value types (or use Nullable<T>.Value) to avoid a copy in case the value is mutated. @@ -5779,7 +5767,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, } else { - DotNetAdapter.MethodCacheEntry method = new DotNetAdapter.MethodCacheEntry(candidateMethods.ToArray()); + DotNetAdapter.MethodCacheEntry method = new DotNetAdapter.MethodCacheEntry(candidateMethods); memberInfo = PSMethod.Create(this.Name, PSObject.DotNetInstanceAdapter, null, method); } } diff --git a/test/powershell/Language/Scripting/Adapter.Tests.ps1 b/test/powershell/Language/Scripting/Adapter.Tests.ps1 new file mode 100644 index 00000000000..db681192c4e --- /dev/null +++ b/test/powershell/Language/Scripting/Adapter.Tests.ps1 @@ -0,0 +1,110 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe "Interface static members" -Tags "CI" { + BeforeAll { + $testType = "InterfaceStaticMemberTest.ITest" -as [Type] + if (-not $testType) { + Add-Type -TypeDefinition @' + using System; + + namespace InterfaceStaticMemberTest { + public interface ITest { + public const int MyConst = 17; + + public static string Type = "ITest-Type"; + public static string Name => "Joe"; + public static string GetPath() => "Path"; + public int GetAge(); + public int GetId(); + } + + public class Foo : ITest { + int ITest.GetId() { return 100; } + int ITest.GetAge() { return 2; } + } + + public class Zoo : Foo { + public static string Type = "Zoo-Type"; + } + } +'@ + } + } + + It "Access static/const members on the interface type" { + [InterfaceStaticMemberTest.ITest]::MyConst | Should -Be 17 + [InterfaceStaticMemberTest.ITest]::Type | Should -Be "ITest-Type" + [InterfaceStaticMemberTest.ITest]::Name | Should -Be "Joe" + [InterfaceStaticMemberTest.ITest]::GetPath() | Should -Be "Path" + + $type = [InterfaceStaticMemberTest.ITest] + $type::MyConst | Should -Be 17 + $type::Type | Should -Be "ITest-Type" + $type::Name | Should -Be "Joe" + $type::GetPath() | Should -Be "Path" + + { [InterfaceStaticMemberTest.ITest]::Name = 'Jane' } | Should -Throw -ErrorId 'PropertyAssignmentException' + { $type::Name = 'Jane' } | Should -Throw -ErrorId 'PropertyAssignmentException' + } + + It "Access interface static/const members on the implementation type" { + [InterfaceStaticMemberTest.Foo]::MyConst | Should -Be 17 + [InterfaceStaticMemberTest.Foo]::Type | Should -Be "ITest-Type" + [InterfaceStaticMemberTest.Foo]::Name | Should -Be "Joe" + [InterfaceStaticMemberTest.Foo]::GetPath() | Should -Be "Path" + [InterfaceStaticMemberTest.Foo]::get_Name() | Should -Be "Joe" + + $type = [InterfaceStaticMemberTest.Foo] + $type::MyConst | Should -Be 17 + $type::Type | Should -Be "ITest-Type" + $type::Name | Should -Be "Joe" + $type::GetPath() | Should -Be "Path" + $type::get_Name() | Should -Be "Joe" + + { [InterfaceStaticMemberTest.Foo]::Name = 'Jane' } | Should -Throw -ErrorId 'PropertyAssignmentException' + { $type::Name = 'Jane' } | Should -Throw -ErrorId 'PropertyAssignmentException' + } + + It "Static field with the same name on the implementation type overrides the one from the interface" { + [InterfaceStaticMemberTest.Zoo]::Type | Should -Be "Zoo-Type" + + $type = [InterfaceStaticMemberTest.Zoo] + $type::Type | Should -Be "Zoo-Type" + + $nameMember = $type | Get-Member -Static -Name Name + $nameMember | Should -Not -BeNullOrEmpty + $nameMember.Name | Should -Be "Name" + $nameMember.MemberType | Should -Be "Property" + + $getNameMember = $type | Get-Member -Static -Name 'get_Name' + $getNameMember | Should -BeNullOrEmpty + + $getNameMember = $type | Get-Member -Static -Name 'get_Name' -Force + $getNameMember | Should -Not -BeNullOrEmpty + $getNameMember.Name | Should -Be "get_Name" + $getNameMember.MemberType | Should -Be "Method" + + $type::Name | Should -Be "Joe" + $type::get_Name() | Should -Be "Joe" + } + + It "Explicitly implemented interface members are visible/accessible by default" { + $obj = [InterfaceStaticMemberTest.Zoo]::new() + + $ageMember = $obj | Get-Member -Name GetAge + $ageMember | Should -Not -BeNullOrEmpty + $ageMember.Name | Should -Be "GetAge" + $ageMember.MemberType | Should -Be "Method" + $ageMember.Definition | Should -Be "int ITest.GetAge()" + + $idMember = $obj | Get-Member -Name GetId + $idMember | Should -Not -BeNullOrEmpty + $idMember.Name | Should -Be "GetId" + $idMember.MemberType | Should -Be "Method" + $idMember.Definition | Should -Be "int ITest.GetId()" + + $obj.GetAge() | Should -Be 2 + $obj.GetId() | Should -Be 100 + } +} From eeb04073775ee2ef6350ea6dc2c4ed3ba7089a52 Mon Sep 17 00:00:00 2001 From: Dongbo Wang <dongbow@microsoft.com> Date: Sat, 14 Aug 2021 14:31:49 -0700 Subject: [PATCH 48/55] Add more tests to validate the current command error handling behaviors (#15919) --- .../Scripting/CommandErrorHandling.Tests.ps1 | 470 ++++++++++++++++++ 1 file changed, 470 insertions(+) create mode 100644 test/powershell/Language/Scripting/CommandErrorHandling.Tests.ps1 diff --git a/test/powershell/Language/Scripting/CommandErrorHandling.Tests.ps1 b/test/powershell/Language/Scripting/CommandErrorHandling.Tests.ps1 new file mode 100644 index 00000000000..fe2ed803ecf --- /dev/null +++ b/test/powershell/Language/Scripting/CommandErrorHandling.Tests.ps1 @@ -0,0 +1,470 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe 'Command error handling in general' -Tag 'CI' { + + BeforeAll { + $pwsh = [PowerShell]::Create() + $pwsh.AddScript(@' + + function ThrowTerminatingError { + [CmdletBinding()] + param() + + $ex = [System.ArgumentException]::new('terminating-exception') + $er = [System.Management.Automation.ErrorRecord]::new($ex, 'ThrowTerminatingError:error', 'InvalidArgument', $null) + $PSCmdlet.ThrowTerminatingError($er) + + Write-Verbose -Verbose "verbose-message" + } + + function ErrorActionStop { + [CmdletBinding()] + param() + + Get-Command NonExist -ErrorAction Stop + Write-Verbose -Verbose "verbose-message" + } + + function ThrowException { + [CmdletBinding()] + param() + + throw 'throw-exception' + Write-Verbose -Verbose "verbose-message" + } + + function WriteErrorAPI { + [CmdletBinding()] + param() + + $ex = [System.ArgumentException]::new('arg-exception') + $er = [System.Management.Automation.ErrorRecord]::new($ex, 'WriteErrorAPI:error', 'InvalidArgument', $null) + $PSCmdlet.WriteError($er) + + Write-Verbose -Verbose "verbose-message" + } + + function WriteErrorCmdlet { + [CmdletBinding()] + param() + + Write-Error 'write-error-cmdlet' + Write-Verbose -Verbose "verbose-message" + } + + function MethodInvocationThrowException { + [CmdletBinding()] + param() + + ## This method call throws exception. + $iss = [initialsessionstate]::Create() + $iss.ImportPSModule($null) + + Write-Verbose -Verbose "verbose-message" + } + + function ExpressionThrowException { + [CmdletBinding()] + param() + + 1/0 ## throw exception. + Write-Verbose -Verbose "verbose-message" + } + +'@).Invoke() + + function RunCommand { + param( + [string] $Command, + [ValidateSet('Continue', 'Ignore', 'SilentlyContinue', 'Stop')] + [string] $ErrorAction + ) + + $pwsh.Commands.Clear() + $pwsh.Streams.ClearStreams() + $pwsh.AddCommand($command).AddParameter('ErrorAction', $ErrorAction).Invoke() + } + + function RunScript { + param([string] $Script) + + $pwsh.Commands.Clear() + $pwsh.Streams.ClearStreams() + $pwsh.AddScript($Script).Invoke() + } + + function GetLastError { + $pwsh.Commands.Clear() + $pwsh.AddCommand('Get-Error').Invoke() + } + + function ClearDollarError { + $pwsh.Commands.Clear() + $pwsh.AddScript('$Error.Clear()').Invoke() + } + } + + AfterAll { + $pwsh.Dispose() + } + + Context 'Terminating error' { + + It "'ThrowTerminatingError' should always stop execution even when the error action is '<ErrorAction>'" -TestCases @( + @{ ErrorAction = 'Continue' } + @{ ErrorAction = 'Ignore' } + @{ ErrorAction = 'SilentlyContinue' } + ) { + param ($ErrorAction) + + $failure = $null + + try { + RunCommand -Command 'ThrowTerminatingError' -ErrorAction $ErrorAction + } catch { + $failure = $_ + } + + $failure | Should -Not -BeNullOrEmpty + $failure.Exception | Should -BeOfType 'System.Management.Automation.MethodInvocationException' + $failure.Exception.InnerException | Should -BeOfType 'System.Management.Automation.CmdletInvocationException' + $failure.Exception.InnerException.InnerException | Should -BeOfType 'System.ArgumentException' + $failure.Exception.InnerException.InnerException.Message | Should -BeExactly 'terminating-exception' + + $pwsh.Streams.Verbose | Should -HaveCount 0 + } + + It "'-ErrorAction Stop' should always stop execution even when the error action is '<ErrorAction>'" -TestCases @( + @{ ErrorAction = 'Continue' } + @{ ErrorAction = 'Ignore' } + @{ ErrorAction = 'SilentlyContinue' } + ) { + param ($ErrorAction) + + $failure = $null + + try { + RunCommand -Command 'ErrorActionStop' -ErrorAction $ErrorAction + } catch { + $failure = $_ + } + + $failure | Should -Not -BeNullOrEmpty + $failure.Exception | Should -BeOfType 'System.Management.Automation.MethodInvocationException' + $failure.Exception.InnerException | Should -BeOfType 'System.Management.Automation.ActionPreferenceStopException' + $failure.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly 'CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand' + + $pwsh.Streams.Verbose | Should -HaveCount 0 + } + + It "'throw' statement should stop execution when running with the default error action ('Continue')" { + $failure = $null + + try { + RunCommand -Command 'ThrowException' -ErrorAction 'Continue' + } catch { + $failure = $_ + } + + $failure | Should -Not -BeNullOrEmpty + $failure.Exception | Should -BeOfType 'System.Management.Automation.MethodInvocationException' + $failure.Exception.InnerException | Should -BeOfType 'System.Management.Automation.RuntimeException' + $failure.Exception.InnerException.Message | Should -BeExactly 'throw-exception' + + $pwsh.Streams.Verbose | Should -HaveCount 0 + } + + <# The 'throw' statement is special, in that it can be suppressed by '-ErrorAction SilentlyContinue/Ignore' #> + It "'throw' statement doesn't stop execution when the error action is '<ErrorAction>'" -TestCases @( + @{ ErrorAction = 'Ignore' } + @{ ErrorAction = 'SilentlyContinue' } + ) { + param ($ErrorAction) + + $failure = $null + + try { + RunCommand -Command 'ThrowException' -ErrorAction $ErrorAction + } catch { + $failure = $_ + } + + $failure | Should -BeNullOrEmpty + $pwsh.Streams.Verbose | Should -HaveCount 1 + $pwsh.Streams.Verbose | Should -BeExactly 'verbose-message' + + ## The suppressed 'throw' exception is not written to the error stream, not sure why but it's the current behavior. + $pwsh.Streams.Error | Should -HaveCount 0 + + ## The suppressed 'throw' exception is kept in '$Error' + $err = GetLastError + $err | Should -Not -BeNullOrEmpty + $err.FullyQualifiedErrorId | Should -BeExactly 'throw-exception' + } + + It "'throw' statement should stop execution with the error action '<ErrorAction>' when it's wrapped in 'try/catch'" -TestCases @( + @{ ErrorAction = 'Ignore' } + @{ ErrorAction = 'SilentlyContinue' } + ) { + param ($ErrorAction) + + RunScript -Script "try { ThrowException -ErrorAction $ErrorAction } catch { Write-Debug -Debug `$_.FullyQualifiedErrorId }" + + $pwsh.Streams.Verbose | Should -HaveCount 0 + $pwsh.Streams.Debug | Should -HaveCount 1 + $pwsh.Streams.Debug | Should -BeExactly 'throw-exception' + } + + It "'throw' statement should stop execution with the error action '<ErrorAction>' when it's accompanied by 'trap' statement" -TestCases @( + @{ ErrorAction = 'Ignore' } + @{ ErrorAction = 'SilentlyContinue' } + ) { + param ($ErrorAction) + + RunScript -Script "trap { Write-Debug -Debug `$_.FullyQualifiedErrorId; continue } ThrowException -ErrorAction $ErrorAction" + + $pwsh.Streams.Verbose | Should -HaveCount 0 + $pwsh.Streams.Debug | Should -HaveCount 1 + $pwsh.Streams.Debug | Should -BeExactly 'throw-exception' + } + } + + Context 'Non-terminating error' { + + It "'WriteErrorAPI' doesn't stop execution with the default error action ('Continue')" { + RunCommand -Command 'WriteErrorAPI' -ErrorAction Continue + + $pwsh.Streams.Error | Should -HaveCount 1 + $pwsh.Streams.Error[0].Exception.Message | Should -BeExactly 'arg-exception' + $pwsh.Streams.Error[0].FullyQualifiedErrorId | Should -BeExactly 'WriteErrorAPI:error,WriteErrorAPI' + + $pwsh.Streams.Verbose | Should -HaveCount 1 + $pwsh.Streams.Verbose | Should -BeExactly 'verbose-message' + } + + It "'WriteErrorAPI' doesn't stop execution with the error action 'Ignore' and the error doesn't get logged in `$Error" { + ClearDollarError + RunCommand -Command 'WriteErrorAPI' -ErrorAction Ignore + + $pwsh.Streams.Error | Should -HaveCount 0 + $pwsh.Streams.Verbose | Should -HaveCount 1 + $pwsh.Streams.Verbose | Should -BeExactly 'verbose-message' + + $lastErr = GetLastError + $lastErr | Should -BeNullOrEmpty + } + + It "'WriteErrorAPI' doesn't stop execution with the error action 'SilentlyContinue' and the error gets logged in `$Error" { + ClearDollarError + RunCommand -Command 'WriteErrorAPI' -ErrorAction SilentlyContinue + + $pwsh.Streams.Error | Should -HaveCount 0 + $pwsh.Streams.Verbose | Should -HaveCount 1 + $pwsh.Streams.Verbose | Should -BeExactly 'verbose-message' + + $lastErr = GetLastError + $lastErr | Should -Not -BeNullOrEmpty + $lastErr.Exception.Message | Should -BeExactly 'arg-exception' + $lastErr.FullyQualifiedErrorId | Should -BeExactly 'WriteErrorAPI:error,WriteErrorAPI' + } + + It "'WriteErrorCmdlet' doesn't stop execution with the default error action ('Continue')" { + RunCommand -Command 'WriteErrorCmdlet' -ErrorAction Continue + + $pwsh.Streams.Error | Should -HaveCount 1 + $pwsh.Streams.Error[0].Exception.Message | Should -BeExactly 'write-error-cmdlet' + $pwsh.Streams.Error[0].FullyQualifiedErrorId | Should -BeExactly 'Microsoft.PowerShell.Commands.WriteErrorException,WriteErrorCmdlet' + + $pwsh.Streams.Verbose | Should -HaveCount 1 + $pwsh.Streams.Verbose | Should -BeExactly 'verbose-message' + } + + It "'WriteErrorCmdlet' doesn't stop execution with the error action 'Ignore' and the error doesn't get logged in `$Error" { + ClearDollarError + RunCommand -Command 'WriteErrorCmdlet' -ErrorAction Ignore + + $pwsh.Streams.Error | Should -HaveCount 0 + $pwsh.Streams.Verbose | Should -HaveCount 1 + $pwsh.Streams.Verbose | Should -BeExactly 'verbose-message' + + $lastErr = GetLastError + $lastErr | Should -BeNullOrEmpty + } + + It "'WriteErrorCmdlet' doesn't stop execution with the error action 'SilentlyContinue' and the error gets logged in `$Error" { + ClearDollarError + RunCommand -Command 'WriteErrorCmdlet' -ErrorAction SilentlyContinue + + $pwsh.Streams.Error | Should -HaveCount 0 + $pwsh.Streams.Verbose | Should -HaveCount 1 + $pwsh.Streams.Verbose | Should -BeExactly 'verbose-message' + + $lastErr = GetLastError + $lastErr | Should -Not -BeNullOrEmpty + $lastErr.Exception.Message | Should -BeExactly 'write-error-cmdlet' + $lastErr.FullyQualifiedErrorId | Should -BeExactly 'Microsoft.PowerShell.Commands.WriteErrorException,WriteErrorCmdlet' + } + } + + Context 'Exception thrown from the method invocation or expression' { + + #region MethodInvocationThrowException + + It "'MethodInvocationThrowException' emits non-terminating error with the default error action ('Continue')" { + RunCommand -Command 'MethodInvocationThrowException' -ErrorAction 'Continue' + + $pwsh.Streams.Error | Should -HaveCount 1 + $pwsh.Streams.Error[0].FullyQualifiedErrorId | Should -BeExactly 'ArgumentNullException' + + $pwsh.Streams.Verbose | Should -HaveCount 1 + $pwsh.Streams.Verbose | Should -BeExactly 'verbose-message' + } + + It "'MethodInvocationThrowException' emits no error with the error action '<ErrorAction>'" -TestCases @( + @{ ErrorAction = 'Ignore' } + @{ ErrorAction = 'SilentlyContinue' } + ) { + param ($ErrorAction) + + RunCommand -Command 'MethodInvocationThrowException' -ErrorAction $ErrorAction + + $pwsh.Streams.Error | Should -HaveCount 0 + $pwsh.Streams.Verbose | Should -HaveCount 1 + $pwsh.Streams.Verbose | Should -BeExactly 'verbose-message' + + ## The suppressed exception is kept in '$Error' + $err = GetLastError + $err | Should -Not -BeNullOrEmpty + $err.FullyQualifiedErrorId | Should -BeExactly 'ArgumentNullException' + } + + It "'MethodInvocationThrowException' emits terminating error with the error action 'Stop'" { + $failure = $null + + try { + RunCommand -Command 'MethodInvocationThrowException' -ErrorAction Stop + } catch { + $failure = $_ + } + + $failure | Should -Not -BeNullOrEmpty + $failure.Exception | Should -BeOfType 'System.Management.Automation.MethodInvocationException' + $failure.Exception.InnerException | Should -BeOfType 'System.Management.Automation.CmdletInvocationException' + $failure.Exception.InnerException.InnerException.InnerException | Should -BeOfType 'System.ArgumentNullException' + + $pwsh.Streams.Verbose | Should -HaveCount 0 + } + + It "'MethodInvocationThrowException' emits terminating error with the error action '<ErrorAction>' when it's wrapped in 'try/catch'" -TestCases @( + @{ ErrorAction = 'Continue' } + @{ ErrorAction = 'Ignore' } + @{ ErrorAction = 'SilentlyContinue' } + ) { + param ($ErrorAction) + + RunScript -Script "try { MethodInvocationThrowException -ErrorAction $ErrorAction } catch { Write-Debug -Debug `$_.Exception.InnerException.GetType().FullName }" + + $pwsh.Streams.Error | Should -HaveCount 0 + $pwsh.Streams.Verbose | Should -HaveCount 0 + $pwsh.Streams.Debug | Should -HaveCount 1 + $pwsh.Streams.Debug | Should -BeExactly 'System.ArgumentNullException' + } + + It "'MethodInvocationThrowException' emits terminating error with the error action '<ErrorAction>' when it's accompanied by 'trap' statement" -TestCases @( + @{ ErrorAction = 'Continue' } + @{ ErrorAction = 'Ignore' } + @{ ErrorAction = 'SilentlyContinue' } + ) { + param ($ErrorAction) + + RunScript -Script "trap { Write-Debug -Debug `$_.Exception.InnerException.GetType().FullName; continue } MethodInvocationThrowException -ErrorAction $ErrorAction" + + $pwsh.Streams.Error | Should -HaveCount 0 + $pwsh.Streams.Verbose | Should -HaveCount 0 + $pwsh.Streams.Debug | Should -HaveCount 1 + $pwsh.Streams.Debug | Should -BeExactly 'System.ArgumentNullException' + } + + #endregion + + #region ExpressionThrowException + + It "'ExpressionThrowException' emits non-terminating error with the default error action ('Continue')" { + RunCommand -Command 'ExpressionThrowException' -ErrorAction 'Continue' + + $pwsh.Streams.Error | Should -HaveCount 1 + $pwsh.Streams.Error[0].Exception.InnerException | Should -BeOfType 'System.DivideByZeroException' + + $pwsh.Streams.Verbose | Should -HaveCount 1 + $pwsh.Streams.Verbose | Should -BeExactly 'verbose-message' + } + + It "'ExpressionThrowException' emits no error with the error action '<ErrorAction>'" -TestCases @( + @{ ErrorAction = 'Ignore' } + @{ ErrorAction = 'SilentlyContinue' } + ) { + param ($ErrorAction) + + RunCommand -Command 'ExpressionThrowException' -ErrorAction $ErrorAction + + $pwsh.Streams.Error | Should -HaveCount 0 + $pwsh.Streams.Verbose | Should -HaveCount 1 + $pwsh.Streams.Verbose | Should -BeExactly 'verbose-message' + + ## The suppressed exception is kept in '$Error' + $err = GetLastError + $err | Should -Not -BeNullOrEmpty + $err.Exception.InnerException | Should -BeOfType 'System.DivideByZeroException' + } + + It "'ExpressionThrowException' emits terminating error with the error action 'Stop'" { + $failure = $null + + try { + RunCommand -Command 'ExpressionThrowException' -ErrorAction Stop + } catch { + $failure = $_ + } + + $failure | Should -Not -BeNullOrEmpty + $failure.Exception | Should -BeOfType 'System.Management.Automation.MethodInvocationException' + $failure.Exception.InnerException | Should -BeOfType 'System.Management.Automation.CmdletInvocationException' + $failure.Exception.InnerException.InnerException.InnerException | Should -BeOfType 'System.DivideByZeroException' + + $pwsh.Streams.Verbose | Should -HaveCount 0 + } + + It "'ExpressionThrowException' emits terminating error with the error action '<ErrorAction>' when it's wrapped in 'try/catch'" -TestCases @( + @{ ErrorAction = 'Continue' } + @{ ErrorAction = 'Ignore' } + @{ ErrorAction = 'SilentlyContinue' } + ) { + param ($ErrorAction) + + RunScript -Script "try { ExpressionThrowException -ErrorAction $ErrorAction } catch { Write-Debug -Debug `$_.Exception.InnerException.GetType().FullName }" + + $pwsh.Streams.Error | Should -HaveCount 0 + $pwsh.Streams.Verbose | Should -HaveCount 0 + $pwsh.Streams.Debug | Should -HaveCount 1 + $pwsh.Streams.Debug | Should -BeExactly 'System.DivideByZeroException' + } + + It "'ExpressionThrowException' emits terminating error with the error action '<ErrorAction>' when it's accompanied by 'trap' statement" -TestCases @( + @{ ErrorAction = 'Continue' } + @{ ErrorAction = 'Ignore' } + @{ ErrorAction = 'SilentlyContinue' } + ) { + param ($ErrorAction) + + RunScript -Script "trap { Write-Debug -Debug `$_.Exception.InnerException.GetType().FullName; continue } ExpressionThrowException -ErrorAction $ErrorAction" + + $pwsh.Streams.Error | Should -HaveCount 0 + $pwsh.Streams.Verbose | Should -HaveCount 0 + $pwsh.Streams.Debug | Should -HaveCount 1 + $pwsh.Streams.Debug | Should -BeExactly 'System.DivideByZeroException' + } + + #endregion + } +} From 9fcc5631b1d13be64ecea2a678e0359a60ed9c58 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 Aug 2021 08:50:15 -0700 Subject: [PATCH 49/55] Bump `Microsoft.CodeAnalysis.NetAnalyzers` to newer version (#15935) --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index f5ac2ffbbcd..235daa43009 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,7 @@ <Project> <ItemGroup> <PackageReference Include="DotNetAnalyzers.DocumentationAnalyzers" Version="1.0.0-beta.59" PrivateAssets="all" /> - <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="6.0.0-rc1.21406.1" PrivateAssets="all" /> + <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="6.0.0-rc1.21413.4" PrivateAssets="all" /> <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.354" PrivateAssets="all" /> </ItemGroup> </Project> From b3a12b4faaa442d26bd16556142ccec5bd088746 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 Aug 2021 08:52:07 -0700 Subject: [PATCH 50/55] Bump `Microsoft.NET.Test.Sdk` from 16.10.0 to 16.11.0 (#15934) --- test/xUnit/xUnit.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index eca8262436b..967f1cce627 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -27,7 +27,7 @@ <PackageReference Include="Xunit.SkippableFact" Version="1.4.13" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="XunitXml.TestLogger" Version="3.0.66" /> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.10.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" /> </ItemGroup> <ItemGroup> From a162856af5cc8df7e084a478d14442e926dff1c0 Mon Sep 17 00:00:00 2001 From: Steve Lee <slee@microsoft.com> Date: Mon, 16 Aug 2021 14:17:07 -0700 Subject: [PATCH 51/55] Change default to `OutputRendering.Host` and remove `OutputRendering.Automatic` (#15882) --- .../FormatAndOutput/common/PSStyle.cs | 9 +-- .../FormatAndOutput/common/StringDecorated.cs | 52 ++++++--------- .../engine/Utils.cs | 3 - .../resources/StringDecoratedStrings.resx | 64 +++++++++++++++++++ .../SuppressAnsiEscapeSequence.Tests.ps1 | 3 + .../Format-List.Tests.ps1 | 3 + .../Format-Table.Tests.ps1 | 9 +++ .../Get-Error.Tests.ps1 | 3 + .../Select-String.Tests.ps1 | 3 + .../Formatting/OutputRendering.Tests.ps1 | 11 +++- .../engine/Formatting/PSStyle.Tests.ps1 | 8 ++- 11 files changed, 122 insertions(+), 46 deletions(-) create mode 100644 src/System.Management.Automation/resources/StringDecoratedStrings.resx diff --git a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs index 8efb46e40c7..9f6b74bdc1d 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs @@ -13,17 +13,14 @@ namespace System.Management.Automation /// </summary> public enum OutputRendering { - /// <summary>Automatic by PowerShell.</summary> - Automatic = 0, + /// <summary>Render ANSI only to host.</summary> + Host = 0, /// <summary>Render as plaintext.</summary> PlainText = 1, /// <summary>Render as ANSI.</summary> Ansi = 2, - - /// <summary>Render ANSI only to host.</summary> - Host = 3, } #endregion OutputRendering @@ -565,7 +562,7 @@ public FileInfoFormatting() /// <summary> /// Gets or sets the rendering mode for output. /// </summary> - public OutputRendering OutputRendering { get; set; } = OutputRendering.Automatic; + public OutputRendering OutputRendering { get; set; } = OutputRendering.Host; /// <summary> /// Gets value to turn off all attributes. diff --git a/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs b/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs index 3c1041f9c47..03a360ff5c1 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs @@ -55,7 +55,10 @@ public StringDecorated(string text) /// Render the decorarted string using automatic output rendering. /// </summary> /// <returns>Rendered string based on automatic output rendering.</returns> - public override string ToString() => _isDecorated ? ToString(OutputRendering.Automatic) : _text; + public override string ToString() => ToString( + PSStyle.Instance.OutputRendering == OutputRendering.PlainText + ? OutputRendering.PlainText + : OutputRendering.Ansi); /// <summary> /// Return string representation of content depending on output rendering mode. @@ -64,28 +67,17 @@ public StringDecorated(string text) /// <returns>Rendered string based on outputRendering.</returns> public string ToString(OutputRendering outputRendering) { - if (!_isDecorated) + if (outputRendering == OutputRendering.Host) { - return _text; + throw new ArgumentException(StringDecoratedStrings.RequireExplicitRendering); } - if (outputRendering == OutputRendering.Automatic) - { - outputRendering = OutputRendering.Ansi; - if (PSStyle.Instance.OutputRendering == OutputRendering.PlainText) - { - outputRendering = OutputRendering.PlainText; - } - } - - if (outputRendering == OutputRendering.PlainText) - { - return PlainText; - } - else + if (!_isDecorated) { return _text; } + + return outputRendering == OutputRendering.PlainText ? PlainText : _text; } } @@ -139,7 +131,10 @@ public ValueStringDecorated(string text) /// Render the decorarted string using automatic output rendering. /// </summary> /// <returns>Rendered string based on automatic output rendering.</returns> - public override string ToString() => _isDecorated ? ToString(OutputRendering.Automatic) : _text; + public override string ToString() => ToString( + PSStyle.Instance.OutputRendering == OutputRendering.PlainText + ? OutputRendering.PlainText + : OutputRendering.Ansi); /// <summary> /// Return string representation of content depending on output rendering mode. @@ -148,28 +143,17 @@ public ValueStringDecorated(string text) /// <returns>Rendered string based on outputRendering.</returns> public string ToString(OutputRendering outputRendering) { - if (!_isDecorated) + if (outputRendering == OutputRendering.Host) { - return _text; + throw new ArgumentException(StringDecoratedStrings.RequireExplicitRendering); } - if (outputRendering == OutputRendering.Automatic) - { - outputRendering = OutputRendering.Ansi; - if (PSStyle.Instance.OutputRendering == OutputRendering.PlainText) - { - outputRendering = OutputRendering.PlainText; - } - } - - if (outputRendering == OutputRendering.PlainText) - { - return PlainText; - } - else + if (!_isDecorated) { return _text; } + + return outputRendering == OutputRendering.PlainText ? PlainText : _text; } } } diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 8115ebbabcf..eb2470e6d17 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1570,9 +1570,6 @@ internal static bool ShouldOutputPlainText(bool isHost, bool? supportsVirtualTer { switch (PSStyle.Instance.OutputRendering) { - case OutputRendering.Automatic: - outputRendering = OutputRendering.Ansi; - break; case OutputRendering.Host: outputRendering = isHost ? OutputRendering.Ansi : OutputRendering.PlainText; break; diff --git a/src/System.Management.Automation/resources/StringDecoratedStrings.resx b/src/System.Management.Automation/resources/StringDecoratedStrings.resx new file mode 100644 index 00000000000..e16aa999992 --- /dev/null +++ b/src/System.Management.Automation/resources/StringDecoratedStrings.resx @@ -0,0 +1,64 @@ +<?xml version="1.0" encoding="utf-8"?> +<root> + <xsd:schema id="root" xmlns="" xmlns:xsd="https://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + <xsd:import namespace="https://www.w3.org/XML/1998/namespace" /> + <xsd:element name="root" msdata:IsDataSet="true"> + <xsd:complexType> + <xsd:choice maxOccurs="unbounded"> + <xsd:element name="metadata"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" /> + </xsd:sequence> + <xsd:attribute name="name" use="required" type="xsd:string" /> + <xsd:attribute name="type" type="xsd:string" /> + <xsd:attribute name="mimetype" type="xsd:string" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="assembly"> + <xsd:complexType> + <xsd:attribute name="alias" type="xsd:string" /> + <xsd:attribute name="name" type="xsd:string" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="data"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> + <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> + <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="resheader"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" /> + </xsd:complexType> + </xsd:element> + </xsd:choice> + </xsd:complexType> + </xsd:element> + </xsd:schema> + <resheader name="resmimetype"> + <value>text/microsoft-resx</value> + </resheader> + <resheader name="version"> + <value>2.0</value> + </resheader> + <resheader name="reader"> + <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <resheader name="writer"> + <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <data name="RequireExplicitRendering" xml:space="preserve"> + <value>Only 'ANSI' or 'PlainText' is supported for this method.</value> + </data> +</root> diff --git a/test/powershell/Language/Scripting/SuppressAnsiEscapeSequence.Tests.ps1 b/test/powershell/Language/Scripting/SuppressAnsiEscapeSequence.Tests.ps1 index 568e56be904..30a82309a70 100644 --- a/test/powershell/Language/Scripting/SuppressAnsiEscapeSequence.Tests.ps1 +++ b/test/powershell/Language/Scripting/SuppressAnsiEscapeSequence.Tests.ps1 @@ -4,10 +4,13 @@ Describe '$env:__SuppressAnsiEscapeSequences tests' -Tag CI { BeforeAll { $originalSuppressPref = $env:__SuppressAnsiEscapeSequences + $originalRendering = $PSStyle.OutputRendering + $PSStyle.OutputRendering = 'Ansi' } AfterAll { $env:__SuppressAnsiEscapeSequences = $originalSuppressPref + $PSStyle.OutputRendering = $originalRendering } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-List.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-List.Tests.ps1 index 11f2297997b..715503c3577 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-List.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-List.Tests.ps1 @@ -213,10 +213,13 @@ dbda : KM Describe 'Format-List color tests' { BeforeAll { + $originalRendering = $PSStyle.OutputRendering + $PSStyle.OutputRendering = 'Ansi' [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('ForceFormatListFixedLabelWidth', $true) } AfterAll { + $PSStyle.OutputRendering = $originalRendering [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('ForceFormatListFixedLabelWidth', $false) } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 index 277ca8d2d8e..3d4111e89a5 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 @@ -848,6 +848,15 @@ A Name B } Describe 'Table color tests' { + BeforeAll { + $originalRendering = $PSStyle.OutputRendering + $PSStyle.OutputRendering = 'Ansi' + } + + AfterAll { + $PSStyle.OutputRendering = $originalRendering + } + It 'Table header should use FormatAccent' { ([pscustomobject]@{foo = 1} | Format-Table | Out-String).Trim() | Should -BeExactly @" $($PSStyle.Formatting.FormatAccent)foo$($PSStyle.Reset) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 index 9581b3a8fd0..651eaa287dd 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Error.Tests.ps1 @@ -134,6 +134,8 @@ Describe 'Get-Error tests' -Tag CI { } try { + $originalRendering = $PSStyle.OutputRendering + $PSStyle.OutputRendering = 'Ansi' $out = pwsh -noprofile -command '$PSStyle.OutputRendering = "ANSI"; [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook("BypassOutputRedirectionCheck", $true); try { 1/0 } catch { }; Get-Error' | Out-String # need to escape the open square bracket so the regex works @@ -145,6 +147,7 @@ Describe 'Get-Error tests' -Tag CI { } finally { + $PSStyle.OutputRendering = $originalRendering if ($suppressVT) { $env:__SuppressAnsiEscapeSequences = 1 } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-String.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-String.Tests.ps1 index 68c238abb78..0351001cb99 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-String.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-String.Tests.ps1 @@ -5,9 +5,12 @@ Describe "Select-String" -Tags "CI" { BeforeAll { $nl = [Environment]::NewLine $currentDirectory = $PWD.Path + $originalRendering = $PSStyle.OutputRendering + $PSStyle.OutputRendering = 'Ansi' } AfterAll { + $PSStyle.OutputRendering = $originalRendering Push-Location $currentDirectory } diff --git a/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 index 1ca13cb138b..106197b10f5 100644 --- a/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 +++ b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 @@ -25,7 +25,6 @@ Describe 'OutputRendering tests' { } It 'OutputRendering works for "<outputRendering>" to the host' -TestCases @( - @{ outputRendering = 'automatic'; ansi = $true } @{ outputRendering = 'host' ; ansi = $true } @{ outputRendering = 'ansi' ; ansi = $true } @{ outputRendering = 'plaintext'; ansi = $false } @@ -43,7 +42,6 @@ Describe 'OutputRendering tests' { } It 'OutputRendering works for "<outputRendering>" to the pipeline' -TestCases @( - @{ outputRendering = 'automatic'; ansi = $true } @{ outputRendering = 'host' ; ansi = $false } @{ outputRendering = 'ansi' ; ansi = $true } @{ outputRendering = 'plaintext'; ansi = $false } @@ -79,4 +77,13 @@ Describe 'OutputRendering tests' { $out[0] | Should -BeExactly "$($PSStyle.Formatting.$stream)$($stream.ToUpper()): hello$($PSStyle.Reset)" -Because ($out[0] | Out-String | Format-hex) $out[1] | Should -BeExactly "bye" } + + It 'ToString(OutputRendering) works correctly' { + $s = [System.Management.Automation.Internal.StringDecorated]::new($PSStyle.Foreground.Red + 'Hello') + $s.IsDecorated | Should -BeTrue + $s.ToString() | Should -BeExactly "$($PSStyle.Foreground.Red)Hello" + $s.ToString([System.Management.Automation.OutputRendering]::ANSI) | Should -BeExactly "$($PSStyle.Foreground.Red)Hello" + $s.ToString([System.Management.Automation.OutputRendering]::PlainText) | Should -BeExactly 'Hello' + { $s.ToString([System.Management.Automation.OutputRendering]::Host) } | Should -Throw -ErrorId 'ArgumentException' + } } diff --git a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 index f6cde2a4a01..2dd984453cb 100644 --- a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 +++ b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 @@ -83,7 +83,7 @@ Describe 'Tests for $PSStyle automatic variable' { It '$PSStyle has correct default for OutputRendering' { $PSStyle | Should -Not -BeNullOrEmpty - $PSStyle.OutputRendering | Should -BeExactly 'Automatic' + $PSStyle.OutputRendering | Should -BeExactly 'Host' } It '$PSStyle has correct defaults for style <key>' -TestCases (Get-TestCases $styleDefaults) { @@ -137,26 +137,32 @@ Describe 'Tests for $PSStyle automatic variable' { It '$PSStyle.Formatting.FormatAccent is applied to Format-List' { $old = $PSStyle.Formatting.FormatAccent + $oldRender = $PSStyle.OutputRendering try { + $PSStyle.OutputRendering = 'Ansi' $PSStyle.Formatting.FormatAccent = $PSStyle.Foreground.Yellow + $PSStyle.Background.Red + $PSStyle.Italic $out = $PSVersionTable | Format-List | Out-String $out | Should -BeLike "*$($PSStyle.Formatting.FormatAccent.Replace('[',"``["))*" } finally { + $PSStyle.OutputRendering = $oldRender $PSStyle.Formatting.FormatAccent = $old } } It '$PSStyle.Formatting.TableHeader is applied to Format-Table' { $old = $PSStyle.Formatting.TableHeader + $oldRender = $PSStyle.OutputRendering try { + $PSStyle.OutputRendering = 'Ansi' $PSStyle.Formatting.TableHeader = $PSStyle.Foreground.Blue + $PSStyle.Background.White + $PSStyle.Bold $out = $PSVersionTable | Format-Table | Out-String $out | Should -BeLike "*$($PSStyle.Formatting.TableHeader.Replace('[',"``["))*" } finally { + $PSStyle.OutputRendering = $oldRender $PSStyle.Formatting.TableHeader = $old } } From 55855fbe5d646627834e91140caab1a102940587 Mon Sep 17 00:00:00 2001 From: arfy slowy <slowy.arfy@gmail.com> Date: Tue, 17 Aug 2021 11:01:04 +0700 Subject: [PATCH 52/55] Fix spelling in XML docs (#15939) --- .../HelpWindow/HelpParagraphBuilder.cs | 2 +- .../HelpWindow/ParagraphBuilder.cs | 4 +- .../HelpWindow/ParagraphSearcher.cs | 2 +- .../FilterCore/FilterEvaluator.cs | 2 +- .../ManagementList/FilterCore/IEvaluate.cs | 2 +- .../FilterProviders/FilterRulePanelItem.cs | 2 +- .../ManagementList/Innerlist.cs | 2 +- .../ShowCommand/ViewModel/CommandViewModel.cs | 2 +- .../ShowCommand/ViewModel/ModuleViewModel.cs | 2 +- .../ViewModel/ParameterSetViewModel.cs | 2 +- .../CoreCLR/Stubs.cs | 2 +- .../commands/utility/TestJsonCommand.cs | 2 +- .../commands/utility/UtilityCommon.cs | 2 +- .../Common/WebRequestPSCmdlet.Common.cs | 2 +- .../host/msh/ConsoleHost.cs | 2 +- .../host/msh/ConsoleHostRawUserInterface.cs | 2 +- .../host/msh/UpdatesNotification.cs | 2 +- .../DotNetCode/Eventing/EventProvider.cs | 2 +- .../CommandCompletion/CompletionCompleters.cs | 2 +- .../engine/Subsystem/SubsystemManager.cs | 4 +- .../remoting/common/RunspaceConnectionInfo.cs | 2 +- .../remoting/common/RunspacePoolStateInfo.cs | 2 +- .../help/DscResourceHelpProvider.cs | 2 +- .../help/MamlNode.cs | 2 +- .../namespaces/FileSystemContentStream.cs | 2 +- .../namespaces/FileSystemProvider.cs | 42 +++++++++---------- 26 files changed, 48 insertions(+), 48 deletions(-) diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs index 1d4bcacd893..a0f2cf950bd 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs @@ -690,7 +690,7 @@ private static void FormatMethodData(PSObject member, string name, out string me { parameterType = GetPropertyString(parameterTypeData, "name"); - // If there is no type for the paramter, we expect it is System.Object + // If there is no type for the parameter, we expect it is System.Object if (string.IsNullOrEmpty(parameterType)) { parameterType = "object"; diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs index 822e4c05026..3d3613c1860 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs @@ -128,7 +128,7 @@ internal void BuildParagraph() } /// <summary> - /// Highlights all ocurrences of <paramref name="search"/>. + /// Highlights all occurrences of <paramref name="search"/>. /// This is called after all calls to AddText have been made. /// </summary> /// <param name="search">Search string.</param> @@ -249,7 +249,7 @@ private static void AddInline(Paragraph currentParagraph, bool currentBold, bool /// </summary> /// <param name="currentSpanIndex">Current index within <paramref name="allSpans"/>.</param> /// <param name="currentSpan">Current span within <paramref name="allSpans"/>.</param> - /// <param name="caracterPosition">Caracter position. This comes from a position within this.textBuilder.</param> + /// <param name="caracterPosition">Character position. This comes from a position within this.textBuilder.</param> /// <param name="allSpans">The collection of spans. This is either this.boldSpans or this.highlightedSpans.</param> private static void MoveSpanToPosition(ref int currentSpanIndex, ref TextSpan? currentSpan, int caracterPosition, List<TextSpan> allSpans) { diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs index e71a27bac8b..6c42047b1b7 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs @@ -56,7 +56,7 @@ internal Run MoveAndHighlightNextNextMatch(bool forward, TextPointer caretPositi } // If the caret is in the end of a highlight we move to the adjacent run - // It has to be in the end because if there is a match at the begining of the file + // It has to be in the end because if there is a match at the beginning of the file // and the caret has not been touched (so it is in the beginning of the file too) // we want to highlight this first match. // Considering the caller allways set the caret to the end of the highlight diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs index 2b33153a983..3e811368476 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs @@ -9,7 +9,7 @@ namespace Microsoft.Management.UI.Internal { /// <summary> - /// The FilterEvaluator class is responsible for allowing the registeration of + /// The FilterEvaluator class is responsible for allowing the registration of /// the FilterExpressionProviders and producing a FilterExpression composed of /// the FilterExpression returned from the providers. /// </summary> diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IEvaluate.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IEvaluate.cs index f83f6b377aa..161f14d4537 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IEvaluate.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IEvaluate.cs @@ -13,7 +13,7 @@ public interface IEvaluate { /// <summary> /// Gets a values indicating whether the supplied item has meet the - /// criteria rule specificed by the rule. + /// criteria rule specified by the rule. /// </summary> /// <param name="item"> /// The item to evaluate. diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs index cbafae9d283..7f9a5afcc4c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs @@ -25,7 +25,7 @@ public FilterRule Rule } /// <summary> - /// Gets a string that indentifies which group this + /// Gets a string that identifies which group this /// item belongs to. /// </summary> public string GroupId diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs index 78a8da29c65..868e17d85c4 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs @@ -296,7 +296,7 @@ protected override void OnItemsSourceChanged(System.Collections.IEnumerable oldV this.itemsSourceIsEmpty = this.ItemsSource != null && this.ItemsSource.GetEnumerator().MoveNext() == false; - // A view can be created if there is data to auto-generate columns, or columns are added programatically \\ + // A view can be created if there is data to auto-generate columns, or columns are added programmatically \\ bool canCreateView = (this.ItemsSource != null) && (this.itemsSourceIsEmpty == false || this.AutoGenerateColumns == false); diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs index 13f3b8507d9..33908ea732f 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs @@ -465,7 +465,7 @@ public void OpenHelpWindow() } /// <summary> - /// Determins whether current command name and a specifed ParameterSetName have same name. + /// Determines whether current command name and a specified ParameterSetName have same name. /// </summary> /// <param name="name">The name of ShareParameterSet.</param> /// <returns>Return true is ShareParameterSet. Else return false.</returns> diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs index 38925e458a9..95e45123d22 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs @@ -373,7 +373,7 @@ internal void RefreshFilteredCommands(string filter) } /// <summary> - /// Callled in response to a GUI event that requires the command to be run. + /// Called in response to a GUI event that requires the command to be run. /// </summary> internal void OnRunSelectedCommand() { diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs index f599750d7f9..1521aab7742 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs @@ -39,7 +39,7 @@ public class ParameterSetViewModel : INotifyPropertyChanged /// Initializes a new instance of the ParameterSetViewModel class. /// </summary> /// <param name="name">The name of the parameterSet.</param> - /// <param name="parameters">The array parametes of the parameterSet.</param> + /// <param name="parameters">The array parameters of the parameterSet.</param> [SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Justification = "this type is internal, made public only for WPF Binding")] public ParameterSetViewModel( string name, diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs index 5d57816c0e7..845179009f7 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs @@ -245,7 +245,7 @@ public enum PerformanceCounterType /// A difference counter that shows the change in the measured attribute /// between the two most recent sample intervals. It is the same as the /// CounterDelta32 counter type except that is uses larger fields to - /// accomodate larger values.</summary> + /// accommodate larger values.</summary> CounterDelta64 = 4195584 } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs index c8ba1e7ea48..cfee0f78aa4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs @@ -41,7 +41,7 @@ public class TestJsonCommand : PSCmdlet public string Schema { get; set; } /// <summary> - /// Gets or sets path to the file containg schema to validate the JSON string against. + /// Gets or sets path to the file containing schema to validate the JSON string against. /// This is optional parameter. /// </summary> [Parameter(Position = 1, ParameterSetName = SchemaFileParameterSet)] diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs index 4deb6f5d50c..3906405d916 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs @@ -78,7 +78,7 @@ public static class UtilityResources public static string FileReadError { get { return UtilityCommonStrings.FileReadError; } } /// <summary> - /// The resource string used to indicate 'PATH:' in the formating header. + /// The resource string used to indicate 'PATH:' in the formatting header. /// </summary> public static string FormatHexPathPrefix { get { return UtilityCommonStrings.FormatHexPathPrefix; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 604582661a0..85860aa19e6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -132,7 +132,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet public virtual SwitchParameter AllowUnencryptedAuthentication { get; set; } /// <summary> - /// Gets or sets the Authentication property used to determin the Authentication method for the web session. + /// Gets or sets the Authentication property used to determine the Authentication method for the web session. /// Authentication does not work with UseDefaultCredentials. /// Authentication over unencrypted sessions requires AllowUnencryptedAuthentication. /// Basic: Requires Credential. diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index e54e7b02631..06d61548048 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -2715,7 +2715,7 @@ private bool HandleErrors(Exception e, string line, bool inBlockMode, ref String } else { - // an exception ocurred when the command was executed. Tell the user about it. + // an exception occurred when the command was executed. Tell the user about it. _parent.ReportException(e, _exec); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs index bca63be834b..41053ecea7a 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs @@ -457,7 +457,7 @@ public override } // if the new size will extend past the edge of screen buffer, then move the window position to try to - // accomodate that. + // accommodate that. ConsoleControl.SMALL_RECT r = bufferInfo.WindowRect; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs index b33d8f2e61c..dff3757259f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs @@ -411,7 +411,7 @@ private static NotificationType GetNotificationType() private enum NotificationType { /// <summary> - /// Turn off the udpate notification. + /// Turn off the update notification. /// </summary> Off = 0, diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs index 293cd1faf44..9713ac0b0b5 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -107,7 +107,7 @@ private unsafe void EtwRegister() } // - // implement Dispose Pattern to early deregister from ETW insted of waiting for + // implement Dispose Pattern to early deregister from ETW instead of waiting for // the finalizer to call deregistration. // Once the user is done with the provider it needs to call Close() or Dispose() // If neither are called the finalizer will unregister the provider anyway diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 69f24c243cc..b525098ac6c 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -7396,7 +7396,7 @@ public int Compare(PSObject x, PSObject y) } /// <summary> - /// This class is very similar to the restricted langauge checker, but it is meant to allow more things, yet still + /// This class is very similar to the restricted language checker, but it is meant to allow more things, yet still /// be considered "safe", at least in the sense that tab completion can rely on it to not do bad things. The primary /// use is for intellisense where you don't want to run arbitrary code, but you do want to know the values /// of various expressions so you can get the members. diff --git a/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs b/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs index d211cb532a7..d603436790c 100644 --- a/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs +++ b/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs @@ -66,7 +66,7 @@ static SubsystemManager() /// directly interacting with the implementation proxy object of `IPrediction`. /// </remarks> /// <typeparam name="TConcreteSubsystem">The concrete subsystem base type.</typeparam> - /// <returns>The most recently registered implmentation object of the concrete subsystem.</returns> + /// <returns>The most recently registered implementation object of the concrete subsystem.</returns> internal static TConcreteSubsystem? GetSubsystem<TConcreteSubsystem>() where TConcreteSubsystem : class, ISubsystem { @@ -87,7 +87,7 @@ static SubsystemManager() /// Return an empty collection when the given subsystem is not registered. /// </summary> /// <typeparam name="TConcreteSubsystem">The concrete subsystem base type.</typeparam> - /// <returns>A readonly collection of all implmentation objects registered for the concrete subsystem.</returns> + /// <returns>A readonly collection of all implementation objects registered for the concrete subsystem.</returns> internal static ReadOnlyCollection<TConcreteSubsystem> GetSubsystems<TConcreteSubsystem>() where TConcreteSubsystem : class, ISubsystem { diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 04ce777964e..49763f43a13 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -2191,7 +2191,7 @@ internal int StartSSHProcess( startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-i ""{0}""", this.KeyFilePath)); } - // pass "-l login_name" commmand line argument to ssh if UserName is set + // pass "-l login_name" command line argument to ssh if UserName is set // if UserName is not set, then ssh will use User from ssh_config if defined else the environment user by default if (!string.IsNullOrEmpty(this.UserName)) { diff --git a/src/System.Management.Automation/engine/remoting/common/RunspacePoolStateInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspacePoolStateInfo.cs index e863a7c795e..fb4807351c3 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspacePoolStateInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspacePoolStateInfo.cs @@ -17,7 +17,7 @@ namespace System.Management.Automation public sealed class RunspacePoolStateInfo { /// <summary> - /// State of the runspace pool when this event occured. + /// State of the runspace pool when this event occurred. /// </summary> public RunspacePoolState State { get; } diff --git a/src/System.Management.Automation/help/DscResourceHelpProvider.cs b/src/System.Management.Automation/help/DscResourceHelpProvider.cs index c29ed02b456..42412926a47 100644 --- a/src/System.Management.Automation/help/DscResourceHelpProvider.cs +++ b/src/System.Management.Automation/help/DscResourceHelpProvider.cs @@ -279,7 +279,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier, string com } if (e != null) - s_tracer.WriteLine("Error occured in DscResourceHelpProvider {0}", e.Message); + s_tracer.WriteLine("Error occurred in DscResourceHelpProvider {0}", e.Message); if (reportErrors && (e != null)) { diff --git a/src/System.Management.Automation/help/MamlNode.cs b/src/System.Management.Automation/help/MamlNode.cs index fe4e803a294..8f8df05bb79 100644 --- a/src/System.Management.Automation/help/MamlNode.cs +++ b/src/System.Management.Automation/help/MamlNode.cs @@ -123,7 +123,7 @@ internal PSObject PSObject /// </atomicXml> /// In this case, an PSObject that wraps string "atomic xml text" will be returned with following properties /// attribute => name - /// 3. Composite xml, which is an xmlNode with structured child nodes, but not a special case for Maml formating. + /// 3. Composite xml, which is an xmlNode with structured child nodes, but not a special case for Maml formatting. /// <compositeXml attribute="attribute"> /// <singleChildNode> /// single child node text diff --git a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs index f5d299ecfd6..1a9935cb1ad 100644 --- a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs +++ b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs @@ -567,7 +567,7 @@ internal void SeekItemsBackward(int backCount) (e is UnauthorizedAccessException) || (e is ArgumentNullException)) { - // Exception contains specific message about the error occured and so no need for errordetails. + // Exception contains specific message about the error occurred and so no need for errordetails. _provider.WriteError(new ErrorRecord(e, "GetContentReaderIOError", ErrorCategory.ReadError, _path)); } else diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 02d9708d045..e95669c2961 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -1359,7 +1359,7 @@ protected override void GetItem(string path) } catch (IOException ioError) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. ErrorRecord er = new ErrorRecord(ioError, "GetItemIOError", ErrorCategory.ReadError, path); WriteError(er); } @@ -2250,7 +2250,7 @@ protected override void RenameItem( } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "RenameItemIOError", ErrorCategory.WriteError, path)); } catch (UnauthorizedAccessException accessException) @@ -2362,7 +2362,7 @@ protected override void NewItem( } catch (IOException exception) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(exception, "NewItemIOError", ErrorCategory.WriteError, path)); } catch (UnauthorizedAccessException accessException) @@ -2858,7 +2858,7 @@ private void CreateDirectory(string path, bool streamOutput) // Ignore the error if force was specified if (!Force) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "CreateDirectoryIOError", ErrorCategory.WriteError, path)); } } @@ -2933,7 +2933,7 @@ private bool CreateIntermediateDirectories(string path) } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "CreateIntermediateDirectoriesIOError", ErrorCategory.WriteError, path)); } catch (UnauthorizedAccessException accessException) @@ -3076,7 +3076,7 @@ protected override void RemoveItem(string path, bool recurse) } catch (IOException exception) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(exception, "RemoveItemIOError", ErrorCategory.WriteError, path)); } catch (UnauthorizedAccessException accessException) @@ -3925,7 +3925,7 @@ private void CopyDirectoryInfoItem( } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "CopyDirectoryInfoItemIOError", ErrorCategory.WriteError, file)); } catch (UnauthorizedAccessException accessException) @@ -3956,7 +3956,7 @@ private void CopyDirectoryInfoItem( } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "CopyDirectoryInfoItemIOError", ErrorCategory.WriteError, childDir)); } catch (UnauthorizedAccessException accessException) @@ -5254,7 +5254,7 @@ protected override string NormalizeRelativePath( } catch (IOException ioError) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioError, "NormalizeRelativePathIOError", ErrorCategory.ReadError, path)); break; } @@ -5898,7 +5898,7 @@ protected override void MoveItem( } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "MoveItemIOError", ErrorCategory.WriteError, path)); } catch (UnauthorizedAccessException accessException) @@ -6011,7 +6011,7 @@ private void MoveFileInfoItem( (exception is ArgumentNullException) || (exception is IOException)) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "MoveFileInfoItemIOError", ErrorCategory.WriteError, destfile)); } else @@ -6020,13 +6020,13 @@ private void MoveFileInfoItem( } else { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "MoveFileInfoItemIOError", ErrorCategory.WriteError, file)); } } else { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "MoveFileInfoItemIOError", ErrorCategory.WriteError, file)); } } @@ -6097,7 +6097,7 @@ private void MoveDirectoryInfoItem( } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "MoveDirectoryItemIOError", ErrorCategory.WriteError, directory)); } } @@ -6259,7 +6259,7 @@ public void GetProperty(string path, Collection<string> providerSpecificPickList } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "GetPropertyIOError", ErrorCategory.ReadError, path)); } catch (UnauthorizedAccessException accessException) @@ -6559,7 +6559,7 @@ public void ClearProperty( } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "ClearPropertyIOError", ErrorCategory.WriteError, path)); } } @@ -6739,7 +6739,7 @@ public IContentReader GetContentReader(string path) } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "GetContentReaderIOError", ErrorCategory.ReadError, path)); } catch (System.Security.SecurityException securityException) @@ -6879,7 +6879,7 @@ public IContentWriter GetContentWriter(string path) } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "GetContentWriterIOError", ErrorCategory.WriteError, path)); } catch (System.Security.SecurityException securityException) @@ -7045,7 +7045,7 @@ public void ClearContent(string path) } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "ClearContentIOError", ErrorCategory.WriteError, path)); } catch (UnauthorizedAccessException accessException) @@ -7177,7 +7177,7 @@ private static class NativeMethods /// </param> /// <returns>If connection is established to the network resource /// then success is returned or else the error code describing the - /// type of failure that occured while establishing + /// type of failure that occurred while establishing /// the connection is returned.</returns> [DllImport("mpr.dll", CharSet = CharSet.Unicode)] internal static extern int WNetAddConnection2(ref NetResource netResource, byte[] password, string username, int flags); @@ -7197,7 +7197,7 @@ private static class NativeMethods /// if there are open files or jobs. /// </param> /// <returns>If connection is removed then success is returned or - /// else the error code describing the type of failure that occured while + /// else the error code describing the type of failure that occurred while /// trying to remove the connection is returned. /// </returns> [DllImport("mpr.dll", CharSet = CharSet.Unicode)] From 7d53fbbdf7032c1f293da21108bd287cbe6e00db Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan <adityap@microsoft.com> Date: Tue, 17 Aug 2021 11:58:19 -0700 Subject: [PATCH 53/55] Update change logs for 7.0.7 and 7.1.4 (#15921) --- .spelling | 2 ++ CHANGELOG/7.0.md | 19 +++++++++++++++++++ CHANGELOG/7.1.md | 19 +++++++++++++++++++ 3 files changed, 40 insertions(+) diff --git a/.spelling b/.spelling index cd325a98394..20f3b23142f 100644 --- a/.spelling +++ b/.spelling @@ -1260,6 +1260,7 @@ ini package.json jcotton42 RPMs +PSDesiredStateConfiguration - CHANGELOG/preview.md Gimly jborean93 @@ -1371,6 +1372,7 @@ codesign release-BuildJson yml centos-7 +PSDesiredStateConfiguration - test/perf/benchmarks/README.md benchmarked BenchmarkDotNet diff --git a/CHANGELOG/7.0.md b/CHANGELOG/7.0.md index af21d0bd957..fe0eca4c5a7 100644 --- a/CHANGELOG/7.0.md +++ b/CHANGELOG/7.0.md @@ -1,5 +1,24 @@ # 7.0 Changelog +## [7.0.7] - 2021-08-12 + +### Build and Packaging Improvements + +<details> + +<summary> +Bump .NET SDK to 3.1.412 +</summary> + +<ul> +<li>Remove cat file from <code>PSDesiredStateConfiguration</code> module (Internal 16722)</li> +<li>Update .NET SDK to <code>3.1.412</code> (Internal 16717)</li> +</ul> + +</details> + +[7.0.7]: https://github.com/PowerShell/PowerShell/compare/v7.0.6...v7.0.7 + ## [7.0.6] - 2021-03-11 ### General Cmdlet Updates and Fixes diff --git a/CHANGELOG/7.1.md b/CHANGELOG/7.1.md index 86b7a478c30..91d00b70a49 100644 --- a/CHANGELOG/7.1.md +++ b/CHANGELOG/7.1.md @@ -1,5 +1,24 @@ # 7.1 Changelog +## [7.1.4] - 2021-08-12 + +### Build and Packaging Improvements + +<details> + +<summary> +Bump .NET SDK to version 5.0.400 +</summary> + +<ul> +<li>Remove the cat file from <code>PSDesiredStateConfiguration</code> module (Internal 16723)</li> +<li>Update .NET SDK version and other packages (Internal 16715)</li> +</ul> + +</details> + +[7.1.4]: https://github.com/PowerShell/PowerShell/compare/v7.1.3...v7.1.4 + ## [7.1.3] - 2021-03-11 ### Engine Updates and Fixes From 176303d172bcb0726e097ac5139de9f724ecec6b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 18 Aug 2021 14:06:30 +0500 Subject: [PATCH 54/55] Bump Microsoft.CodeAnalysis.NetAnalyzers (#15944) Bumps [Microsoft.CodeAnalysis.NetAnalyzers](https://github.com/dotnet/roslyn-analyzers) from 6.0.0-rc1.21413.4 to 6.0.0-rc2.21417.3. - [Release notes](https://github.com/dotnet/roslyn-analyzers/releases) - [Changelog](https://github.com/dotnet/roslyn-analyzers/blob/main/PostReleaseActivities.md) - [Commits](https://github.com/dotnet/roslyn-analyzers/commits) --- updated-dependencies: - dependency-name: Microsoft.CodeAnalysis.NetAnalyzers dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- Analyzers.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Analyzers.props b/Analyzers.props index 235daa43009..c8d452755b8 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,7 +1,7 @@ <Project> <ItemGroup> <PackageReference Include="DotNetAnalyzers.DocumentationAnalyzers" Version="1.0.0-beta.59" PrivateAssets="all" /> - <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="6.0.0-rc1.21413.4" PrivateAssets="all" /> + <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="6.0.0-rc2.21417.3" PrivateAssets="all" /> <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.354" PrivateAssets="all" /> </ItemGroup> </Project> From f7b3389331f3ca149d2a8c1f97cd14a8f5c6c4d7 Mon Sep 17 00:00:00 2001 From: Dongbo Wang <dongbow@microsoft.com> Date: Thu, 19 Aug 2021 23:48:32 +0000 Subject: [PATCH 55/55] Merged PR 16810: Update the changelog for 7.2.0-preview.9 Update the changelog for 7.2.0-preview.9 --- .spelling | 7 ++++ CHANGELOG/preview.md | 96 +++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 102 insertions(+), 1 deletion(-) diff --git a/.spelling b/.spelling index 20f3b23142f..02d1b7e2a9f 100644 --- a/.spelling +++ b/.spelling @@ -1367,6 +1367,13 @@ adamsitnik msixbundle PowerShell-Native#70 AppxManifest.xml +preview.9 +ArmaanMcleod +entrypoint +lselden +SethFalco +CodeQL +slowy07 - CHANGELOG/7.0.md codesign release-BuildJson diff --git a/CHANGELOG/preview.md b/CHANGELOG/preview.md index 305903ea24d..31443e0e6f7 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -1,5 +1,99 @@ # Current preview release +## [7.2.0-preview.9] - 2021-08-23 + +### Breaking Changes + +- Change the default value of `$PSStyle.OutputRendering` to `OutputRendering.Host` and remove `OutputRendering.Automatic` (#15882) +- Fix `CA1052` for public API to make classes static when they only have static methods (#15775) (Thanks @xtqqczze!) +- Update `pwsh.exe -File` to only accept `.ps1` script files on Windows (#15859) + +### Engine Updates and Fixes + +- Update .NET adapter to handle interface static members properly (#15908) +- Catch and handle unauthorized access exception when removing AppLocker test files (#15881) + +### General Cmdlet Updates and Fixes + +- Add `-PassThru` parameter to `Set-Clipboard` (#13713) (Thanks @ThomasNieto!) +- Add `-Encoding` parameter for `Tee-Object` (#12135) (Thanks @Peter-Schneider!) +- Update `ConvertTo-Csv` and `Export-Csv` to handle `IDictionary` objects (#11029) (Thanks @vexx32!) +- Update the parameters `-Exception` and `-ErrorRecord` for `Write-Error` to be position 0 (#13813) (Thanks @ThomasNieto!) +- Don't use `ArgumentList` when creating COM object with `New-Object` as it's not applicable to the COM parameter set (#15915) +- Fix `$PSStyle` list output to correctly show `TableHeader` (#15928) +- Remove the `PSImplicitRemotingBatching` experimental feature (#15863) +- Fix issue with `Get-Process -Module` failing to stop when it's piped to `Select-Object` (#15682) (Thanks @ArmaanMcleod!) +- Make the experimental features `PSUnixFileStat`, `PSCultureInvariantReplaceOperator`, `PSNotApplyErrorActionToStderr`, `PSAnsiRendering`, `PSAnsiProgressFeatureName` stable (#15864) +- Enhance `Remove-Item` to work with OneDrive (#15571) (Thanks @iSazonov!) +- Make global tool entrypoint class static (#15880) +- Update `ServerRemoteHost` version to be same as `PSVersion` (#15809) +- Make the initialization of `HttpKnownHeaderNames` thread safe (#15519) (Thanks @iSazonov!) +- `ConvertTo-Csv`: Quote fields with quotes and newlines when using `-UseQuotes AsNeeded` (#15765) (Thanks @lselden!) +- Forwarding progress stream changes from `Foreach-Object -Parallel` runspaces (#14271) (Thanks @powercode!) +- Add validation to `$PSStyle` to reject printable text when setting a property that only expects ANSI escape sequence (#15825) + +### Code Cleanup + +<details> + +<summary> + +<p>We thank the following contributors!</p> +<p>@xtqqczze</p> + +</summary> + +<ul> +<li>Avoid unneeded array allocation in module code (#14329) (Thanks @xtqqczze!)</li> +<li>Enable and fix analysis rules <code>CA1052</code>, <code>CA1067</code>, and <code>IDE0049</code> (#15840) (Thanks @xtqqczze!)</li> +<li>Avoid unnecessary allocation in formatting code (#15832) (Thanks @xtqqczze!)</li> +<li>Specify the analyzed API surface for all code quality rules (#15778) (Thanks @xtqqczze!)</li> +</ul> + +</details> + +### Tools + +- Enable `/rebase` to automatically rebase a PR (#15808) +- Update `.editorconfig` to not replace tabs with spaces in `.tsv` files (#15815) (Thanks @SethFalco!) +- Update PowerShell team members in the change log generation script (#15817) + +### Tests + +- Add more tests to validate the current command error handling behaviors (#15919) +- Make `Measure-Object` property test independent of the file system (#15879) +- Add more information when a `syslog` parsing error occurs (#15857) +- Harden logic when looking for `syslog` entries to be sure that we select based on the process id (#15841) + +### Build and Packaging Improvements + +<details> + +<summary> + +<p>We thank the following contributors!</p> +<p>@xtqqczze</p> + +</summary> + +<ul> +<li>Disable implicit namespace imports for test projects (#15895)</li> +<li>Update language version to 10 and fix related issues (#15886)</li> +<li>Update <code>CodeQL</code> workflow to use Ubuntu 18.04 (#15868)</li> +<li>Bump the version of various packages (#15944, #15934, #15935, #15891, #15812, #15822) (Thanks @xtqqczze!)</li> +</ul> + +</details> + +### Documentation and Help Content + +- Update `README` and `metadata files` for release `v7.2.0-preview.8` (#15819) +- Update change logs for 7.0.7 and 7.1.4 (#15921) +- Fix spelling in XML docs (#15939) (Thanks @slowy07!) +- Update PowerShell Committee members (#15837) + +[7.2.0-preview.9]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.8...v7.2.0-preview.9 + ## [7.2.0-preview.8] - 2021-07-22 ### Engine Updates and Fixes @@ -86,7 +180,7 @@ Update .NET to version <code>v6.0.0-preview.6</code> <li>Enable ARM64 packaging for macOS (#15768)</li> <li>Make Microsoft Update opt-out/in check boxes work (#15784)</li> <li>Add Microsoft Update opt out to MSI install (#15727)</li> -<li>Bump <code>NJsonSchema</code> from <code>10.4.4</code> to <code>10.4.5</code> (#15769) (Thanks @dependabot[bot]!)</li> +<li>Bump <code>NJsonSchema</code> from <code>10.4.4</code> to <code>10.4.5</code> (#15769)</li> <li>Fix computation of SHA512 checksum (#15736)</li> <li>Update the script to use quality parameter for <code>dotnet-install</code> (#15731)</li> <li>Generate SHA512 checksum file for all packages (#15678)</li>