Skip to content

Commit

Permalink
Merge pull request #4950 from FabienTschanz/fix/write-host
Browse files Browse the repository at this point in the history
Replace some Write-Host with appropriate alternatives
  • Loading branch information
ykuijs committed Aug 23, 2024
2 parents 6fa24f5 + 9599eb3 commit 1ec7623
Show file tree
Hide file tree
Showing 9 changed files with 51 additions and 70 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@
* M365DSCUtil
* Fix `Compare-PSCustomObjectArrays` by allowing empty arrays as input
FIXES [#4952](https://github.com/microsoft/Microsoft365DSC/issues/4952)
* MISC
* Replace some `Write-Host` occurrences in core engine with
appropriate alternatives.
FIXES [#4943](https://github.com/microsoft/Microsoft365DSC/issues/4943)

# 1.24.731.1

Expand Down
33 changes: 12 additions & 21 deletions Modules/Microsoft365DSC/Modules/M365DSCAgent.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,6 @@ function Test-M365DSCAgent
param(

)
#Ensure the proper dependencies are installed in the current environment.
Confirm-M365DSCDependencies

#region Telemetry
$data = [System.Collections.Generic.Dictionary[[String], [String]]]::new()
$data.Add('Event', 'TestAgent')
Expand Down Expand Up @@ -68,45 +65,39 @@ function Test-M365DSCAgent

#region Modules Dependencies
Write-Progress -Activity 'Scanning Dependencies...' -PercentComplete (3 / $TotalSteps * 100)
$M365DSC = Get-Module Microsoft365DSC
$ManifestPath = Join-Path -Path $M365DSC.ModuleBase -ChildPath 'Microsoft365DSC.psd1'
$manifest = Import-PowerShellDataFile $ManifestPath
$dependencies = $manifest.RequiredModules
$dependencies = Update-M365DSCDependencies -ValidateOnly
foreach ($dependency in $dependencies)
{
$module = Get-Module $dependency.ModuleName -ListAvailable | `
Where-Object -FilterScript { $_.Version -eq $dependency.RequiredVersion }
if ($null -eq $module)
{
$Issues += @{
ID = 'I2'
Message = "M365DSC has a dependency on module $($dependency.ModuleName) which was not found. You need to install " + `
"this module by running: Install-Module $($dependency.ModuleName) -RequiredVersion $($dependency.RequiredVersion) -Force"
}
$Issues += @{
ID = 'I2'
Message = "M365DSC has a dependency on module $($dependency.ModuleName) which was not found. You need to install " + `
"this module by running: Install-Module $($dependency.ModuleName) -RequiredVersion $($dependency.RequiredVersion) -Force"
}
}
#endregion

Write-Progress -Completed -Activity 'Completed Analysis'
if ($Issues.Count -gt 0)
{
Write-Host "The following issues were detected with the current agent's configuration. Please take " + `
'proper action to remediate.'
$errorMessage = "The following issues were detected with the current agent's configuration. Please take " + `
"proper action to remediate. `r`n"
$i = 1
foreach ($issue in $Issues)
{
Write-Error -Message " [$i/$($Issues.Count)] $($issue.Message)"
$errorMessage += " [$i/$($Issues.Count)] $($issue.Message)`r`n"
}
Write-Error -Message $errorMessage -ErrorAction Continue
}

if ($Recommendations.Count -gt 0)
{
Write-Host 'The following recommendations were issued. We strongly recommend adressing those: '
$warningMessage = 'The following recommendations were issued. We strongly recommend adressing those: '
$i = 1
foreach ($recommendation in $Recommendations)
{
Write-Warning " [$i/$($Recommendations.Count)] $($recommendation.Message)"
$warningMessage += " [$i/$($Recommendations.Count)] $($recommendation.Message)`r`n"
}
Write-Warning -Message $warningMessage
}

if ($Recommendations.Count -eq 0 -and $Issues.Count -eq 0)
Expand Down
6 changes: 2 additions & 4 deletions Modules/Microsoft365DSC/Modules/M365DSCExoResourceUtils.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,7 @@ function New-ExoUnitTest
}
catch
{
Write-Host "DSC resource $ResourceName not found!"
break;
throw "DSC resource $ResourceName not found!"
}

# Copy unit test template
Expand All @@ -238,8 +237,7 @@ function New-ExoUnitTest
}
catch
{
Write-Host 'Cannot create unit test file!'
break;
throw 'Failed to create unit test file!'
}

$parameterInformation = @()
Expand Down
5 changes: 2 additions & 3 deletions Modules/Microsoft365DSC/Modules/M365DSCLogEngine.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ function New-M365DSCLogEntry
}
else
{
Write-Host " Error Log created at {file://$LogFileName}" -ForegroundColor Red
Write-Host "Error Log created at {file://$LogFileName}" -ForegroundColor Red
}
#endregion
}
Expand Down Expand Up @@ -332,8 +332,7 @@ function Export-M365DSCDiagnosticData

if (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator') -eq $false)
{
Write-Host -Object '[ERROR] You need to run this cmdlet with Administrator privileges!' -ForegroundColor Red
return
throw 'You need to run this cmdlet with Administrator privileges!'
}

$afterDate = (Get-Date).AddDays(($NumberOfDays * -1))
Expand Down
4 changes: 2 additions & 2 deletions Modules/Microsoft365DSC/Modules/M365DSCPermissions.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ function Get-M365DSCCompiledPermissionList
}
catch
{
Write-Host "File settings.json was not found for resource {$resourceName}" -ForegroundColor Red
Write-Warning -Message "File settings.json was not found for resource {$resourceName}"
}

if ($null -ne $settingsFilePath)
Expand Down Expand Up @@ -1747,7 +1747,7 @@ function Update-M365DSCAzureAdApplication
{
if ($_.Exception.Message -match 'Key credential end date is invalid')
{
Write-Host "Caught error: $($_.Exception.Message)"
Write-Error $($_.Exception.Message) -ErrorAction Continue
if ($retryCount -lt $maxRetries)
{
$retryCount++
Expand Down
4 changes: 2 additions & 2 deletions Modules/Microsoft365DSC/Modules/M365DSCReport.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -1086,7 +1086,7 @@ function Compare-M365DSCConfigurations
}
catch
{
Write-Host "Error: $_"
Write-Error -Message $_ -ErrorAction Continue
}
$i++
}
Expand Down Expand Up @@ -1140,7 +1140,7 @@ function Compare-M365DSCConfigurations
}
catch
{
Write-Host "Error: $_"
Write-Error -Message $_ -ErrorAction Continue
}
Write-Progress -Activity 'Scanning Destination...' -Completed

Expand Down
16 changes: 7 additions & 9 deletions Modules/Microsoft365DSC/Modules/M365DSCReverse.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -256,9 +256,9 @@ function Start-M365DSCConfigurationExtract
$ComponentsToSkip += $resource.InputObject
}

Write-Host '[WARNING]' -NoNewline -ForegroundColor Yellow
Write-Host ' Based on the provided Authentication parameters, the following resources cannot be extracted: ' -ForegroundColor Gray
Write-Host "$($resourcesNotSupported -join ',')" -ForegroundColor Gray
$warningMessage = 'Based on the provided Authentication parameters, the following resources cannot be extracted: '
$warningMessage += $resourcesNotSupported -join ','
Write-Warning -Message $warningMessage

# If all selected resources are not valid based on the authentication method used, simply return.
if ($ComponentsToSkip.Length -eq $selectedResources.Length)
Expand Down Expand Up @@ -773,12 +773,12 @@ function Start-M365DSCConfigurationExtract
Write-Host "Results:"
if ($results.Count -gt 0)
{
$errorMessage = ''
foreach ($issue in $results)
{
Write-Host " - [" -NoNewline
Write-Host "$($issue.Reason)" -ForegroundColor Red -NoNewline
Write-Host "]: $($issue.InstanceName)"
$errorMessage += " - [$($issue.Reason)]: $($issue.InstanceName)`r`n"
}
Write-Error -Message $errorMessage -ErrorAction Continue
}
else
{
Expand Down Expand Up @@ -918,9 +918,7 @@ function Start-M365DSCConfigurationExtract
}
else
{
Write-Host "$($Global:M365DSCEmojiYellowCircle) Warning {" -NoNewline
Write-Host "Cannot export Local Configuration Manager settings. This process isn't executed with Administrative Privileges!" -NoNewline -ForegroundColor DarkCyan
Write-Host '}'
Write-Warning -Message "Cannot export Local Configuration Manager settings. This process isn't executed with Administrative Privileges!"
}
}
catch
Expand Down
42 changes: 18 additions & 24 deletions Modules/Microsoft365DSC/Modules/M365DSCUtil.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -1211,7 +1211,7 @@ function Export-M365DSCConfiguration
}
else
{
Write-Host -Object "[WARNING] We recommend providing the TenantId property in the format of <tenant>.onmicrosoft.*" -ForegroundColor Yellow
Write-Warning -Message "We recommend providing the TenantId property in the format of <tenant>.onmicrosoft.*"
}
}
return $true
Expand Down Expand Up @@ -1278,30 +1278,27 @@ function Export-M365DSCConfiguration
{
if ($Credential.Username -notmatch ".onmicrosoft.")
{
Write-Host -Object "[WARNING] We recommend providing the username in the format of <tenant>.onmicrosoft.* for the Credential property." -ForegroundColor Yellow
Write-Warning -Message "We recommend providing the username in the format of <tenant>.onmicrosoft.* for the Credential property."
}
}

if ($PSBoundParameters.ContainsKey('CertificatePath') -eq $true -and `
$PSBoundParameters.ContainsKey('CertificatePassword') -eq $false)
{
Write-Host -Object '[ERROR] You have to specify CertificatePassword when you specify CertificatePath' -ForegroundColor Red
return
throw 'You have to specify CertificatePassword when you specify CertificatePath'
}

if ($PSBoundParameters.ContainsKey('CertificatePassword') -eq $true -and `
$PSBoundParameters.ContainsKey('CertificatePath') -eq $false)
{
Write-Host -Object '[ERROR] You have to specify CertificatePath when you specify CertificatePassword' -ForegroundColor Red
return
throw 'You have to specify CertificatePath when you specify CertificatePassword'
}

if ($PSBoundParameters.ContainsKey('ApplicationId') -eq $true -and `
$PSBoundParameters.ContainsKey('Credential') -eq $false -and `
$PSBoundParameters.ContainsKey('TenantId') -eq $false)
{
Write-Host -Object '[ERROR] You have to specify TenantId when you specify ApplicationId' -ForegroundColor Red
return
throw 'You have to specify TenantId when you specify ApplicationId'
}

if ($PSBoundParameters.ContainsKey('ApplicationId') -eq $true -and `
Expand All @@ -1311,8 +1308,7 @@ function Export-M365DSCConfiguration
$PSBoundParameters.ContainsKey('ApplicationSecret') -eq $false -and `
$PSBoundParameters.ContainsKey('CertificatePath') -eq $false))
{
Write-Host -Object '[ERROR] You have to specify ApplicationSecret, CertificateThumbprint or CertificatePath when you specify ApplicationId/TenantId' -ForegroundColor Red
return
throw 'You have to specify ApplicationSecret, CertificateThumbprint or CertificatePath when you specify ApplicationId/TenantId'
}

if (($PSBoundParameters.ContainsKey('ApplicationId') -eq $false -or `
Expand All @@ -1322,8 +1318,7 @@ function Export-M365DSCConfiguration
$PSBoundParameters.ContainsKey('ApplicationSecret') -eq $true -or `
$PSBoundParameters.ContainsKey('CertificatePath') -eq $true))
{
Write-Host -Message '[ERROR] You have to specify ApplicationId and TenantId when you specify ApplicationSecret, CertificateThumbprint or CertificatePath' -ForegroundColor Red
return
throw 'You have to specify ApplicationId and TenantId when you specify ApplicationSecret, CertificateThumbprint or CertificatePath'
}

# Default to Credential if no authentication mechanism were provided
Expand Down Expand Up @@ -3093,7 +3088,7 @@ function Update-M365DSCDependencies

foreach ($dependency in $dependencies)
{
Write-Progress -Activity 'Scanning Dependencies' -PercentComplete ($i / $dependencies.Count * 100)
Write-Progress -Activity 'Scanning dependencies' -PercentComplete ($i / $dependencies.Count * 100)
try
{
if (-not $Force)
Expand Down Expand Up @@ -3136,15 +3131,14 @@ function Update-M365DSCDependencies
}
catch
{
Write-Host "Could not update or import {$($dependency.ModuleName)}"
Write-Host "Error-Mesage: $($_.Exception.Message)"
Write-Error -Message "Could not update or import {$($dependency.ModuleName)}: $($_.Exception.Message)" -ErrorAction Continue
}

$i++
}

# The progress bar seems to hang sometimes. Make sure it is no longer displayed.
Write-Progress -Activity 'Scanning Dependencies' -Completed
Write-Progress -Activity 'Scanning dependencies' -Completed

if ($ValidateOnly)
{
Expand All @@ -3154,10 +3148,10 @@ function Update-M365DSCDependencies
}
catch
{
New-M365DSCLogEntry -Message 'Error Updating Dependencies:' `
New-M365DSCLogEntry -Message 'Error updating dependencies:' `
-Exception $_ `
-Source $($MyInvocation.MyCommand.Source)
Write-Error $_
Write-Error $_ -ErrorAction Continue
}
}

Expand Down Expand Up @@ -3196,7 +3190,7 @@ function Uninstall-M365DSCOutdatedDependencies
New-M365DSCLogEntry -Message "Could not uninstall $($module.Name) Version $($module.Version)" `
-Exception $_ `
-Source $($MyInvocation.MyCommand.Source)
Write-Host "Could not uninstall $($module.Name) Version $($module.Version)"
Write-Error -Message "Could not uninstall $($module.Name) Version $($module.Version)" -ErrorAction Continue
}
}

