From 09e2e63688fa5f155a6ca3050af08582bfb424d1 Mon Sep 17 00:00:00 2001 From: Michael Lombardi Date: Wed, 26 Jul 2023 10:04:25 -0500 Subject: [PATCH] (GH-110) Handle missing module in PS Group resource Prior to this change, the PowerShell group resource would fail unexpectedly for operations that didn't include the group, like invoking a different resource. When the resource's script failed to import the PSDesiredStateConfiguration module, the script errors would bubble up through any DSC invocation. For `get`, `set`, and `test` operations, this is desirable, but not for `list`, where a missing module means that the group can't provide any resources. Instead of breaking execution for other resources, the script should exit with code `0` for `list` operations. This change: - Adds logic to the beginning of the resource's script, checking for the PSDesiredStateConfiguration module. - If the module isn't found, the script raises an error. - For the list operation, the script exits with code `0` - being unable to list the DSC Resources is expected on systems that may not have the module installed and aren't trying to list PowerShell DSC Resources explicitly. For now, the script has no way to distinguish between being called for a general list operation, like before a `dsc resource get` command, and a specific list operation, like `dsc resource list DSC/PowerShellGroup`. It would make sense for the operation to exit with code `1` for the latter. - For non-list operations, the script exits with code `1`. --- powershellgroup/powershellgroup.resource.ps1 | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/powershellgroup/powershellgroup.resource.ps1 b/powershellgroup/powershellgroup.resource.ps1 index 44359873..397c0836 100644 --- a/powershellgroup/powershellgroup.resource.ps1 +++ b/powershellgroup/powershellgroup.resource.ps1 @@ -33,7 +33,20 @@ function RefreshCache } } -Import-Module PSDesiredStateConfiguration +$DscModule = Get-Module -Name PSDesiredStateConfiguration -ListAvailable | + Sort-Object -Property Version -Descending | + Select-Object -First 1 + +if ($null -eq $DscModule) +{ + Write-Error "Could not find and import the PSDesiredStateConfiguration module." + # Missing module is okay for listing resources + if ($Operation -eq 'List') { exit 0 } + + exit 1 +} + +Import-Module $DscModule if ($Operation -eq 'List') {