From 608c61435845fd53150e88239ad2399a99c887e5 Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 10:52:52 -0500 Subject: [PATCH 01/24] Removed IncludeRules from settings that overrides defaults By having this defined, we override the value `IncludeDefaultRules = $true` --- PSScriptAnalyzerSettings.psd1 | 9 --------- 1 file changed, 9 deletions(-) diff --git a/PSScriptAnalyzerSettings.psd1 b/PSScriptAnalyzerSettings.psd1 index 6897a72ea8..b031bbdaaa 100644 --- a/PSScriptAnalyzerSettings.psd1 +++ b/PSScriptAnalyzerSettings.psd1 @@ -6,15 +6,6 @@ 'PSAvoidUsingWriteHost' ) - IncludeRules = @( - 'PSPlaceOpenBrace', - 'PSPlaceCloseBrace', - 'PSUseConsistentWhitespace', - 'PSUseConsistentIndentation', - 'PSAlignAssignmentStatement', - 'PSUseCorrectCasing' - ) - Rules = @{ PSPlaceOpenBrace = @{ Enable = $true From 0aba0e1fca00c52b9a1f42461c7c982daa410091 Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 10:59:28 -0500 Subject: [PATCH 02/24] Adding PSReviewUnusedParameter to exclude rule and removed overrides --- .build/BuildFunctions/Get-EmbeddedFileList.ps1 | 1 - Diagnostics/ExchangeLogCollector/ExchangeLogCollector.ps1 | 1 - Diagnostics/ExchangeLogCollector/extern/Start-JobManager.ps1 | 1 - M365/src/DLT365Groupsupgrade.ps1 | 1 - PSScriptAnalyzerSettings.psd1 | 3 ++- Performance/ExPerfAnalyzer.ps1 | 1 - .../src/SourceSideValidations/Get-BadPermissionJob.ps1 | 1 - Search/Troubleshoot-ModernSearch.ps1 | 1 - Security/src/EOMT.ps1 | 1 - Security/src/ExchangeMitigations.ps1 | 1 - Setup/FixInstallerCache/FixInstallerCache.ps1 | 1 - Setup/SetupAssist/SetupAssist.ps1 | 1 - Setup/SetupLogReviewer/SetupLogReviewer.ps1 | 1 - 13 files changed, 2 insertions(+), 13 deletions(-) diff --git a/.build/BuildFunctions/Get-EmbeddedFileList.ps1 b/.build/BuildFunctions/Get-EmbeddedFileList.ps1 index 2645b3d893..d06670210b 100644 --- a/.build/BuildFunctions/Get-EmbeddedFileList.ps1 +++ b/.build/BuildFunctions/Get-EmbeddedFileList.ps1 @@ -11,7 +11,6 @@ function Get-EmbeddedFileList { [CmdletBinding()] [OutputType([string[]])] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', 'FilesAlreadyAdded', Justification = 'Incorrect rule result')] param ( [Parameter()] [string] diff --git a/Diagnostics/ExchangeLogCollector/ExchangeLogCollector.ps1 b/Diagnostics/ExchangeLogCollector/ExchangeLogCollector.ps1 index 27887ce6bb..e72c33cf18 100644 --- a/Diagnostics/ExchangeLogCollector/ExchangeLogCollector.ps1 +++ b/Diagnostics/ExchangeLogCollector/ExchangeLogCollector.ps1 @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'All Parameters are used in other functions of the script')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Value is used')] [CmdletBinding()] Param ( diff --git a/Diagnostics/ExchangeLogCollector/extern/Start-JobManager.ps1 b/Diagnostics/ExchangeLogCollector/extern/Start-JobManager.ps1 index f014b32e4c..aeb474872a 100644 --- a/Diagnostics/ExchangeLogCollector/extern/Start-JobManager.ps1 +++ b/Diagnostics/ExchangeLogCollector/extern/Start-JobManager.ps1 @@ -5,7 +5,6 @@ #v21.01.22.2234 Function Start-JobManager { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'I prefer Start here')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'Removed unneeded functions')] [CmdletBinding()] param( [Parameter(Mandatory = $true)][array]$ServersWithArguments, diff --git a/M365/src/DLT365Groupsupgrade.ps1 b/M365/src/DLT365Groupsupgrade.ps1 index 5f6902c1fb..45cf764a8b 100644 --- a/M365/src/DLT365Groupsupgrade.ps1 +++ b/M365/src/DLT365Groupsupgrade.ps1 @@ -93,7 +93,6 @@ Function Debugdirsync { } #Check if Distribution Group can't be upgraded because EmailAddressPolicyViolated Function Debugmatchingeap { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'Incorrect rule result')] param( [Parameter(Mandatory = $true)] [PScustomobject]$Distgroup diff --git a/PSScriptAnalyzerSettings.psd1 b/PSScriptAnalyzerSettings.psd1 index b031bbdaaa..7492809f51 100644 --- a/PSScriptAnalyzerSettings.psd1 +++ b/PSScriptAnalyzerSettings.psd1 @@ -3,7 +3,8 @@ IncludeDefaultRules = $true ExcludeRules = @( - 'PSAvoidUsingWriteHost' + 'PSAvoidUsingWriteHost', + 'PSReviewUnusedParameter' ) Rules = @{ diff --git a/Performance/ExPerfAnalyzer.ps1 b/Performance/ExPerfAnalyzer.ps1 index 7b3211c79c..09da3f323d 100644 --- a/Performance/ExPerfAnalyzer.ps1 +++ b/Performance/ExPerfAnalyzer.ps1 @@ -2,7 +2,6 @@ # Licensed under the MIT License. [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Vars are in use')] -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'Parameters are in use')] [CmdletBinding()] Param( #[Parameter(Mandatory=$true,ParameterSetName="FileDirectory")][string]$PerfmonFileDirectory, diff --git a/PublicFolders/src/SourceSideValidations/Get-BadPermissionJob.ps1 b/PublicFolders/src/SourceSideValidations/Get-BadPermissionJob.ps1 index 260c07d4fc..27c354f57a 100644 --- a/PublicFolders/src/SourceSideValidations/Get-BadPermissionJob.ps1 +++ b/PublicFolders/src/SourceSideValidations/Get-BadPermissionJob.ps1 @@ -3,7 +3,6 @@ function Get-BadPermissionJob { [CmdletBinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'Incorrect rule result')] param ( [Parameter(Position = 0)] [string] diff --git a/Search/Troubleshoot-ModernSearch.ps1 b/Search/Troubleshoot-ModernSearch.ps1 index 47bd7b71ca..2c36ca3f41 100644 --- a/Search/Troubleshoot-ModernSearch.ps1 +++ b/Search/Troubleshoot-ModernSearch.ps1 @@ -2,7 +2,6 @@ # Licensed under the MIT License. #Exchange On Prem Script to help assist with determining why search might not be working on an Exchange 2019+ Server -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'Parameter is used')] [CmdletBinding(DefaultParameterSetName = "SubjectAndFolder")] param( [Parameter(Mandatory = $true, ParameterSetName = "SubjectAndFolder")] diff --git a/Security/src/EOMT.ps1 b/Security/src/EOMT.ps1 index 07605e3749..a810b8b858 100644 --- a/Security/src/EOMT.ps1 +++ b/Security/src/EOMT.ps1 @@ -45,7 +45,6 @@ https://aka.ms/privacy #> -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'Invalid rule result')] [Cmdletbinding()] param ( [switch]$RunFullScan, diff --git a/Security/src/ExchangeMitigations.ps1 b/Security/src/ExchangeMitigations.ps1 index c8487c7157..3d20b71aa7 100644 --- a/Security/src/ExchangeMitigations.ps1 +++ b/Security/src/ExchangeMitigations.ps1 @@ -107,7 +107,6 @@ #> [CmdLetBinding()] -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'Incorrect rule result')] param( [switch]$ApplyAllMitigations, [switch]$ApplyBackendCookieMitigation, diff --git a/Setup/FixInstallerCache/FixInstallerCache.ps1 b/Setup/FixInstallerCache/FixInstallerCache.ps1 index 90d4ed3af3..622ffd5c45 100644 --- a/Setup/FixInstallerCache/FixInstallerCache.ps1 +++ b/Setup/FixInstallerCache/FixInstallerCache.ps1 @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'Parameters are being used')] [CmdletBinding(DefaultParameterSetName = "CopyFromCu")] param( [Parameter(Mandatory = $true, ParameterSetName = "CopyFromCu")] diff --git a/Setup/SetupAssist/SetupAssist.ps1 b/Setup/SetupAssist/SetupAssist.ps1 index 2e9c704a8f..36e13bb66c 100644 --- a/Setup/SetupAssist/SetupAssist.ps1 +++ b/Setup/SetupAssist/SetupAssist.ps1 @@ -6,7 +6,6 @@ # # TODO: Add AD Object Permissions check # -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'Parameter is used')] [CmdletBinding()] param( [switch]$OtherWellKnownObjects diff --git a/Setup/SetupLogReviewer/SetupLogReviewer.ps1 b/Setup/SetupLogReviewer/SetupLogReviewer.ps1 index cbe856858c..33de9fd9db 100644 --- a/Setup/SetupLogReviewer/SetupLogReviewer.ps1 +++ b/Setup/SetupLogReviewer/SetupLogReviewer.ps1 @@ -6,7 +6,6 @@ # # Use the DelegateSetup switch if the log is from a Delegated Setup and you are running into a Prerequisite Check issue # -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'Parameter is used')] [CmdletBinding(DefaultParameterSetName = "Main")] param( [Parameter(Mandatory = $true, From 7ba53dca628727e8470a2f447d6bb3fa5a189d9b Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 11:11:22 -0500 Subject: [PATCH 03/24] Added OutputType --- .build/BuildFunctions/Test-PathCaseSensitive.ps1 | 1 + .../Troubleshoot-ModernSearch/StoreQuery/StoreQueryFunctions.ps1 | 1 + 2 files changed, 2 insertions(+) diff --git a/.build/BuildFunctions/Test-PathCaseSensitive.ps1 b/.build/BuildFunctions/Test-PathCaseSensitive.ps1 index c9dc3e7abb..606ba6e8a1 100644 --- a/.build/BuildFunctions/Test-PathCaseSensitive.ps1 +++ b/.build/BuildFunctions/Test-PathCaseSensitive.ps1 @@ -3,6 +3,7 @@ function Test-PathCaseSensitive { [CmdletBinding()] + [OutputType("System.Boolean")] param ( [Parameter(Mandatory = $true)] [string] diff --git a/Search/Troubleshoot-ModernSearch/StoreQuery/StoreQueryFunctions.ps1 b/Search/Troubleshoot-ModernSearch/StoreQuery/StoreQueryFunctions.ps1 index f1b5c6412d..523253cea2 100644 --- a/Search/Troubleshoot-ModernSearch/StoreQuery/StoreQueryFunctions.ps1 +++ b/Search/Troubleshoot-ModernSearch/StoreQuery/StoreQueryFunctions.ps1 @@ -93,6 +93,7 @@ Function AddToWhere { Function InvokeGetStoreQuery { [CmdletBinding()] + [OutputType("System.Object[]")] param( [Parameter(ValueFromPipeline = $true, Mandatory = $true)] [object]$Query From 687a56756b0d26dd9c135c85f333dd135e836d21 Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 11:17:41 -0500 Subject: [PATCH 04/24] Addressed Get-Encoding being an alias --- .build/CodeFormatter.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.build/CodeFormatter.ps1 b/.build/CodeFormatter.ps1 index 9349cc2602..4ef5ba5494 100644 --- a/.build/CodeFormatter.ps1 +++ b/.build/CodeFormatter.ps1 @@ -27,7 +27,7 @@ $filesFailed = $false # MD files must NOT have a BOM Get-ChildItem -Path $repoRoot -Include *.md -Recurse | ForEach-Object { - $encoding = Get-Encoding $_ + $encoding = Get-PsOneEncoding $_ if ($encoding.BOM) { Write-Warning "MD file has BOM: $($_.FullName)" if ($Save) { @@ -47,7 +47,7 @@ Get-ChildItem -Path $repoRoot -Include *.md -Recurse | ForEach-Object { foreach ($file in $scriptFiles) { # PS1 files must have a BOM - $encoding = Get-Encoding $file + $encoding = Get-PsOneEncoding $file if (-not $encoding.BOM) { Write-Warning "File has no BOM: $file" if ($Save) { From edf26a0e2c0cbd97f2c4c1941b86d1f0fd9bda6a Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 11:20:53 -0500 Subject: [PATCH 05/24] Fixed bug in analyzer engine --- Diagnostics/HealthChecker/Analyzer/Invoke-AnalyzerEngine.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Diagnostics/HealthChecker/Analyzer/Invoke-AnalyzerEngine.ps1 b/Diagnostics/HealthChecker/Analyzer/Invoke-AnalyzerEngine.ps1 index edbcf30959..48f9e47286 100644 --- a/Diagnostics/HealthChecker/Analyzer/Invoke-AnalyzerEngine.ps1 +++ b/Diagnostics/HealthChecker/Analyzer/Invoke-AnalyzerEngine.ps1 @@ -1451,7 +1451,7 @@ Function Invoke-AnalyzerEngine { -DisplayWriteType $shaDisplayWriteType ` -AnalyzedInformation $analyzedResults - $analyzedResultsults = Add-AnalyzedResultInformation -Name "Signature Hash Algorithm" -Details $certificate.SignatureHashAlgorithm ` + $analyzedResults = Add-AnalyzedResultInformation -Name "Signature Hash Algorithm" -Details $certificate.SignatureHashAlgorithm ` -DisplayGroupingKey $keySecuritySettings ` -DisplayCustomTabNumber 2 ` -DisplayWriteType $shaDisplayWriteType ` From 3a1400cc230a50c409624801d73121729d8d5e7d Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 11:32:25 -0500 Subject: [PATCH 06/24] Addressed PSUseDeclaredVarsMoreThanAssignments --- Admin/Get-SimpleAuditLogReport.ps1 | 5 ++--- .../Write/Write-CheckSearchProcessState.ps1 | 1 - Shared/Tests/Invoke-ScriptBlockHandler.Tests.ps1 | 14 ++++++++++---- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/Admin/Get-SimpleAuditLogReport.ps1 b/Admin/Get-SimpleAuditLogReport.ps1 index 173af57e8f..ca67c8a65c 100644 --- a/Admin/Get-SimpleAuditLogReport.ps1 +++ b/Admin/Get-SimpleAuditLogReport.ps1 @@ -87,9 +87,6 @@ Process { # Deal with each object in the input $searchresults | ForEach-Object { - # Reset the result object - $Result = New-Object PSObject - # Get the alias of the User that ran the command $user = ($_.caller.split("/"))[-1] @@ -183,6 +180,8 @@ Process { # Get just the name of the cmdlet that was run [string]$cmdlet = $_.CmdletName + # Reset the result object + $Result = New-Object PSObject # Build the result object to return our values $Result | Add-Member -MemberType NoteProperty -Value $user -Name Caller $Result | Add-Member -MemberType NoteProperty -Value $cmdlet -Name Cmdlet diff --git a/Search/Troubleshoot-ModernSearch/Write/Write-CheckSearchProcessState.ps1 b/Search/Troubleshoot-ModernSearch/Write/Write-CheckSearchProcessState.ps1 index 8b16e31b0f..3774e70b68 100644 --- a/Search/Troubleshoot-ModernSearch/Write/Write-CheckSearchProcessState.ps1 +++ b/Search/Troubleshoot-ModernSearch/Write/Write-CheckSearchProcessState.ps1 @@ -14,7 +14,6 @@ Function Write-CheckSearchProcessState { $thirdPartyModuleFound = $false $checksPassed = $true $status = "Passed" - $processNotStarted = $false } process { diff --git a/Shared/Tests/Invoke-ScriptBlockHandler.Tests.ps1 b/Shared/Tests/Invoke-ScriptBlockHandler.Tests.ps1 index 6f071d15c2..9de1058b5e 100644 --- a/Shared/Tests/Invoke-ScriptBlockHandler.Tests.ps1 +++ b/Shared/Tests/Invoke-ScriptBlockHandler.Tests.ps1 @@ -1,6 +1,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. - +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', Justification = 'Incorrect rule result')] +[CmdletBinding()] +param() BeforeAll { $parent = Split-Path -Parent $PSScriptRoot $scriptName = "Invoke-ScriptBlockHandler.ps1" @@ -100,7 +102,7 @@ Describe "Testing $scriptName" { $result = Invoke-ScriptBlockHandler -ComputerName "BadComputerName" ` -ScriptBlock { [System.Environment]::ProcessorCount } ` -ScriptBlockDescription "Getting Processor Count" - $results | Should -Be $null + $result | Should -Be $null Assert-MockCalled -CommandName Write-Verbose -Exactly 1 -ParameterFilter { $Message -like "*Getting Processor Count" } Test-VerboseOutput -Local $false @@ -145,23 +147,27 @@ Describe "Testing $scriptName" { } It "Processor Count" { - $myValue = [System.Environment]::ProcessorCount $results = Invoke-ScriptBlockHandler -ComputerName $myFQDN ` -ScriptBlock { [System.Environment]::ProcessorCount } ` -ScriptBlockDescription "Getting Processor Count" + #not able to properly test because of Admin + $results | Should -Be $null + Assert-MockCalled -CommandName Write-Verbose -Exactly 1 -ParameterFilter { $Message -like "*Getting Processor Count" } Assert-MockCalled -CommandName Invoke-Command -Exactly 1 Test-VerboseOutput -Local $false } It "Passing Argument List" { $httpProxyPath32 = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections" - $testResults = Get-WinHttpSettings $httpProxyPath32 $results = Invoke-ScriptBlockHandler -ComputerName $myFQDN ` -ScriptBlock ${Function:Get-WinHttpSettings} ` -ScriptBlockDescription "Getting Http Proxy Settings 32 bit" ` -ArgumentList $httpProxyPath32 + #not able to properly test because of Admin + $results | Should -Be $null + Assert-MockCalled -CommandName Write-Verbose -Exactly 1 -ParameterFilter { $Message -like "*Getting Http Proxy Settings 32 bit" } Assert-MockCalled -CommandName Invoke-Command -Exactly 1 Test-VerboseOutput -Local $false -Without $false From fc185af86c1f0ece4df9ffa16e74e7ac2c2562dc Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 11:32:36 -0500 Subject: [PATCH 07/24] Fixed Pester Test --- Shared/Tests/Get-ServerPendingReboot.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Shared/Tests/Get-ServerPendingReboot.Tests.ps1 b/Shared/Tests/Get-ServerPendingReboot.Tests.ps1 index eec99a4e26..9cfb5d3be2 100644 --- a/Shared/Tests/Get-ServerPendingReboot.Tests.ps1 +++ b/Shared/Tests/Get-ServerPendingReboot.Tests.ps1 @@ -3,7 +3,7 @@ BeforeAll { $parent = Split-Path -Parent $PSScriptRoot - $scriptName = "Get-ServerPendingReboot.ps1" + $scriptName = "Get-ServerRebootPending.ps1" . "$parent\$scriptName" From 04193e13be0acc641d895ad1043ef2dfeba119b4 Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 11:34:06 -0500 Subject: [PATCH 08/24] Addressed PSAvoidTrailingWhitespace --- Diagnostics/HealthChecker/Helpers/Test-RequiresServerFqdn.ps1 | 2 +- .../ManagedAvailabilityTroubleshooter.ps1 | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Diagnostics/HealthChecker/Helpers/Test-RequiresServerFqdn.ps1 b/Diagnostics/HealthChecker/Helpers/Test-RequiresServerFqdn.ps1 index 2f600e50fd..4eb52959b6 100644 --- a/Diagnostics/HealthChecker/Helpers/Test-RequiresServerFqdn.ps1 +++ b/Diagnostics/HealthChecker/Helpers/Test-RequiresServerFqdn.ps1 @@ -20,7 +20,7 @@ Function Test-RequiresServerFqdn { try { Invoke-Command -ComputerName $Script:Server -ScriptBlock { Get-Date | Out-Null } -ErrorAction Stop - Write-Verbose "Connected successfully using: $($Script:Server)." + Write-Verbose "Connected successfully using: $($Script:Server)." } catch { Invoke-CatchActions if ($tempServerName.Count -gt 1) { diff --git a/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 b/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 index 8028024f43..3d5aca0da7 100644 --- a/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 +++ b/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 @@ -1187,4 +1187,4 @@ if ($Investigationchoose -eq 5) { } if (($Investigationchoose -eq 6) -and ($exchangeversion)) { CollectMaLogs $MyInvocation.MyCommand.Path -} +} From b7715e8b88424bbb8ff8071c5aa79dc3faf0458b Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 11:36:28 -0500 Subject: [PATCH 09/24] Addressed PSPossibleIncorrectComparisonWithNull --- .../ManagedAvailabilityTroubleshooter.ps1 | 2 +- .../Exchange/Get-MailboxStatisticsOnDatabase.ps1 | 2 +- Shared/Get-RemoteRegistryValue.ps1 | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 b/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 index 3d5aca0da7..9f984072c0 100644 --- a/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 +++ b/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 @@ -122,7 +122,7 @@ function InvestigateProbe { if ( -not ($ProbeInfo.TargetResource -eq "[null]")) { $probename2add += "/" + $ProbeInfo.TargetResource } } - if ($ProbeDetailsfullname -eq $null ) + if ($null -eq $ProbeDetailsfullname) { $ProbeDetailsfullname = $Probename = $probename2add } else { $ProbeNameAlreadyinthelist = $false diff --git a/Search/Troubleshoot-ModernSearch/Exchange/Get-MailboxStatisticsOnDatabase.ps1 b/Search/Troubleshoot-ModernSearch/Exchange/Get-MailboxStatisticsOnDatabase.ps1 index ff767d8d77..6dc700c703 100644 --- a/Search/Troubleshoot-ModernSearch/Exchange/Get-MailboxStatisticsOnDatabase.ps1 +++ b/Search/Troubleshoot-ModernSearch/Exchange/Get-MailboxStatisticsOnDatabase.ps1 @@ -18,7 +18,7 @@ Function Get-MailboxStatisticsOnDatabase { if ($_.DisplayName -notlike "SystemMailbox*" -and $_.DisplayName -notlike "*HealthMailbox-*" -and $_.MailboxTypeDetail.ToString() -ne "ArbitrationMailbox" -and - $_.DisconnectReason -eq $null) { + $null -eq $_.DisconnectReason) { $totalMailboxItems = $_.ItemCount + $_.AssociatedItemCount + $_.DeletedItemCount $totalBigFunnelItems = $_.BigFunnelIndexedCount + $_.BigFunnelPartiallyIndexedCount + $_.BigFunnelNotIndexedCount + ` diff --git a/Shared/Get-RemoteRegistryValue.ps1 b/Shared/Get-RemoteRegistryValue.ps1 index a1dffd7136..6e7cbcf849 100644 --- a/Shared/Get-RemoteRegistryValue.ps1 +++ b/Shared/Get-RemoteRegistryValue.ps1 @@ -44,7 +44,7 @@ Function Get-RemoteRegistryValue { $registryGetValue = $regSubKey.GetValue($GetValue) Write-Verbose "Finished running GetValue()" - if ($registryGetValue -ne $null -and + if ($null -ne $registryGetValue -and (-not ([System.String]::IsNullOrWhiteSpace($ValueType)))) { Write-Verbose "Validating ValueType $ValueType" $registryValueType = $regSubKey.GetValueKind($GetValue) From d142c862dc393e18d9ccf91b4e258358445c5743 Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 11:54:27 -0500 Subject: [PATCH 10/24] Addressed PSAvoidUsingWMICmdlet --- .../Exchange/Get-SearchProcessState.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/Search/Troubleshoot-ModernSearch/Exchange/Get-SearchProcessState.ps1 b/Search/Troubleshoot-ModernSearch/Exchange/Get-SearchProcessState.ps1 index 282f4fd1bb..280c8c2136 100644 --- a/Search/Troubleshoot-ModernSearch/Exchange/Get-SearchProcessState.ps1 +++ b/Search/Troubleshoot-ModernSearch/Exchange/Get-SearchProcessState.ps1 @@ -2,6 +2,7 @@ # Licensed under the MIT License. Function Get-SearchProcessState { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWMICmdlet', Justification = 'Cmdlet required')] [CmdletBinding()] param( [string]$ComputerName = $env:COMPUTERNAME From 2a9c5872b6eaee118c3dd7239cd7aa2e7357ca66 Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 11:58:24 -0500 Subject: [PATCH 11/24] Addressed PSUseProcessBlockForPipelineCommand --- .../StoreQuery/StoreQueryFunctions.ps1 | 107 ++++++++++-------- Shared/LoggerFunctions.ps1 | 13 ++- 2 files changed, 64 insertions(+), 56 deletions(-) diff --git a/Search/Troubleshoot-ModernSearch/StoreQuery/StoreQueryFunctions.ps1 b/Search/Troubleshoot-ModernSearch/StoreQuery/StoreQueryFunctions.ps1 index 523253cea2..da60555f51 100644 --- a/Search/Troubleshoot-ModernSearch/StoreQuery/StoreQueryFunctions.ps1 +++ b/Search/Troubleshoot-ModernSearch/StoreQuery/StoreQueryFunctions.ps1 @@ -8,12 +8,13 @@ Function ResetQueryInstances { [object] $Query ) - - $Query.IsUnlimited = $false - $Query.SelectPartQuery = [string]::Empty - $Query.FromPartQuery = [string]::Empty - $Query.WherePartQuery = [string]::Empty - $Query + process { + $Query.IsUnlimited = $false + $Query.SelectPartQuery = [string]::Empty + $Query.FromPartQuery = [string]::Empty + $Query.WherePartQuery = [string]::Empty + $Query + } } Function SetSelect { @@ -26,11 +27,12 @@ Function SetSelect { [Parameter(Mandatory = $true)] [string[]]$Value ) - - [string]$temp = $Value | - ForEach-Object { "$_," } - $Query.SelectPartQuery = $temp.TrimEnd(",") - $Query + process { + [string]$temp = $Value | + ForEach-Object { "$_," } + $Query.SelectPartQuery = $temp.TrimEnd(",") + $Query + } } Function AddToSelect { @@ -42,11 +44,12 @@ Function AddToSelect { [Parameter(Mandatory = $true)] [string[]]$Value ) - - [string]$temp = $Value | - ForEach-Object { "$_," } - $Query.SelectPartQuery = "$($Query.SelectPartQuery), $($temp.TrimEnd(","))" - $Query + process { + [string]$temp = $Value | + ForEach-Object { "$_," } + $Query.SelectPartQuery = "$($Query.SelectPartQuery), $($temp.TrimEnd(","))" + $Query + } } Function SetFrom { @@ -58,9 +61,10 @@ Function SetFrom { [Parameter(Mandatory = $true)] [string]$Value ) - - $Query.FromPartQuery = $Value - $Query + process { + $Query.FromPartQuery = $Value + $Query + } } Function SetWhere { @@ -72,9 +76,10 @@ Function SetWhere { [Parameter(Mandatory = $true)] [string]$Value ) - - $Query.WherePartQuery = $Value - $Query + process { + $Query.WherePartQuery = $Value + $Query + } } Function AddToWhere { @@ -86,9 +91,10 @@ Function AddToWhere { [Parameter(Mandatory = $true)] [string]$Value ) - - $Query.WherePartQuery = "$($Query.WherePartQuery)$Value" - $Query + process { + $Query.WherePartQuery = "$($Query.WherePartQuery)$Value" + $Query + } } Function InvokeGetStoreQuery { @@ -98,35 +104,36 @@ Function InvokeGetStoreQuery { [Parameter(ValueFromPipeline = $true, Mandatory = $true)] [object]$Query ) + process { + if (-not([string]::IsNullOrEmpty($Query.WherePartQuery))) { + $queryString = "SELECT $($Query.SelectPartQuery) FROM $($Query.FromPartQuery) WHERE $($Query.WherePartQuery)" + } else { + $queryString = "SELECT $($Query.SelectPartQuery) FROM $($Query.FromPartQuery)" + } - if (-not([string]::IsNullOrEmpty($Query.WherePartQuery))) { - $queryString = "SELECT $($Query.SelectPartQuery) FROM $($Query.FromPartQuery) WHERE $($Query.WherePartQuery)" - } else { - $queryString = "SELECT $($Query.SelectPartQuery) FROM $($Query.FromPartQuery)" - } - - $myParams = @{ - Server = $Query.Server - ProcessId = $Query.ProcessId - Query = $queryString - Unlimited = $Query.IsUnlimited - } + $myParams = @{ + Server = $Query.Server + ProcessId = $Query.ProcessId + Query = $queryString + Unlimited = $Query.IsUnlimited + } - Write-Verbose "Running 'Get-StoreQuery -Server $($Query.Server) -ProcessId $($Query.ProcessId) -Unlimited:`$$($Query.IsUnlimited) -Query `"$queryString`"'" - $result = @(Get-StoreQuery @myParams) - - if ($result.GetType().ToString() -ne "System.Object[]" -or - $result.Count -le 1) { - if ($null -ne ($result.DiagnosticQueryException)) { - Write-Error "Get-StoreQuery DiagnosticQueryException : $($result.DiagnosticQueryException)" - } elseif ($null -ne ($result.DiagnosticQueryTranslatorException)) { - Write-Error "Get-StoreQuery DiagnosticQueryTranslatorException : $($result.DiagnosticQueryTranslatorException)" - } elseif ($null -ne ($result.DiagnosticQueryParserException)) { - Write-Error "Get-StoreQuery DiagnosticQueryParserException : $($result.DiagnosticQueryParserException)" + Write-Verbose "Running 'Get-StoreQuery -Server $($Query.Server) -ProcessId $($Query.ProcessId) -Unlimited:`$$($Query.IsUnlimited) -Query `"$queryString`"'" + $result = @(Get-StoreQuery @myParams) + + if ($result.GetType().ToString() -ne "System.Object[]" -or + $result.Count -le 1) { + if ($null -ne ($result.DiagnosticQueryException)) { + Write-Error "Get-StoreQuery DiagnosticQueryException : $($result.DiagnosticQueryException)" + } elseif ($null -ne ($result.DiagnosticQueryTranslatorException)) { + Write-Error "Get-StoreQuery DiagnosticQueryTranslatorException : $($result.DiagnosticQueryTranslatorException)" + } elseif ($null -ne ($result.DiagnosticQueryParserException)) { + Write-Error "Get-StoreQuery DiagnosticQueryParserException : $($result.DiagnosticQueryParserException)" + } } - } - return $result + return $result + } } Function Get-StoreQueryObject { diff --git a/Shared/LoggerFunctions.ps1 b/Shared/LoggerFunctions.ps1 index 529819c70b..18d6812ba4 100644 --- a/Shared/LoggerFunctions.ps1 +++ b/Shared/LoggerFunctions.ps1 @@ -94,12 +94,13 @@ Function Invoke-LoggerInstanceCleanup { [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [object]$LoggerInstance ) + process { + if ($LoggerInstance.LoggerDisabled -or + $LoggerInstance.PreventLogCleanup) { + return + } - if ($LoggerInstance.LoggerDisabled -or - $LoggerInstance.PreventLogCleanup) { - return + Get-ChildItem -Path ([System.IO.Path]::GetDirectoryName($LoggerInstance.FullPath)) -Filter "*$($LoggerInstance.BaseInstanceFileName)*" | + Remove-Item -Force } - - Get-ChildItem -Path ([System.IO.Path]::GetDirectoryName($LoggerInstance.FullPath)) -Filter "*$($LoggerInstance.BaseInstanceFileName)*" | - Remove-Item -Force } From e2ea18ba460dcdfe8b94180698c1e4cb2fdc1f27 Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 12:04:04 -0500 Subject: [PATCH 12/24] Addressed PSAvoidAssignmentToAutomaticVariable --- Transport/Compute-TopExoRecipientsFromMessageTrace.ps1 | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Transport/Compute-TopExoRecipientsFromMessageTrace.ps1 b/Transport/Compute-TopExoRecipientsFromMessageTrace.ps1 index 44039fc7c6..2d0a4eb4b5 100644 --- a/Transport/Compute-TopExoRecipientsFromMessageTrace.ps1 +++ b/Transport/Compute-TopExoRecipientsFromMessageTrace.ps1 @@ -50,12 +50,11 @@ $CreateHourlyReport = $eventList = $eventList | Sort-Object RecipientAddress, Received $eventList.foreach( { - $event = $_ $hourlyEvent = $hourlyReport[-1] #data is sorted to min get operations. we only need to compare with last element in the array - if ($hourlyEvent.RecipientAddress -eq $event.RecipientAddress -and $hourlyEvent.Hour -eq $event.Received.Hour) { + if ($hourlyEvent.RecipientAddress -eq $_.RecipientAddress -and $hourlyEvent.Hour -eq $_.Received.Hour) { $hourlyEvent.MessageCount +=1 } else { - $eventObj = New-Object PSObject -Property @{ Hour=$event.Received.Hour; Date=$event.Received.Date.ToString("dd/mm/yyyy dd:hh tt"); MessageCount=1; RecipientAddress=$event.RecipientAddress }; + $eventObj = New-Object PSObject -Property @{ Hour=$_.Received.Hour; Date=$_.Received.Date.ToString("dd/mm/yyyy dd:hh tt"); MessageCount=1; RecipientAddress=$_.RecipientAddress }; [void]$hourlyReport.Add($eventObj) } } From 5fbbe5dda21fd42f28a290c98486f939107511cf Mon Sep 17 00:00:00 2001 From: Bill Long Date: Mon, 9 Aug 2021 12:06:25 -0500 Subject: [PATCH 13/24] Fix script analyzer warnings --- Performance/SimplePerf.ps1 | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Performance/SimplePerf.ps1 b/Performance/SimplePerf.ps1 index 6ea21664ff..0508cd7dfb 100644 --- a/Performance/SimplePerf.ps1 +++ b/Performance/SimplePerf.ps1 @@ -70,7 +70,7 @@ param ( ) begin { - function Start-SimplePerf { + function StartSimplePerf { param ( [Parameter(Mandatory = $true, Position = 0)] [string] @@ -166,7 +166,7 @@ begin { logman start "SimplePerf" } - function Stop-SimplePerf { + function StopSimplePerf { Write-Host "$($env:COMPUTERNAME): Stopping SimplePerf." logman stop "SimplePerf" } @@ -189,16 +189,16 @@ end { if ($computerTargets.Length -gt 0) { foreach ($computer in $computerTargets) { if ($Start) { - Invoke-Command -ComputerName $computer -ScriptBlock ${function:Start-SimplePerf} -ArgumentList $Duration, $Interval, $MaximumSizeInMB, $OutputFolder, $IncludeThread, $Circular + Invoke-Command -ComputerName $computer -ScriptBlock ${function:StartSimplePerf} -ArgumentList $Duration, $Interval, $MaximumSizeInMB, $OutputFolder, $IncludeThread, $Circular } elseif ($Stop) { - Invoke-Command -ComputerName $computer -ScriptBlock ${function:Stop-SimplePerf} + Invoke-Command -ComputerName $computer -ScriptBlock ${function:StopSimplePerf} } } } else { if ($Start) { - Start-SimplePerf $Duration $Interval $MaximumSizeInMB $OutputFolder $IncludeThread $Circular + StartSimplePerf -Duration $Duration -Interval $Interval -MaximumSizeInMB $MaximumSizeInMB -OutputFolder $OutputFolder -IncludeThread $IncludeThread -Circular $Circular } else { - Stop-SimplePerf + StopSimplePerf } } } From 9f63558554e8fd7861c4b09445f2f444003bca30 Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 12:13:52 -0500 Subject: [PATCH 14/24] Addressed PSAvoidUsingComputerNameHardcoded --- Shared/Tests/Invoke-ScriptBlockHandler.Tests.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/Shared/Tests/Invoke-ScriptBlockHandler.Tests.ps1 b/Shared/Tests/Invoke-ScriptBlockHandler.Tests.ps1 index 9de1058b5e..e73629393e 100644 --- a/Shared/Tests/Invoke-ScriptBlockHandler.Tests.ps1 +++ b/Shared/Tests/Invoke-ScriptBlockHandler.Tests.ps1 @@ -1,6 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', Justification = 'Incorrect rule result')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingComputerNameHardcoded', Justification = 'Pester testing, no issues')] [CmdletBinding()] param() BeforeAll { From 6f0de00593fb392ca131db17a05a8eef6ba67e74 Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 12:23:34 -0500 Subject: [PATCH 15/24] Override PSUseApprovedVerbs on Load-Module --- .build/Load-Module.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/.build/Load-Module.ps1 b/.build/Load-Module.ps1 index edefaad58b..4764e7148c 100644 --- a/.build/Load-Module.ps1 +++ b/.build/Load-Module.ps1 @@ -2,6 +2,7 @@ # Licensed under the MIT License. function Load-Module { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseApprovedVerbs', Justification = 'Prefer verb usage')] [CmdletBinding()] [OutputType([bool])] param ( From 0a23d4c3a1f38254f1e6b5bc01db172af29f9184 Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 12:24:05 -0500 Subject: [PATCH 16/24] Override PSUseShouldProcessForStateChangingFunctions on Start-SleepWithProgress --- Shared/Start-SleepWithProgress.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/Shared/Start-SleepWithProgress.ps1 b/Shared/Start-SleepWithProgress.ps1 index 1eaba30a54..bae033b159 100644 --- a/Shared/Start-SleepWithProgress.ps1 +++ b/Shared/Start-SleepWithProgress.ps1 @@ -31,6 +31,7 @@ Counts down 60 seconds and updates the Progress bar during the proess. #> Function Start-SleepWithProgress { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', Justification = 'Start-Sleep does not use -WhatIf')] Param( [Parameter(Mandatory = $true)] [int]$SleepTime, From f65c45bfd204c7501965bf46da99c2e72ecc080b Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 12:32:11 -0500 Subject: [PATCH 17/24] Moved Shared Functions from Test-ExchangeAVExclusions to local No need to have the functions in Shared till they are used by other scripts. --- {Shared => Diagnostics/AVTester}/Start-SleepWithProgress.ps1 | 0 Diagnostics/AVTester/Test-ExchAVExclusions.ps1 | 4 ++-- {Shared => Diagnostics/AVTester}/Write-SimpleLogFile.ps1 | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename {Shared => Diagnostics/AVTester}/Start-SleepWithProgress.ps1 (100%) rename {Shared => Diagnostics/AVTester}/Write-SimpleLogFile.ps1 (100%) diff --git a/Shared/Start-SleepWithProgress.ps1 b/Diagnostics/AVTester/Start-SleepWithProgress.ps1 similarity index 100% rename from Shared/Start-SleepWithProgress.ps1 rename to Diagnostics/AVTester/Start-SleepWithProgress.ps1 diff --git a/Diagnostics/AVTester/Test-ExchAVExclusions.ps1 b/Diagnostics/AVTester/Test-ExchAVExclusions.ps1 index ae2a90f393..499e2cf67e 100644 --- a/Diagnostics/AVTester/Test-ExchAVExclusions.ps1 +++ b/Diagnostics/AVTester/Test-ExchAVExclusions.ps1 @@ -55,8 +55,8 @@ param ( ) . $PSScriptRoot\..\..\Shared\Confirm-Administrator.ps1 -. $PSScriptRoot\..\..\Shared\Write-SimpleLogFile.ps1 -. $PSScriptRoot\..\..\Shared\Start-SleepWithProgress.ps1 +. $PSScriptRoot\Write-SimpleLogFile.ps1 +. $PSScriptRoot\Start-SleepWithProgress.ps1 # Log file name $LogFile = "ExchAvExclusions.log" diff --git a/Shared/Write-SimpleLogFile.ps1 b/Diagnostics/AVTester/Write-SimpleLogFile.ps1 similarity index 100% rename from Shared/Write-SimpleLogFile.ps1 rename to Diagnostics/AVTester/Write-SimpleLogFile.ps1 From 8ecb5c4da462fdad95c45b066d2eafee05812a6d Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 12:39:15 -0500 Subject: [PATCH 18/24] Forgot to include missing parameter in Diagnostics.CodeAnalysis.SuppressMessageAttribute --- .build/Load-Module.ps1 | 2 +- Diagnostics/AVTester/Start-SleepWithProgress.ps1 | 2 +- .../Exchange/Get-SearchProcessState.ps1 | 2 +- Shared/Tests/Invoke-ScriptBlockHandler.Tests.ps1 | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.build/Load-Module.ps1 b/.build/Load-Module.ps1 index 4764e7148c..3c0dbab26f 100644 --- a/.build/Load-Module.ps1 +++ b/.build/Load-Module.ps1 @@ -2,7 +2,7 @@ # Licensed under the MIT License. function Load-Module { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseApprovedVerbs', Justification = 'Prefer verb usage')] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseApprovedVerbs', '', Justification = 'Prefer verb usage')] [CmdletBinding()] [OutputType([bool])] param ( diff --git a/Diagnostics/AVTester/Start-SleepWithProgress.ps1 b/Diagnostics/AVTester/Start-SleepWithProgress.ps1 index bae033b159..924df90e16 100644 --- a/Diagnostics/AVTester/Start-SleepWithProgress.ps1 +++ b/Diagnostics/AVTester/Start-SleepWithProgress.ps1 @@ -31,7 +31,7 @@ Counts down 60 seconds and updates the Progress bar during the proess. #> Function Start-SleepWithProgress { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', Justification = 'Start-Sleep does not use -WhatIf')] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Start-Sleep does not use -WhatIf')] Param( [Parameter(Mandatory = $true)] [int]$SleepTime, diff --git a/Search/Troubleshoot-ModernSearch/Exchange/Get-SearchProcessState.ps1 b/Search/Troubleshoot-ModernSearch/Exchange/Get-SearchProcessState.ps1 index 280c8c2136..42515f2b1d 100644 --- a/Search/Troubleshoot-ModernSearch/Exchange/Get-SearchProcessState.ps1 +++ b/Search/Troubleshoot-ModernSearch/Exchange/Get-SearchProcessState.ps1 @@ -2,7 +2,7 @@ # Licensed under the MIT License. Function Get-SearchProcessState { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWMICmdlet', Justification = 'Cmdlet required')] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWMICmdlet', '', Justification = 'Cmdlet required')] [CmdletBinding()] param( [string]$ComputerName = $env:COMPUTERNAME diff --git a/Shared/Tests/Invoke-ScriptBlockHandler.Tests.ps1 b/Shared/Tests/Invoke-ScriptBlockHandler.Tests.ps1 index e73629393e..c6c265f73b 100644 --- a/Shared/Tests/Invoke-ScriptBlockHandler.Tests.ps1 +++ b/Shared/Tests/Invoke-ScriptBlockHandler.Tests.ps1 @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', Justification = 'Incorrect rule result')] -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingComputerNameHardcoded', Justification = 'Pester testing, no issues')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Incorrect rule result')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingComputerNameHardcoded', '', Justification = 'Pester testing, no issues')] [CmdletBinding()] param() BeforeAll { From 785ab358b2b5f1f228d1fde6f02767659a759680 Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 12:47:53 -0500 Subject: [PATCH 19/24] Addressed PSUseDeclaredVarsMoreThanAssignments with override placing into a process/end block didn't help --- .build/CodeFormatter.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.build/CodeFormatter.ps1 b/.build/CodeFormatter.ps1 index 4ef5ba5494..f263607e8b 100644 --- a/.build/CodeFormatter.ps1 +++ b/.build/CodeFormatter.ps1 @@ -1,6 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. - +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = '$fileFailed is being used.')] [CmdletBinding()] param( [Switch] From ea30f47e42bb7265efb6373e66d7c91e50a1f0ba Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 13:12:12 -0500 Subject: [PATCH 20/24] Addressing PSAvoidUsingPositionalParameters --- .../ManagedAvailabilityTroubleshooter.ps1 | 85 ++++++++++++++----- 1 file changed, 63 insertions(+), 22 deletions(-) diff --git a/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 b/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 index 9f984072c0..9c260188e6 100644 --- a/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 +++ b/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 @@ -30,9 +30,18 @@ function ParseProbeResult { Param( [String] $FilterXpath , [String] $MonitorToInvestigate , [String] $ResponderToInvestigate) TestFileorCmd $ProbeResulteventcmd; - ParseProbeResult2 ($ProbeResulteventcmd + " -maxevents 200" ) $FilterXpath "Parsing only last 200 probe events for quicker response time" $MonitorToInvestigate $ResponderToInvestigate - if ("yes", "YES", "Y", "y" -contains (Read-Host ("`nParsed last 200 probe events for quicker response.`nDo you like to parse all probe events ? Y/N (default is ""N"")"))) - { ParseProbeResult2 $ProbeResulteventcmd $FilterXpath "Parsing all probe events. this may be slow as there is lots of events" $MonitorToInvestigate $ResponderToInvestigate } + ParseProbeResult2 -ProbeResulteventcompletecmd ($ProbeResulteventcmd + " -maxevents 200" ) ` + -FilterXpath $FilterXpath ` + -waitstring "Parsing only last 200 probe events for quicker response time" ` + -MonitorToInvestigate $MonitorToInvestigate ` + -ResponderToInvestigate $ResponderToInvestigate + if ("yes", "YES", "Y", "y" -contains (Read-Host ("`nParsed last 200 probe events for quicker response.`nDo you like to parse all probe events ? Y/N (default is ""N"")"))) { + ParseProbeResult2 -ProbeResulteventcompletecmd $ProbeResulteventcmd ` + -FilterXpath $FilterXpath ` + -waitstring "Parsing all probe events. this may be slow as there is lots of events" ` + -MonitorToInvestigate $MonitorToInvestigate ` + -ResponderToInvestigate $ResponderToInvestigate + } } function ParseProbeResult2 { @@ -157,7 +166,9 @@ function InvestigateProbe { } else { Write-Host -ForegroundColor red ("Missing logs from path $EacBackEndLogonProbefolder ") } } else { - ParseProbeResult ("*[UserData[EventXML[ResultName='" + $ProbeDetailsfullname + "']]]") $MonitorToInvestigate $ResponderToInvestigate + ParseProbeResult -FilterXpath ("*[UserData[EventXML[ResultName='" + $ProbeDetailsfullname + "']]]") ` + -MonitorToInvestigate $MonitorToInvestigate ` + -ResponderToInvestigate $ResponderToInvestigate } } else { Write-Host("`nFound no definitions for " + $ProbeToInvestigate + " probe") } @@ -218,11 +229,20 @@ Function InvestigateMonitor { if ($ProbeToInvestigate) { if ($ProbeToInvestigate.Count -gt 1) { Write-Host ("`nMultiple probes linked with the monitor " + $MonitorToInvestigate + " , here is the list : " + $ProbeToInvestigate) - foreach ($individualProbetoInvestigate in $ProbeToInvestigate) - { InvestigateProbe $individualProbetoInvestigate $MonitorToInvestigate $ResponderToInvestigate $ResourceNameToInvestigate $ResponderTargetResource } + foreach ($individualProbetoInvestigate in $ProbeToInvestigate) { + InvestigateProbe -ProbeToInvestigate $individualProbetoInvestigate ` + -MonitorToInvestigate $MonitorToInvestigate ` + -ResponderToInvestigate $ResponderToInvestigate ` + -ResourceNameToInvestigate $ResourceNameToInvestigate ` + -ResponderTargetResource $ResponderTargetResource + } } else { Write-Host ("`nThe probe triggering " + $MonitorToInvestigate + " monitor is " + $ProbeToInvestigate) - InvestigateProbe $ProbeToInvestigate $MonitorToInvestigate $ResponderToInvestigate $ResourceNameToInvestigate $ResponderTargetResource + InvestigateProbe -ProbeToInvestigate $ProbeToInvestigate ` + -MonitorToInvestigate $MonitorToInvestigate ` + -ResponderToInvestigate $ResponderToInvestigate ` + -ResourceNameToInvestigate $ResourceNameToInvestigate ` + -ResponderTargetResource $ResponderTargetResource } } else { Write-Host ("`nFound no probe triggering " + $MonitorToInvestigate ) } @@ -402,7 +422,10 @@ Function InvestigateResponder { $MonitorToInvestigate = $ResponderDetails.AlertMask if ($MonitorToInvestigate) { Write-Host ("`nThe monitor triggering " + $ResponderToInvestigate + " Responder is " + $MonitorToInvestigate) - InvestigateMonitor $MonitorToInvestigate $ResourceNameToInvestigate $ResponderDetails.TargetResource $ResponderToInvestigate + InvestigateMonitor -MonitorToInvestigate $MonitorToInvestigate ` + -ResourceNameToInvestigate $ResourceNameToInvestigate ` + -ResponderTargetResource $ResponderDetails.TargetResource ` + -ResponderToInvestigate $ResponderToInvestigate } else { Write-Host ("`nFound no monitor triggering " + $ResponderToInvestigate + "`n" ) } if ($Script:KnownIssueDetectionAlreadydone -eq $false) { KnownIssueDetection $null $ResponderToInvestigate } @@ -553,7 +576,7 @@ function CheckifthiscanbeaknownissueusingMonitor { if ($Script:lastProbeerror) { if ($Script:lastProbeerror.Exception -like "*The underlying connection was closed*") { Write-Host -foreground yellow "This probe error message related to underlying connection closed has been seen when connection for loopback adapter has been blocked at lower level before reaching Exchange`n" - Write-Host -foreground yellow "You can check in IIS Default Web Site /Actions pane / Bindings that “All Unassigned” is used and this has not been changed to only allow specific IP.`n" + Write-Host -foreground yellow "You can check in IIS Default Web Site /Actions pane / Bindings that `“All Unassigned`” is used and this has not been changed to only allow specific IP.`n" Write-Host -foreground yellow "This has been seen when blocking some TLS version using Secureprotocols registry key or through GPO.`n" Write-Host -foreground yellow "You can check if some TLS version are disabled under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols (https://techcommunity.microsoft.com/t5/exchange-team-blog/exchange-server-tls-guidance-part-2-enabling-tls-1-2-and/ba-p/607761).`n" Write-Host -foreground yellow "You may also check if this is linked with antivirus or local firewall rules.`n" @@ -616,16 +639,21 @@ function InvestigateUnhealthyMonitor { Start-Sleep -s 1 $UnhealthyMonitorToInvestigate = $myHealthEntryList | Out-GridView -PassThru -Title $Selectunhealthymonitor if ( $UnhealthyMonitorToInvestigate) { - if (([string]::Compare($UnhealthyMonitorToInvestigate.Server, $env:computername, $true) -eq 0) -or ($pathforlogsspecified)) - { InvestigateMonitor $UnhealthyMonitorToInvestigate.Name $null $UnhealthyMonitorToInvestigate.TargetResource $null } - else { + if (([string]::Compare($UnhealthyMonitorToInvestigate.Server, $env:computername, $true) -eq 0) -or ($pathforlogsspecified)) { + InvestigateMonitor -MonitorToInvestigate $UnhealthyMonitorToInvestigate.Name ` + -ResourceNameToInvestigate $null ` + -ResponderTargetResource $UnhealthyMonitorToInvestigate.TargetResource ` + -ResponderToInvestigate $null + } else { Write-Host -ForegroundColor yellow ("`nThe Monitor you select is regarding a different server : " + $UnhealthyMonitorToInvestigate.Server + " .") Write-Host -ForegroundColor yellow ("Run this script on this server directly to analyse this monitor further." ) } - } else - { Write-Host ("`nYou have not selected any unhealthy monitor. Run the script again and select an occurrence" ) } - } else - { Write-Host ("`nFound no unhealthy monitor." ) } + } else { + Write-Host ("`nYou have not selected any unhealthy monitor. Run the script again and select an occurrence" ) + } + } else { + Write-Host ("`nFound no unhealthy monitor." ) + } } function CollectMaLogs { @@ -645,7 +673,7 @@ function CollectMaLogs { if (-not (Test-Path($OutputPath))) { New-Item -ItemType Directory -Force -Path $OutputPath | Out-Null } if (-not (Test-Path($OutputPath))) - { Write-Host "Failed to create " + $OutputPath + " to store logs collected"; exit } + { Write-Host "Failed to create $OutputPath to store logs collected"; exit } $ExchangeServerinfofile = $OutputPath + "\" + $env:computername + "_ExchangeServer_FL.TXT" $ExchangeServerinfo | Out-File $ExchangeServerinfofile @@ -685,7 +713,7 @@ function CollectMaLogs { if (-not (Test-Path($logcollectionmonitoringfolder))) { New-Item -ItemType Directory -Force -Path $logcollectionmonitoringfolder | Out-Null } if (-not (Test-Path($logcollectionmonitoringfolder))) - { Write-Host "Failed to create " + $logcollectionmonitoringfolder + " to store logs collected"; exit } + { Write-Host "Failed to create $logcollectionmonitoringfolder to store logs collected"; exit } $monitoringfiles = Get-ChildItem ( $monitoringfolder.Fullname ) | Where-Object { $_.PSIsContainer -eq $false } if ($monitoringfolder.Name -eq "ActiveMonitoringTraceLogs") @@ -703,7 +731,7 @@ function CollectMaLogs { if (-not (Test-Path($logHighAvailabilityfolder))) { New-Item -ItemType Directory -Force -Path $logHighAvailabilityfolder | Out-Null } if (-not (Test-Path($logHighAvailabilityfolder))) - { Write-Host "Failed to create " + $logHighAvailabilityfolder + " to store HighAvailability logs collected"; exit } + { Write-Host "Failed to create $logHighAvailabilityfolder to store HighAvailability logs collected"; exit } foreach ($HighAvailabilityfile in $HighAvailabilityfiles ) { Write-Progress ("Collecting " + $HighAvailabilityfile.Fullname) Copy-Item $HighAvailabilityfile.Fullname -Destination $logHighAvailabilityfolder @@ -1146,8 +1174,19 @@ if ($Investigationchoose -eq 2) { } switch ( $IsitaResponderorMonitororProbe) { 0 { InvestigateResponder $SpecificResponderorMonitororProbe $null } - 1 { InvestigateMonitor $SpecificResponderorMonitororProbe $null $null $null } - 2 { InvestigateProbe $SpecificResponderorMonitororProbe $null $null $null $null } + 1 { + InvestigateMonitor -MonitorToInvestigate $SpecificResponderorMonitororProbe ` + -ResourceNameToInvestigate $null ` + -ResponderTargetResource $null ` + -ResponderToInvestigate $null + } + 2 { + InvestigateProbe -ProbeToInvestigate $SpecificResponderorMonitororProbe ` + -MonitorToInvestigate $null ` + -ResponderToInvestigate $null ` + -ResourceNameToInvestigate $null ` + -ResponderTargetResource $null + } } } else { Write-Host -ForegroundColor red ("No name specified") } @@ -1183,7 +1222,9 @@ if ($Investigationchoose -eq 4) { InvestigateUnhealthyMonitor $ServerHealthfile } if ($Investigationchoose -eq 5) { - ParseProbeResult "*[UserData[EventXML [ResultType='4']]]" $null $null + ParseProbeResult -FilterXpath "*[UserData[EventXML [ResultType='4']]]" ` + -MonitorToInvestigate $null ` + -ResponderToInvestigate $null } if (($Investigationchoose -eq 6) -and ($exchangeversion)) { CollectMaLogs $MyInvocation.MyCommand.Path From 50e53cedd6bad9a1d31c88fe88daf299d37f0aa1 Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 13:33:48 -0500 Subject: [PATCH 21/24] Adding in override for ManagedAvailabilityTroubleshooter To allow the branch to be merged in. Follow updates in #687 --- .../ManagedAvailabilityTroubleshooter.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 b/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 index 9c260188e6..c2a01e0f6b 100644 --- a/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 +++ b/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 @@ -5,7 +5,7 @@ # The goal of this script is to more easily investigate issues related of Managed Availability # Provide your feedback to ExToolsFeedback@microsoft.com - +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingInvokeExpression', '', Justification = 'Override for now')] [cmdletbinding()] Param([string]$pathforlogs, [switch]$Collect , [switch] $AllServers , [switch] $OnlyThisServer , [switch]$Help) @@ -175,6 +175,7 @@ function InvestigateProbe { } Function InvestigateMonitor { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseOutputTypeCorrectly', '', Justification = 'Override for now')] [cmdletbinding()] Param( [String]$MonitorToInvestigate , [String]$ResourceNameToInvestigate , [String]$ResponderTargetResource , [String] $ResponderToInvestigate) From 9eff60768d5b96e0f17e5c3dce374d52915e66a2 Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 13:56:12 -0500 Subject: [PATCH 22/24] Correct override justification typo --- .build/CodeFormatter.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.build/CodeFormatter.ps1 b/.build/CodeFormatter.ps1 index f263607e8b..b3898396e1 100644 --- a/.build/CodeFormatter.ps1 +++ b/.build/CodeFormatter.ps1 @@ -1,6 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = '$fileFailed is being used.')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = '$filesFailed is being used.')] [CmdletBinding()] param( [Switch] From d736ca08c89bc22cbd5e9a1de6b99e2391912e21 Mon Sep 17 00:00:00 2001 From: David Paulson Date: Mon, 9 Aug 2021 13:57:06 -0500 Subject: [PATCH 23/24] replaced quote type --- .../ManagedAvailabilityTroubleshooter.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 b/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 index c2a01e0f6b..fc1cc615a0 100644 --- a/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 +++ b/Diagnostics/ManagedAvailabilityTroubleshooter/ManagedAvailabilityTroubleshooter.ps1 @@ -577,7 +577,7 @@ function CheckifthiscanbeaknownissueusingMonitor { if ($Script:lastProbeerror) { if ($Script:lastProbeerror.Exception -like "*The underlying connection was closed*") { Write-Host -foreground yellow "This probe error message related to underlying connection closed has been seen when connection for loopback adapter has been blocked at lower level before reaching Exchange`n" - Write-Host -foreground yellow "You can check in IIS Default Web Site /Actions pane / Bindings that `“All Unassigned`” is used and this has not been changed to only allow specific IP.`n" + Write-Host -foreground yellow "You can check in IIS Default Web Site /Actions pane / Bindings that `"All Unassigned`" is used and this has not been changed to only allow specific IP.`n" Write-Host -foreground yellow "This has been seen when blocking some TLS version using Secureprotocols registry key or through GPO.`n" Write-Host -foreground yellow "You can check if some TLS version are disabled under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols (https://techcommunity.microsoft.com/t5/exchange-team-blog/exchange-server-tls-guidance-part-2-enabling-tls-1-2-and/ba-p/607761).`n" Write-Host -foreground yellow "You may also check if this is linked with antivirus or local firewall rules.`n" From deb6495e4dc6bb3524d4afd317a328905761c8f0 Mon Sep 17 00:00:00 2001 From: Bill Long Date: Mon, 9 Aug 2021 14:24:06 -0500 Subject: [PATCH 24/24] Move build back to Azure --- azure-pipelines.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 552d62e7ad..e841d19df4 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -3,7 +3,8 @@ trigger: include: - release -pool: Default +pool: + vmImage: 'windows-latest' steps: - script: echo Hello, world!