PowerShell-Docs-DSC icon indicating copy to clipboard operation
PowerShell-Docs-DSC copied to clipboard

Document how to invoke DSC Resources with complex properties in v1.1

Open michaeltlombardi opened this issue 1 year ago • 0 comments

Prerequisites

  • [X] Existing Issue: Search the existing issues for this repository. If there is an issue that fits your needs do not file a new one. Subscribe, react, or comment on that issue instead.
  • [X] Descriptive Title: Write the title for this issue as a short synopsis. If possible, provide context. For example, "Typo in Get-Foo cmdlet" instead of "Typo."
  • [X] Verify Version: If there is a mismatch between documentation and the module on your system, ensure that the version you are using is the same as the documentation. Check this box if they match or the issue you are reporting is not version specific.

Version

v1.1

Links

  • https://learn.microsoft.com/en-us/powershell/dsc/managing-nodes/directcallresource?view=dsc-1.1

Summary

When a user wants to invoke a DSC Resource that has complex properties in PSDSCv1.1, they need to convert the complex property into a CimInstance or the invocation errors confusingly.

Details

With the example resource definition:

[DscResource()]
class InvocableExample {
  [DscProperty(Key)] [string]      $Path
  [DscProperty()]    [Complex]     $Info
  [DscProperty()]    [VeryComplex] $Options

  [InvocableExample] Get()  { return $this }
  [bool]             Test() { return $true }
  [void]             Set()  { }
}

class Complex {
    [DscProperty()] [string] $Version
    [DscProperty()] [bool]   $StartOnBoot
}

class VeryComplex {
  [DscProperty()] [string]   $Name
  [DscProperty()] [Nested[]] $Settings
}

class Nested {
  [DscProperty()] [bool]   $Enabled
  [DscProperty()] [string] $Name
}

You can use New-CimInstance with the ClientOnly parameter to create the complex property inline for the DSC Resource's property hash:

Invoke-DscResource -Name InvocableExample -Method Get -ModuleName ExampleResources -Property @{
  Path = 'C:\dsc\example.json'
  Info = New-CimInstance -ClientOnly -ClassName Complex -Property @{
    Version = '1.1.0'
  }
}

When the property's type is an array, like [Nested[]], you need to cast the inline array to [CimInstance[]]:

$Options = New-CimInstance -ClientOnly -ClassName VeryComplex -Property @{
    Name = 'Nested Options'
    Settings = New-CimInstance -ClientOnly Nested -Property [CimInstance[]]@(
        @{ Name = 'First'  ; Enabled = $true  }
        @{ Name = 'Second' ; Enabled = $false }
    )
}

You need to convert every complex property, including nested ones, with New-CimInstance.

Suggested Fix

Extend the documentation for invoking DSC Resources in v1.1 to document this requirement.

michaeltlombardi avatar May 09 '23 16:05 michaeltlombardi