add: finally block to always disconnect

This commit is contained in:
DrIOS
2024-06-23 19:06:59 -05:00
parent 8b91a8c06e
commit 5c852679d9

View File

@@ -248,12 +248,20 @@ function Invoke-M365SecurityAudit {
$currentTestIndex = 0
# Establishing connections if required
try {
$actualUniqueConnections = Get-UniqueConnection -Connections $requiredConnections
if (!($DoNotConnect) -and $PSCmdlet.ShouldProcess("Establish connections to Microsoft 365 services: $($actualUniqueConnections -join ', ')", "Connect")) {
try {
Write-Information "Establishing connections to Microsoft 365 services: $($actualUniqueConnections -join ', ')" -InformationAction Continue
Connect-M365Suite -TenantAdminUrl $TenantAdminUrl -RequiredConnections $requiredConnections -SkipConfirmation:$DoNotConfirmConnections
}
}
catch {
Write-Host "Connection execution aborted: $_" -ForegroundColor Red
break
}
try {
Write-Information "A total of $($totalTests) tests were selected to run..." -InformationAction Continue
# Import the test functions
$testFiles | ForEach-Object {
@@ -265,7 +273,7 @@ function Invoke-M365SecurityAudit {
}
Catch {
# Log the error and add the test to the failed tests collection
Write-Error "Failed to load test function $($_.Name): $_"
Write-Verbose "Failed to load test function $($_.Name): $_" -Verbose
$script:FailedTests.Add([PSCustomObject]@{ Test = $_.Name; Error = $_ })
}
}
@@ -284,7 +292,9 @@ function Invoke-M365SecurityAudit {
}
}
catch {
Write-Error "An error occurred: $_"
# Log the error and add the test to the failed tests collection
Write-Verbose "Invoke-M365SecurityAudit: Failed to load test function $($_.Name): $_" -Verbose
$script:FailedTests.Add([PSCustomObject]@{ Test = $_.Name; Error = $_ })
}
finally {
if (!($DoNotDisconnect) -and $PSCmdlet.ShouldProcess("Disconnect from Microsoft 365 services: $($actualUniqueConnections -join ', ')", "Disconnect")) {
@@ -293,8 +303,6 @@ function Invoke-M365SecurityAudit {
}
}
}
}
End {
if ($PSCmdlet.ShouldProcess("Measure and display audit results for $($totalTests) tests", "Measure")) {
# Call the private function to calculate and display results
@@ -316,3 +324,4 @@ function Invoke-M365SecurityAudit {
}