Expand Down Expand Up @@ -3227,20 +3221,20 @@ function Uninstall-M365DSCOutdatedDependencies
New-M365DSCLogEntry -Message "Could not uninstall $($foundModule.Name) Version $($foundModule.Version)" `
-Exception $_ `
-Source $($MyInvocation.MyCommand.Source)
Write-Host "Could not uninstall $($foundModule.Name) Version $($foundModule.Version)"
Write-Error -Message "Could not uninstall $($foundModule.Name) Version $($foundModule.Version)" -ErrorAction Continue
}
}
}
catch
{
Write-Host "Could not uninstall {$($dependency.ModuleName)}"
Write-Error -Message "Could not uninstall {$($dependency.ModuleName)}" -ErrorAction Continue
}
$i++
}
}
catch
{
New-M365DSCLogEntry -Message 'Error Uninstalling Outdated Dependencies:' `
New-M365DSCLogEntry -Message 'Error uninstalling outdated dependencies:' `
-Exception $_ `
-Source $($MyInvocation.MyCommand.Source)
Write-Error $_
Expand All @@ -3263,13 +3257,13 @@ function Uninstall-M365DSCOutdatedDependencies
}
catch
{
Write-Host "Could not uninstall $($foundModule.Name) Version $($foundModule.Version) "
Write-Error -Message "Could not uninstall $($foundModule.Name) Version $($foundModule.Version)" -ErrorAction Continue
}
}
}
catch
{
Write-Host "Could not uninstall {$($dependency.ModuleName)}"
Write-Error -Message "Could not uninstall {$($dependency.ModuleName)}" -ErrorAction Continue
}
}

Expand Down
7 changes: 2 additions & 5 deletions ResourceGenerator/M365DSCResourceGenerator.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -1181,14 +1181,12 @@ function Get-MgGraphModuleCmdLetDifference

if ($modules.Count -eq 0)
{
Write-Host '[ERROR] No module selected!' -ForegroundColor Red
return
throw 'No module selected!'
}

if (($modules.Name | Sort-Object | Select-Object -Unique).Count -ne 1 -or $modules.Count -ne 2)
{
Write-Host '[ERROR] Please select two versions of the same module' -ForegroundColor Red
return
throw 'Please select two versions of the same module'
}

[array]$exportedKeysModule1 = $modules[0].ExportedCommands.Keys
Expand Down Expand Up @@ -2568,7 +2566,6 @@ function Get-M365DSCFakeValues
{
$parameterName = Get-StringFirstCharacterToLower -Value $parameterName
}
write-host -ForegroundColor Yellow $parameterName
$result.Add($parameterName, $hashValue)
}
}
Expand Down

0 comments on commit 1ec7623

Please sign in to comment.