From 41ec47ead4e251c3d76581a68e88bdba857d7724 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Sat, 25 Feb 2023 23:02:58 +0100 Subject: [PATCH] ComputerManagementDsc: Class-based resources re-use module DscResource.Base (#405) * ComputerManagementDsc: Class-based resources re-use module DscResource.Base * Fix CHANGELOG.md * Fix CHANGELOG.md * Merge branch 'main' into f/remove-resourcebase Co-Authored-By: Daniel Scott-Raynsford --- CHANGELOG.md | 3 + RequiredModules.psd1 | 1 + build.yaml | 8 + source/Build.psd1 | 5 - source/Classes/010.ResourceBase.ps1 | 260 ------------------ source/Classes/020.PSResourceRepository.ps1 | 3 +- source/Enum/1.Ensure.ps1 | 9 - source/Private/ConvertFrom-CompareResult.ps1 | 44 --- source/Private/ConvertTo-Reason.ps1 | 119 -------- source/Private/Get-ClassName.ps1 | 55 ---- source/Private/Get-DscProperty.ps1 | 153 ----------- source/Private/Get-LocalizedDataRecursive.ps1 | 87 ------ .../Test-ResourceDscPropertyIsAssigned.ps1 | 40 --- .../Private/Test-ResourceHasDscProperty.ps1 | 62 ----- source/en-US/ResourceBase.strings.psd1 | 17 -- source/prefix.ps1 | 2 + 16 files changed, 16 insertions(+), 852 deletions(-) delete mode 100644 source/Build.psd1 delete mode 100644 source/Classes/010.ResourceBase.ps1 delete mode 100644 source/Enum/1.Ensure.ps1 delete mode 100644 source/Private/ConvertFrom-CompareResult.ps1 delete mode 100644 source/Private/ConvertTo-Reason.ps1 delete mode 100644 source/Private/Get-ClassName.ps1 delete mode 100644 source/Private/Get-DscProperty.ps1 delete mode 100644 source/Private/Get-LocalizedDataRecursive.ps1 delete mode 100644 source/Private/Test-ResourceDscPropertyIsAssigned.ps1 delete mode 100644 source/Private/Test-ResourceHasDscProperty.ps1 delete mode 100644 source/en-US/ResourceBase.strings.psd1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 83848987..4f9376f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 in the module manifest in the source folder as the built module is automatically updated with this information by the pipeline - Fixes [Issue #396](https://github.com/dsccommunity/ComputerManagementDsc/issues/396). - Moved the build step of the pipeline to a Windows build worker when running in Azure DevOps. + - The class-based resources are now re-using the module DscResource.Base - Fixes [Issue #404](https://github.com/dsccommunity/ComputerManagementDsc/issues/404). + - Removed the file `source/build.psd1` as it is no longer required for the + build pipeline. ## [8.5.0] - 2021-09-13 diff --git a/RequiredModules.psd1 b/RequiredModules.psd1 index 78a848aa..6dc94f03 100644 --- a/RequiredModules.psd1 +++ b/RequiredModules.psd1 @@ -20,6 +20,7 @@ 'DscResource.AnalyzerRules' = 'latest' 'DscResource.DocGenerator' = 'latest' 'DscResource.Common' = 'latest' + 'DscResource.Base' = 'latest' xDscResourceDesigner = 'latest' LoopbackAdapter = 'latest' } diff --git a/build.yaml b/build.yaml index a5ffa612..246b1795 100644 --- a/build.yaml +++ b/build.yaml @@ -21,6 +21,12 @@ NestedModule: AddToManifest: false Exclude: PSGetModuleInfo.xml + DscResource.Base: + CopyOnly: true + Path: ./output/RequiredModules/DscResource.Base + AddToManifest: false + Exclude: PSGetModuleInfo.xml + #################################################### # Pipeline Configuration # #################################################### @@ -62,6 +68,7 @@ Pester: OutputFormat: NUnitXML ExcludeFromCodeCoverage: - Modules/DscResource.Common + - Modules/DscResource.Base Script: - tests/Unit ExcludeTag: @@ -78,6 +85,7 @@ DscTest: - output ExcludeModuleFile: - Modules/DscResource.Common + - Modules/DscResource.Base MainGitBranch: main Resolve-Dependency: diff --git a/source/Build.psd1 b/source/Build.psd1 deleted file mode 100644 index 3009ed89..00000000 --- a/source/Build.psd1 +++ /dev/null @@ -1,5 +0,0 @@ -@{ - Path = 'ComputerManagementDsc.psd1' -} -# Waiting for ModuleBuilder to do away with this file -# when all parameters are provided to the function diff --git a/source/Classes/010.ResourceBase.ps1 b/source/Classes/010.ResourceBase.ps1 deleted file mode 100644 index 881c81fe..00000000 --- a/source/Classes/010.ResourceBase.ps1 +++ /dev/null @@ -1,260 +0,0 @@ -<# - .SYNOPSIS - A class with methods that are equal for all class-based resources. - - .DESCRIPTION - A class with methods that are equal for all class-based resources. - - .NOTES - This class should be able to be inherited by all DSC resources. This class - shall not contain any DSC properties, neither shall it contain anything - specific to only a single resource. -#> - -class ResourceBase -{ - # Property for holding localization strings - hidden [System.Collections.Hashtable] $localizedData = @{} - - # Property for derived class to set properties that should not be enforced. - hidden [System.String[]] $ExcludeDscProperties = @() - - # Default constructor - ResourceBase() - { - <# - TODO: When this fails, for example when the localized string file is missing - the LCM returns the error 'Failed to create an object of PowerShell - class SqlDatabasePermission' instead of the actual error that occurred. - #> - $this.localizedData = Get-LocalizedDataRecursive -ClassName ($this | Get-ClassName -Recurse) - } - - [ResourceBase] Get() - { - $this.Assert() - - # Get all key properties. - $keyProperty = $this | Get-DscProperty -Type 'Key' - - Write-Verbose -Message ($this.localizedData.GetCurrentState -f $this.GetType().Name, ($keyProperty | ConvertTo-Json -Compress)) - - $getCurrentStateResult = $this.GetCurrentState($keyProperty) - - $dscResourceObject = [System.Activator]::CreateInstance($this.GetType()) - - # Set values returned from the derived class' GetCurrentState(). - foreach ($propertyName in $this.PSObject.Properties.Name) - { - if ($propertyName -in @($getCurrentStateResult.Keys)) - { - $dscResourceObject.$propertyName = $getCurrentStateResult.$propertyName - } - } - - $keyPropertyAddedToCurrentState = $false - - # Set key property values unless it was returned from the derived class' GetCurrentState(). - foreach ($propertyName in $keyProperty.Keys) - { - if ($propertyName -notin @($getCurrentStateResult.Keys)) - { - # Add the key value to the instance to be returned. - $dscResourceObject.$propertyName = $this.$propertyName - - $keyPropertyAddedToCurrentState = $true - } - } - - if (($this | Test-ResourceHasDscProperty -Name 'Ensure') -and -not $getCurrentStateResult.ContainsKey('Ensure')) - { - # Evaluate if we should set Ensure property. - if ($keyPropertyAddedToCurrentState) - { - <# - A key property was added to the current state, assume its because - the object did not exist in the current state. Set Ensure to Absent. - #> - $dscResourceObject.Ensure = [Ensure]::Absent - $getCurrentStateResult.Ensure = [Ensure]::Absent - } - else - { - $dscResourceObject.Ensure = [Ensure]::Present - $getCurrentStateResult.Ensure = [Ensure]::Present - } - } - - <# - Returns all enforced properties not in desires state, or $null if - all enforced properties are in desired state. - #> - $propertiesNotInDesiredState = $this.Compare($getCurrentStateResult, @()) - - <# - Return the correct values for Reasons property if the derived DSC resource - has such property and it hasn't been already set by GetCurrentState(). - #> - if (($this | Test-ResourceHasDscProperty -Name 'Reasons') -and -not $getCurrentStateResult.ContainsKey('Reasons')) - { - # Always return an empty array if all properties are in desired state. - $dscResourceObject.Reasons = $propertiesNotInDesiredState | - ConvertTo-Reason -ResourceName $this.GetType().Name - } - - # Return properties. - return $dscResourceObject - } - - [void] Set() - { - # Get all key properties. - $keyProperty = $this | Get-DscProperty -Type 'Key' - - Write-Verbose -Message ($this.localizedData.SetDesiredState -f $this.GetType().Name, ($keyProperty | ConvertTo-Json -Compress)) - - $this.Assert() - - <# - Returns all enforced properties not in desires state, or $null if - all enforced properties are in desired state. - #> - $propertiesNotInDesiredState = $this.Compare() - - if ($propertiesNotInDesiredState) - { - $propertiesToModify = $propertiesNotInDesiredState | ConvertFrom-CompareResult - - $propertiesToModify.Keys | - ForEach-Object -Process { - Write-Verbose -Message ($this.localizedData.SetProperty -f $_, $propertiesToModify.$_) - } - - <# - Call the Modify() method with the properties that should be enforced - and was not in desired state. - #> - $this.Modify($propertiesToModify) - } - else - { - Write-Verbose -Message $this.localizedData.NoPropertiesToSet - } - } - - [System.Boolean] Test() - { - # Get all key properties. - $keyProperty = $this | Get-DscProperty -Type 'Key' - - Write-Verbose -Message ($this.localizedData.TestDesiredState -f $this.GetType().Name, ($keyProperty | ConvertTo-Json -Compress)) - - $this.Assert() - - $isInDesiredState = $true - - <# - Returns all enforced properties not in desires state, or $null if - all enforced properties are in desired state. - #> - $propertiesNotInDesiredState = $this.Compare() - - if ($propertiesNotInDesiredState) - { - $isInDesiredState = $false - } - - if ($isInDesiredState) - { - Write-Verbose $this.localizedData.InDesiredState - } - else - { - Write-Verbose $this.localizedData.NotInDesiredState - } - - return $isInDesiredState - } - - <# - Returns a hashtable containing all properties that should be enforced and - are not in desired state, or $null if all enforced properties are in - desired state. - - This method should normally not be overridden. - #> - hidden [System.Collections.Hashtable[]] Compare() - { - # Get the current state, all properties except Read properties . - $currentState = $this.Get() | Get-DscProperty -Type @('Key', 'Mandatory', 'Optional') - - return $this.Compare($currentState, @()) - } - - <# - Returns a hashtable containing all properties that should be enforced and - are not in desired state, or $null if all enforced properties are in - desired state. - - This method should normally not be overridden. - #> - hidden [System.Collections.Hashtable[]] Compare([System.Collections.Hashtable] $currentState, [System.String[]] $excludeProperties) - { - # Get the desired state, all assigned properties that has an non-null value. - $desiredState = $this | Get-DscProperty -Type @('Key', 'Mandatory', 'Optional') -HasValue - - $CompareDscParameterState = @{ - CurrentValues = $currentState - DesiredValues = $desiredState - Properties = $desiredState.Keys - ExcludeProperties = ($excludeProperties + $this.ExcludeDscProperties) | Select-Object -Unique - IncludeValue = $true - # This is needed to sort complex types. - SortArrayValues = $true - } - - <# - Returns all enforced properties not in desires state, or $null if - all enforced properties are in desired state. - #> - return (Compare-DscParameterState @CompareDscParameterState) - } - - # This method should normally not be overridden. - hidden [void] Assert() - { - # Get the properties that has a non-null value and is not of type Read. - $desiredState = $this | Get-DscProperty -Type @('Key', 'Mandatory', 'Optional') -HasValue - - $this.AssertProperties($desiredState) - } - - <# - This method can be overridden if resource specific property asserts are - needed. The parameter properties will contain the properties that was - assigned a value. - #> - [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('AvoidEmptyNamedBlocks', '')] - hidden [void] AssertProperties([System.Collections.Hashtable] $properties) - { - } - - <# - This method must be overridden by a resource. The parameter properties will - contain the properties that should be enforced and that are not in desired - state. - #> - hidden [void] Modify([System.Collections.Hashtable] $properties) - { - throw $this.localizedData.ModifyMethodNotImplemented - } - - <# - This method must be overridden by a resource. The parameter properties will - contain the key properties. - #> - hidden [System.Collections.Hashtable] GetCurrentState([System.Collections.Hashtable] $properties) - { - throw $this.localizedData.GetCurrentStateMethodNotImplemented - } -} diff --git a/source/Classes/020.PSResourceRepository.ps1 b/source/Classes/020.PSResourceRepository.ps1 index e6808cf9..fd620206 100644 --- a/source/Classes/020.PSResourceRepository.ps1 +++ b/source/Classes/020.PSResourceRepository.ps1 @@ -112,7 +112,8 @@ class PSResourceRepository : ResourceBase [Nullable[System.Boolean]] $Default - PSResourceRepository () : base () + # Passing the module's base directory to the base constructor so it finds localization files. + PSResourceRepository () : base ($PSScriptRoot) { # These properties will not be enforced. $this.ExcludeDscProperties = @( diff --git a/source/Enum/1.Ensure.ps1 b/source/Enum/1.Ensure.ps1 deleted file mode 100644 index 4cfd9e73..00000000 --- a/source/Enum/1.Ensure.ps1 +++ /dev/null @@ -1,9 +0,0 @@ -<# - .SYNOPSIS - The possible states for the DSC resource parameter Ensure. -#> -enum Ensure -{ - Present - Absent -} diff --git a/source/Private/ConvertFrom-CompareResult.ps1 b/source/Private/ConvertFrom-CompareResult.ps1 deleted file mode 100644 index a917e70b..00000000 --- a/source/Private/ConvertFrom-CompareResult.ps1 +++ /dev/null @@ -1,44 +0,0 @@ -<# - .SYNOPSIS - Returns a hashtable with property name and their expected value. - - .PARAMETER CompareResult - The result from Compare-DscParameterState. - - .EXAMPLE - ConvertFrom-CompareResult -CompareResult (Compare-DscParameterState) - - Returns a hashtable that contain all the properties not in desired state - and their expected value. - - .OUTPUTS - [System.Collections.Hashtable] -#> -function ConvertFrom-CompareResult -{ - [CmdletBinding()] - [OutputType([System.Collections.Hashtable])] - param - ( - [Parameter(Mandatory = $true, ValueFromPipeline = $true)] - [System.Collections.Hashtable[]] - $CompareResult - ) - - begin - { - $returnHashtable = @{} - } - - process - { - $CompareResult | ForEach-Object -Process { - $returnHashtable[$_.Property] = $_.ExpectedValue - } - } - - end - { - return $returnHashtable - } -} diff --git a/source/Private/ConvertTo-Reason.ps1 b/source/Private/ConvertTo-Reason.ps1 deleted file mode 100644 index 65862736..00000000 --- a/source/Private/ConvertTo-Reason.ps1 +++ /dev/null @@ -1,119 +0,0 @@ -<# - .SYNOPSIS - Returns a array of the type `[Reason]`. - - .DESCRIPTION - This command converts the array of properties that is returned by the command - `Compare-DscParameterState`. The result is an array of the type `[Reason]` that - can be returned in a DSC resource's property **Reasons**. - - .PARAMETER Property - The result from the command Compare-DscParameterState. - - .PARAMETER ResourceName - The name of the resource. Will be used to populate the property Code with - the correct value. - - .EXAMPLE - ConvertTo-Reason -Property (Compare-DscParameterState) -ResourceName 'MyResource' - - Returns an array of `[Reason]` that contain all the properties not in desired - state and why a specific property is not in desired state. - - .OUTPUTS - [Reason[]] -#> -function ConvertTo-Reason -{ - [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('UseSyntacticallyCorrectExamples', '', Justification = 'Because the rule does not yet support parsing the code when the output type is not available. The ScriptAnalyzer rule UseSyntacticallyCorrectExamples will always error in the editor due to https://github.com/indented-automation/Indented.ScriptAnalyzerRules/issues/8.')] - [CmdletBinding()] - [OutputType([Reason[]])] - param - ( - [Parameter(Mandatory = $true, ValueFromPipeline = $true)] - [AllowEmptyCollection()] - [AllowNull()] - [System.Collections.Hashtable[]] - $Property, - - [Parameter(Mandatory = $true)] - [System.String] - $ResourceName - ) - - begin - { - # Always return an empty array if there are no properties to add. - $reasons = [Reason[]] @() - } - - process - { - foreach ($currentProperty in $Property) - { - if ($currentProperty.ExpectedValue -is [System.Enum]) - { - # Return the string representation of the value (instead of the numeric value). - $propertyExpectedValue = $currentProperty.ExpectedValue.ToString() - } - else - { - $propertyExpectedValue = $currentProperty.ExpectedValue - } - - if ($property.ActualValue -is [System.Enum]) - { - # Return the string representation of the value so that conversion to json is correct. - $propertyActualValue = $currentProperty.ActualValue.ToString() - } - else - { - $propertyActualValue = $currentProperty.ActualValue - } - - <# - In PowerShell 7 the command ConvertTo-Json returns 'null' on null - value, but not in Windows PowerShell. Switch to output empty string - if value is null. - #> - if ($PSVersionTable.PSEdition -eq 'Desktop') - { - if ($null -eq $propertyExpectedValue) - { - $propertyExpectedValue = '' - } - - if ($null -eq $propertyActualValue) - { - $propertyActualValue = '' - } - } - - # Convert the value to Json to be able to easily visualize complex types - $propertyActualValueJson = $propertyActualValue | ConvertTo-Json -Compress - $propertyExpectedValueJson = $propertyExpectedValue | ConvertTo-Json -Compress - - # If the property name contain the word Path, remove '\\' from path. - if ($currentProperty.Property -match 'Path') - { - $propertyActualValueJson = $propertyActualValueJson -replace '\\\\', '\' - $propertyExpectedValueJson = $propertyExpectedValueJson -replace '\\\\', '\' - } - - $reasons += [Reason] @{ - Code = '{0}:{0}:{1}' -f $ResourceName, $currentProperty.Property - # Convert the object to JSON to handle complex types. - Phrase = 'The property {0} should be {1}, but was {2}' -f @( - $currentProperty.Property, - $propertyExpectedValueJson, - $propertyActualValueJson - ) - } - } - } - - end - { - return $reasons - } -} diff --git a/source/Private/Get-ClassName.ps1 b/source/Private/Get-ClassName.ps1 deleted file mode 100644 index 06745e02..00000000 --- a/source/Private/Get-ClassName.ps1 +++ /dev/null @@ -1,55 +0,0 @@ -<# - .SYNOPSIS - Get the class name of the passed object, and optional an array with - all inherited classes. - - .PARAMETER InputObject - The object to be evaluated. - - .PARAMETER Recurse - Specifies if the class name of inherited classes shall be returned. The - recursive stops when the first object of the type `[System.Object]` is - found. - - .EXAMPLE - Get-ClassName -InputObject $this -Recurse - - Get the class name of the current instance and all the inherited (parent) - classes. - - .OUTPUTS - [System.String[]] -#> -function Get-ClassName -{ - [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseOutputTypeCorrectly', '', Justification = 'Because the rule does not understands that the command returns [System.String[]] when using , (comma) in the return statement')] - [CmdletBinding()] - [OutputType([System.String[]])] - param - ( - [Parameter(Mandatory = $true, ValueFromPipeline = $true)] - [PSObject] - $InputObject, - - [Parameter()] - [System.Management.Automation.SwitchParameter] - $Recurse - ) - - # Create a list of the inherited class names - $class = @($InputObject.GetType().FullName) - - if ($Recurse.IsPresent) - { - $parentClass = $InputObject.GetType().BaseType - - while ($parentClass -ne [System.Object]) - { - $class += $parentClass.FullName - - $parentClass = $parentClass.BaseType - } - } - - return , [System.String[]] $class -} diff --git a/source/Private/Get-DscProperty.ps1 b/source/Private/Get-DscProperty.ps1 deleted file mode 100644 index 481842c8..00000000 --- a/source/Private/Get-DscProperty.ps1 +++ /dev/null @@ -1,153 +0,0 @@ - -<# - .SYNOPSIS - Returns DSC resource properties that is part of a class-based DSC resource. - - .DESCRIPTION - Returns DSC resource properties that is part of a class-based DSC resource. - The properties can be filtered using name, type, or has been assigned a value. - - .PARAMETER InputObject - The object that contain one or more key properties. - - .PARAMETER Name - Specifies one or more property names to return. If left out all properties - are returned. - - .PARAMETER Type - Specifies one or more property types to return. If left out all property - types are returned. - - .PARAMETER HasValue - Specifies to return only properties that has been assigned a non-null value. - If left out all properties are returned regardless if there is a value - assigned or not. - - .EXAMPLE - Get-DscProperty -InputObject $this - - Returns all DSC resource properties of the DSC resource. - - .EXAMPLE - Get-DscProperty -InputObject $this -Name @('MyProperty1', 'MyProperty2') - - Returns the specified DSC resource properties names of the DSC resource. - - .EXAMPLE - Get-DscProperty -InputObject $this -Type @('Mandatory', 'Optional') - - Returns the specified DSC resource property types of the DSC resource. - - .EXAMPLE - Get-DscProperty -InputObject $this -Type @('Optional') -HasValue - - Returns the specified DSC resource property types of the DSC resource, - but only those properties that has been assigned a non-null value. - - .OUTPUTS - [System.Collections.Hashtable] -#> -function Get-DscProperty -{ - [CmdletBinding()] - [OutputType([System.Collections.Hashtable])] - param - ( - [Parameter(Mandatory = $true, ValueFromPipeline = $true)] - [PSObject] - $InputObject, - - [Parameter()] - [System.String[]] - $Name, - - [Parameter()] - [System.String[]] - $ExcludeName, - - [Parameter()] - [ValidateSet('Key', 'Mandatory', 'NotConfigurable', 'Optional')] - [System.String[]] - $Type, - - [Parameter()] - [System.Management.Automation.SwitchParameter] - $HasValue - ) - - $property = $InputObject.PSObject.Properties.Name | - Where-Object -FilterScript { - <# - Return all properties if $Name is not assigned, or if assigned - just those properties. - #> - (-not $Name -or $_ -in $Name) -and - - <# - Return all properties if $ExcludeName is not assigned. Skip - property if it is included in $ExcludeName. - #> - (-not $ExcludeName -or ($_ -notin $ExcludeName)) -and - - # Only return the property if it is a DSC property. - $InputObject.GetType().GetMember($_).CustomAttributes.Where( - { - $_.AttributeType.Name -eq 'DscPropertyAttribute' - } - ) - } - - if (-not [System.String]::IsNullOrEmpty($property)) - { - if ($PSBoundParameters.ContainsKey('Type')) - { - $propertiesOfType = @() - - $propertiesOfType += $property | Where-Object -FilterScript { - $InputObject.GetType().GetMember($_).CustomAttributes.Where( - { - <# - To simplify the code, ignoring that this will compare - MemberNAme against type 'Optional' which does not exist. - #> - $_.NamedArguments.MemberName -in $Type - } - ).NamedArguments.TypedValue.Value -eq $true - } - - # Include all optional parameter if it was requested. - if ($Type -contains 'Optional') - { - $propertiesOfType += $property | Where-Object -FilterScript { - $InputObject.GetType().GetMember($_).CustomAttributes.Where( - { - $_.NamedArguments.MemberName -notin @('Key', 'Mandatory', 'NotConfigurable') - } - ) - } - } - - $property = $propertiesOfType - } - } - - # Return a hashtable containing each key property and its value. - $getPropertyResult = @{} - - foreach ($currentProperty in $property) - { - if ($HasValue.IsPresent) - { - $isAssigned = Test-ResourceDscPropertyIsAssigned -Name $currentProperty -InputObject $InputObject - - if (-not $isAssigned) - { - continue - } - } - - $getPropertyResult.$currentProperty = $InputObject.$currentProperty - } - - return $getPropertyResult -} diff --git a/source/Private/Get-LocalizedDataRecursive.ps1 b/source/Private/Get-LocalizedDataRecursive.ps1 deleted file mode 100644 index b32e18ae..00000000 --- a/source/Private/Get-LocalizedDataRecursive.ps1 +++ /dev/null @@ -1,87 +0,0 @@ -<# - .SYNOPSIS - Get the localization strings data from one or more localization string files. - This can be used in classes to be able to inherit localization strings - from one or more parent (base) classes. - - The order of class names passed to parameter `ClassName` determines the order - of importing localization string files. First entry's localization string file - will be imported first, then next entry's localization string file, and so on. - If the second (or any consecutive) entry's localization string file contain a - localization string key that existed in a previous imported localization string - file that localization string key will be ignored. Making it possible for a - child class to override localization strings from one or more parent (base) - classes. - - .PARAMETER ClassName - An array of class names, normally provided by `Get-ClassName -Recurse`. - - .EXAMPLE - Get-LocalizedDataRecursive -ClassName $InputObject.GetType().FullName - - Returns a hashtable containing all the localized strings for the current - instance. - - .EXAMPLE - Get-LocalizedDataRecursive -ClassName (Get-ClassNamn -InputObject $this -Recurse) - - Returns a hashtable containing all the localized strings for the current - instance and any inherited (parent) classes. - - .OUTPUTS - [System.Collections.Hashtable] -#> -function Get-LocalizedDataRecursive -{ - [CmdletBinding()] - [OutputType([System.Collections.Hashtable])] - param - ( - [Parameter(Mandatory = $true, ValueFromPipeline = $true)] - [System.String[]] - $ClassName - ) - - begin - { - $localizedData = @{} - } - - process - { - foreach ($name in $ClassName) - { - if ($name -match '\.psd1') - { - # Assume we got full file name. - $localizationFileName = $name - } - else - { - # Assume we only got class name. - $localizationFileName = '{0}.strings.psd1' -f $name - } - - Write-Debug -Message ('Importing localization data from {0}' -f $localizationFileName) - - # Get localized data for the class - $classLocalizationStrings = Get-LocalizedData -DefaultUICulture 'en-US' -FileName $localizationFileName -ErrorAction 'Stop' - - # Append only previously unspecified keys in the localization data - foreach ($key in $classLocalizationStrings.Keys) - { - if (-not $localizedData.ContainsKey($key)) - { - $localizedData[$key] = $classLocalizationStrings[$key] - } - } - } - } - - end - { - Write-Debug -Message ('Localization data: {0}' -f ($localizedData | ConvertTo-JSON)) - - return $localizedData - } -} diff --git a/source/Private/Test-ResourceDscPropertyIsAssigned.ps1 b/source/Private/Test-ResourceDscPropertyIsAssigned.ps1 deleted file mode 100644 index 5be5685d..00000000 --- a/source/Private/Test-ResourceDscPropertyIsAssigned.ps1 +++ /dev/null @@ -1,40 +0,0 @@ -<# - .SYNOPSIS - Tests whether the class-based resource property is assigned a non-null value. - - .DESCRIPTION - Tests whether the class-based resource property is assigned a non-null value. - - .PARAMETER InputObject - Specifies the object that contain the property. - - .PARAMETER Name - Specifies the name of the property. - - .EXAMPLE - Test-ResourceDscPropertyIsAssigned -InputObject $this -Name 'MyDscProperty' - - Returns $true or $false whether the property is assigned or not. - - .OUTPUTS - [System.Boolean] -#> -function Test-ResourceDscPropertyIsAssigned -{ - [CmdletBinding()] - [OutputType([System.Boolean])] - param - ( - [Parameter(Mandatory = $true, ValueFromPipeline = $true)] - [PSObject] - $InputObject, - - [Parameter(Mandatory = $true)] - [System.String] - $Name - ) - - $isAssigned = -not ($null -eq $InputObject.$Name) - - return $isAssigned -} diff --git a/source/Private/Test-ResourceHasDscProperty.ps1 b/source/Private/Test-ResourceHasDscProperty.ps1 deleted file mode 100644 index 775582cf..00000000 --- a/source/Private/Test-ResourceHasDscProperty.ps1 +++ /dev/null @@ -1,62 +0,0 @@ -<# - .SYNOPSIS - Tests whether the class-based resource has the specified property. - - .DESCRIPTION - Tests whether the class-based resource has the specified property. - - .PARAMETER InputObject - Specifies the object that should be tested for existens of the specified - property. - - .PARAMETER Name - Specifies the name of the property. - - .PARAMETER HasValue - Specifies if the property should be evaluated to have a non-value. If - the property exist but is assigned `$null` the command returns `$false`. - - .EXAMPLE - Test-ResourceHasDscProperty -InputObject $this -Name 'MyDscProperty' - - Returns $true or $false whether the property exist or not. - - .EXAMPLE - Test-ResourceHasDscProperty -InputObject $this -Name 'MyDscProperty' -HasValue - - Returns $true if the property exist and is assigned a non-null value, if not - $false is returned. - - .OUTPUTS - [System.Boolean] -#> -function Test-ResourceHasDscProperty -{ - [CmdletBinding()] - [OutputType([System.Boolean])] - param - ( - [Parameter(Mandatory = $true, ValueFromPipeline = $true)] - [PSObject] - $InputObject, - - [Parameter(Mandatory = $true)] - [System.String] - $Name, - - [Parameter()] - [System.Management.Automation.SwitchParameter] - $HasValue - ) - - $hasProperty = $false - - $isDscProperty = (Get-DscProperty @PSBoundParameters).ContainsKey($Name) - - if ($isDscProperty) - { - $hasProperty = $true - } - - return $hasProperty -} diff --git a/source/en-US/ResourceBase.strings.psd1 b/source/en-US/ResourceBase.strings.psd1 deleted file mode 100644 index 05f4ff47..00000000 --- a/source/en-US/ResourceBase.strings.psd1 +++ /dev/null @@ -1,17 +0,0 @@ -<# - .SYNOPSIS - The localized resource strings in English (en-US) for the - class ResourceBase. -#> - -ConvertFrom-StringData @' - GetCurrentState = Getting the current state for resource '{0}' using the key property '{1}'. (RB0001) - TestDesiredState = Determining the current state for resource '{0}' using the key property '{1}'. (RB0002) - SetDesiredState = Setting the desired state for resource '{0}' using the key property '{1}'. (RB0003) - NotInDesiredState = The current state is not the desired state. (RB0004) - InDesiredState = The current state is the desired state. (RB0005) - SetProperty = The property '{0}' will be set to '{1}'. (RB0006) - NoPropertiesToSet = All properties are in desired state. (RB0007) - ModifyMethodNotImplemented = An override for the method Modify() is not implemented in the resource. (RB0008) - GetCurrentStateMethodNotImplemented = An override for the method GetCurrentState() is not implemented in the resource. (RB0009) -'@ diff --git a/source/prefix.ps1 b/source/prefix.ps1 index fe46d7df..52e8c878 100644 --- a/source/prefix.ps1 +++ b/source/prefix.ps1 @@ -1,3 +1,5 @@ +using module .\Modules\DscResource.Base + $script:dscResourceCommonModulePath = Join-Path -Path $PSScriptRoot -ChildPath 'Modules/DscResource.Common' Import-Module -Name $script:dscResourceCommonModulePath