GithubHelp home page GithubHelp logo

powershell / psdesiredstateconfiguration Goto Github PK

View Code? Open in Web Editor NEW
49.0 16.0 13.0 246 KB

Source for https://www.powershellgallery.com/packages/PSDesiredStateConfiguration module

License: MIT License

PowerShell 65.46% C# 34.54%

psdesiredstateconfiguration's Introduction

PSDesiredStateConfiguration module

Note

The next generation of this platform is in development. Please submit your feedback on DSC v3.

PSDesiredStateConfiguration (DSC) is the PowerShell module that enables writing configuration as code.

The DSC platform was originally built on top of WMI for Windows. Starting in PowerShell 7.1 and working with internal partner teams Azure Guest Configuration and Automanage, we started making DSC cross-platform by enabling Invoke-DSCResource to directly use resources without going through the Local Configuration Manager (LCM).

Our initial cross-platform work to enable partner teams:

  • Separated out the DSC parts in the PowerShell engine and moved them as a subsystem into the PSDesiredStateConfiguration module
  • Remove PSDesiredStateConfiguration module from the PowerShell 7 package. This allows the PSDesiredStateConfiguration module to be developed independently of PowerShell and users can mix and match versions of PowerShell and PSDesiredStateConfiguration for their environment.
  • Removing the dependency on MOF: Initially, only support DSC Resources written as PowerShell classes. This includes tooling to convert existing script based DSC Resources to be wrapped as PowerShell classes.

Documentation and resources

The documentation for PSDesiredStateConfiguration 3.0.0-beta1 is a work-in-progress. We invite the community to review the documentation and assist us as we work on new documentation during the platform development.

For more information about DSC v3, see PowerShell Desired State Configuration Overview

To download the latest release from the PowerShell Gallery, see PSDesiredStateConfiguration 3.0.0-beta1

Community Feedback

As we continue this journey to make DSC a cross-platform technology, we invite the community to share your ideas and open issues. During the PowerShell 7.3 timeframe, we remain focused on enabling partner teams and will not be accepting public pull requests.

Build

Requirements

Build Process

  • Run build.ps1 -Build -Clean
  • Compiled module will be in ./out/PSDesiredStateConfiguration

CI - Continuous Integration

CI pipeline definition is in .vsts-ci\azure-pipelines-ci.yml and running Compliance and Pester tests in test\PSDesiredStateConfiguration.Tests.ps1 on Windows, Linux and Mac. CI builds are not signed.

Publishing Releases

The module is released on Powershell Gallery. For a release the code of this repo is mirrored into an internal repo and .vsts-ci\azure-pipelines-release.yml pipeline is run. Release builds are signed.

psdesiredstateconfiguration's People

Contributors

adityapatwardhan avatar amitsara avatar anmenaga avatar bagajjal avatar indhukrishna avatar mgreenegit avatar michaeltlombardi avatar stevel-msft avatar thejasonhelmick avatar travisez13 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

psdesiredstateconfiguration's Issues

PSDesiredStateConfiguration 2.0.5 Get-DscResource Returns Incorrect Resources on Windows

Prerequisites

Steps to reproduce

I am experiencing a problem with the PSDesiredStateConfiguration 2.0.5 module. The Get-DscResource function does not return the correct resources when run on windows. The private Get-DscResourceModules function splits the current PSModulePath using a colon instead of the platform specific path separator, which I believe to be the problem.

I have created a repository that demonstrates the problem. The repository has an xUnit.net test project that outlines a couple of scenarios showing the error. I have also documented a potential fix for the issue in the repository at this commit.

Expected behavior

PS> Get-DscResource
# Any dsc resource in PSModulePath

Actual behavior

PS> Get-DscResource
# returns nothing

Error details

No response

Environment data

PSVersion                7.2.2
PSEdition                Core
GitCommitId              7.2.2
OS                       Microsoft Windows 10.0.19043
Platform                  Win32NT
PSCompatibleVersions      {1.0, 2.0, 3.0, 4.0, 5.0, 5.1.10032.0, 6.0.0, 6.1.0, 6.2.0, 7.0.0, 7.1.0, 7.2.2}
PSRemotingProtocolVersion 2.3
SerializationVersion      1.1.0.1
WSManStackVersion         3.0

Visuals

No response

Get-DscResource doesn't identify the class based DSC resource

Prerequisites

Steps to reproduce

Get-DscResource doesn't show class-based DSC resources if the PSD1 has all of these CmdletsToExport, FunctionsToExport, AliasesToExport. To mitigate the issues, one of them has to be commented.
This is a bug introduced during the PowerShell performance related changes. Andrew Menagarishvili has looked into the code and confirmed this bug.

Expected behavior

Get-DscResources should return DSC resources

Actual behavior

Get-DscResource doesn't show the DSC resource

Error details

No error.

Environment data

Observed with OpenSSH V7.1+.

Visuals

Get-DSCResource doesn't show the class-based DSC resource

image

With workaround by commenting functionsToExport, Get-DscResource shows the class-based DSC Resource

image

Invoke-DscResource does not validate required properties

Prerequisites

  • Write a descriptive title.
  • Make sure you are able to repro it on the latest released version
  • Search the existing issues.

Steps to reproduce

If you invoke a resource without the required properties no error is thrown.

Expected behavior

# Error is thrown when required properties are not provided

Actual behavior

# No error

Error details

No response

Environment data

7.4-preview2

Version

2.0.6

Visuals

No response

Get-DscResource is case sensitive to the resource name if module is not specified

On PowerShell Core:

Get-DscResource -Name PsModule

Expected

ResourceType  : MSFT_PSModule                                                                                                                                                                                            
Name          : PSModule                                                                                                                                                                                                  
FriendlyName  : PSModule                                                                                                                                                                                                  
Module        : PowerShellGet                                                                                                                                                                                             
ModuleName    : PowerShellGet                                                                                                                                                                                             
Version       : 2.2                                                                                                                                                                                                       
Path          : /usr/local/microsoft/powershell/7-preview/Modules/PowerShellGet/DscResources/MSFT_PSModule/MSFT_PSModule.psm1                                                                                             
ParentPath    : /usr/local/microsoft/powershell/7-preview/Modules/PowerShellGet/DscResources/MSFT_PSModule                                                                                                                
ImplementedAs : PowerShell                                                                                                                                                                                                
CompanyName   : Microsoft Corporation                                                                                                                                                                                     
Properties    : {Name, AllowClobber, DependsOn, Ensure…}

Actual

CheckResourceFound : The term 'psmodule' is not recognized as the name of a Resource.                                                                     
At C:\program files\powershell\7-preview\Modules\PSDesiredStateConfiguration\PSDesiredStateConfiguration.psm1:3991 char:13                                
+             CheckResourceFound $Name $Resources                                                                                                         
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                                                                                                         
+ CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException                                                                            
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,CheckResourceFound    

Workaround

Get-DscResource -Name PsModule -Module PowerShellGet

Get-DscResource does not return resources in NestedModules

Prerequisites

  • Write a descriptive title.
  • Make sure you are able to repro it on the latest released version
  • Search the existing issues.

Steps to reproduce

I am using the NewFile example in the docs. If the module containing the DSC resources is changed from RootModule to NestedModules then Get-DscResource will not return the module's resources.

The docs mention that this is a valid configuration: Class-based resources

A class-based DSC Resource is defined as a PowerShell class in a module file (.psm1). The class-based DSC Resource doesn't have special requirements for where it's defined. You can define it:

In the root module, like MyModule.psm1
In a nested module, like MyDscResource.psm1

Expected behavior

# resources are returned

Actual behavior

# resources are not returned

Error details

No response

Environment data

Name                           Value
----                           -----
PSVersion                      7.3.3
PSEdition                      Core
GitCommitId                    7.3.3
OS                             Microsoft Windows 10.0.19044
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Version

3.0-beta1

Visuals

No response

Support distinguishing between default and explicit values for value type properties

Summary of the new feature / enhancement

As a DSC Resource author writing resources as PowerShell classes, I want to be able to distinguish between whether a [value type][01] property has been explicitly set or is the default value. For PowerShell classes, [reference type][02] properties, like strings and complex properties (objects), the property value is $null when not explicitly set.

For value type properties, like booleans and integers, the property has a default value when the class is initialized. In the Test() and Set() methods for a resource, the resource can't distinguish between whether the property is its default value (and should be ignored for optional properties) or was explicitly set (and should be used).

The only workarounds for this are:

  1. Make all value-type properties mandatory properties.
  2. Give all value-type properties a semantically definitive default value.

1 - Mandatory value-type properties

The first option artificially limits how a resource can manage a component in ways that may not map to the reality of configuration for that component. Especially if a resource has more than one or two value-type properties.

2 - Default values for value-type properties

The second option works okay for numeric types that can't be set to 0, like the weeks interval for scheduled tasks. Because numerics default to 0, you can be sure that a 0 value indicates the value wasn't explicitly set (and throw an error on invalid value if a user does try to set it).

For enums, this option can work okay. It's common for the $Ensure property. However, if the enum doesn't have a default value in the managed component, then the definition needs to be something like:

enum MyKind {
  Undefined
  Foo
  Bar
  Baz
}

[DscResource()]
class MyResource {
  [DscProperty()] [MyKind] [ValidateSet(
    'Foo',
    'Bar',
    'Baz'
  )] $Kind

  [DscProperty(Key)] [string] $Path

  [MyResource] Get()  { return [MyResource]::new() }
  [bool]       Test() { return $true }
  [void]       Set()  { }
}

That's not intuitive to define and leads to this error message when an invalid value is specified:

$a = [MyResource]::new()
$a.Kind = 'Undefined'
SetValueInvocationException:
  Exception setting "Kind":
    "The argument "Undefined" does not belong to the set "Foo,Bar,Baz" specified by the
    ValidateSet attribute. Supply an argument that is in the set and then try the command
    again."

Compared to the message for a normal enum:

enum MyKindB {
  Foo
  Bar
  Baz
}

[DscResource()]
class MyResourceB {
  [DscProperty()] [MyKindB] $Kind

  [DscProperty(Key)] [string] $Path

  [MyResourceB] Get()  { return [MyResourceB]::new() }
  [bool]       Test() { return $true }
  [void]       Set()  { }
}
$b = [MyResourceB]::new()
$b.Kind = 'Undefined'
SetValueInvocationException:
  Exception setting "Kind": "Cannot convert value "Undefined" to type "MyKindB".
    Error: "Unable to match the identifier name Undefined to a valid enumerator name.
      Specify one of the following enumerator names and try again:
        Foo, Bar, Baz""

Summary

Option 1 forces the resource to model the component in a way that might not match reality and may involve long lists of mandatory properties. Option 2 only sometimes works. It always requires the author to keep their implementation up-to-date with the default values for the component, possibly supporting defaults on a per-version basis, and likely requires additional custom handling and validation.

If a resource could tell whether value-type properties were explicitly set, no workarounds would be needed.

Proposed technical implementation details (optional)

The only implementation I can think of that could help with this without requiring substantial work in PowerShell to support accessors/mutators for class properties (see: PowerShell/PowerShell#2219) is for the PSDesiredStateConfiguration module to define an interface for DSC Resources (#81) with a default implementation (#82) that includes this functionality.

Add a new parameter set to Invoke-DscResource that takes a DscResourceInfo

Summary of the new feature / enhancement

The current implementation of Invoke-DscResource always calls Get-DscResource. If the caller already has the result of Get-DscResource, it should be able to pass the DscResourceInfo object to Invoke-DscResource and avoid the internal call to Get-DscResource, as well as being able to pipe Get-DscResource to Invoke-DscResource and improve performance.

Proposed technical implementation details (optional)

No response

Invoke-DscResource doesn't display any stream output from the dsc resource

Steps to reproduce

Invoke a dsc resource that contains any stream ouput (ex. Verbose). Below is a simple example only to demonstrate verbose output.

StreamTest.psm1

[DscResource()]
class MyTestResource
{
    [DscProperty(Key)]
    [string] $SomeVal

	[void] Set() {
                Write-Verbose "Entered Set method"
	}
	
	[MyTestResource] Get() {
		Write-Verbose "Entered Get method"
	
		return $this
	}
	
	[bool] Test() {
		Write-Verbose "Entered Test method"
		
                return $true
	}
}

StreamTest.psd1

@{

    # Script module or binary module file associated with this manifest.
    RootModule = 'StreamTest.psm1'
	
    DscResourcesToExport = @(
    'MyTestResource'
    )
    
    # Version number of this module.
    ModuleVersion = '1.0.0.0'
    
    # ID used to uniquely identify this module
    GUID = '6c583f5e-3712-432d-a65c-29f665a7a07a'
    
    # Minimum version of the Windows PowerShell engine required by this module
    PowerShellVersion = '5.0'
}

Invoking the dsc resource

$splat = @{
    Name = 'MyTestResource'
    ModuleName = 'StreamTest'
    Method = 'Test'
    Property = @{
        SomeVal = 'Test'
    }
    Verbose = $true
}

Invoke-DscResource @splat

Expected behavior

Should display verbose output from the dsc resource.

Actual behavior

Does not display verbose output from the dsc resource.

image

Environment data

Name Value
PSVersion 7.1.0
PSEdition Core
GitCommitId 7.1.0
OS Microsoft Windows 10.0.18363
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0

DSC should ship Reasons class

Prerequisites

  • Write a descriptive title.
  • Make sure you are able to repro it on the latest released version
  • Search the existing issues.

Steps to reproduce

PSDSC should ship a Reasons class so each DSC resource module doesn't need to define it. It would also address the issue with Reasons type name conflict issues. Backstory: anypackage/dsc#12

Expected behavior

# DSC should ship `Reasons` type.

Actual behavior

# No Reasons type

Error details

No response

Environment data

7.2-preview 2

Version

2.0.6

Visuals

No response

Performance issues with Invoke-DscResource for multiple DSC resources

When used to invoke multiple DSC Resource the Invoke-DscResource cmdlet works really slow. This is caused by a lot of repeating operations (especially with Test and Set methods).

The performance can potentially be increased with any of the following:

  • Having a $Method input that accepts a parameter for executing both Test and Set methods (similar to DSC standard). This way the internal Dsc object can be reused and does need to be found or created twice.
  • Creating the Dsc object not in a separate runspace but instead creating it in a a scriptblock and then dot sourcing it.
$block = @"
using module '$ModuleName'

[$($invokeSplatParams['Name'])]::new()
"@

$dscObj = . ([ScriptBlock]::create($block))

foreach ($key in $invokeSplatParams.Property.Keys) {
   $dscObj.$key = $invokeSplatParams.Property[$key]
}
  • Having an optional flag for skipping DSC Resource validation and letting the user validate prior to it.

Steps to reproduce

Invoke a big quantity of DSC Resources with Invoke-DscResource. The examples are made using DSC Resources from VMware.vSphereDSC.

Example used for measuring Invoke-DscResource performance

$dataCenterFolderInvokeSplat = @{
    Name = 'DatacenterFolder'
    ModuleName = 'VMware.vSphereDSC'
    Property = @{
        Server = '<Server here>'
        Credential = '<Credentials here>'
        Name = "MyDatacentersFolder"
        Location = ''
        Ensure = 'Present'
    }
}

Import-Module 'PSDesiredStateConfiguration'

Measure-Command {
    $state = Invoke-DscResource @dataCenterFolderInvokeSplat -Method Test

    if (-not $state.InDesiredState) {
        Invoke-DscResource @dataCenterFolderInvokeSplat -Method Set
    }
}

Example used for measuring LCM performance

Configuration Test {
    Import-DscResource -ModuleName VMware.vSphereDSC

    Node $AllNodes.NodeName {
        foreach ($vCenter in $AllNodes.VCenters) {
            $Server = $vCenter.Server
            $User = $vCenter.User
            $Password = $vCenter.Password | ConvertTo-SecureString -asPlainText -Force
            $Credential = New-Object System.Management.Automation.PSCredential($User, $Password)

            DatacenterFolder "MyDatacentersFolder_$($Server)" {
                Server = $Server
                Credential = $Credential
                Name = "MyDatacentersFolder"
                Location = ''
                Ensure = 'Present'
            }
        }
    }
}

$configurationData = @{
    AllNodes = @(
        @{
            NodeName = 'localhost'
            PSDscAllowPlainTextPassword = $true
            VCenters = @(
                @{
                    Server = '<Server here>'
                    User = '<User here>'
                    Password = '<Password here>'
                }
            )
        }
    )
}

Test -ConfigurationData $configurationData

Measure-Command {
    Start-Configuration -Path '.\Test\' -Wait -Force
}

Actual behavior

The following table shows measurements made by using 1 and 10 DSC Resources with Invoke-DscResource and Configurations with that many Resources for use with Start-DscConfiguration.

The measured time is the average result from 3 runs each and the measuring unit is in seconds. The measurement is calculated from the Measure-Command cmdlet result.

Resources Count/Execution type LCM Invoke-DscResource
1 4s 8s
10 32s 61s

Environment data

Name Value
PSVersion 7.0.3
PSEdition Core
GitCommitId 7.0.3
OS Microsoft Windows 10.0.18363
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0

InvokeDscResourceTestResult should have a implict bool operator

Summary of the new feature / enhancement

I would like InvokeDscResourceTestResult to have an implicit cast operator to bool so that I can use the result in if statements and other places bool is useful.

Proposed technical implementation details (optional)

public static implicit operator bool(InvokeDscResourceTestResult result) => result.InDesiredState;

Get-DSCResource to show when there are syntax errors.

Current behavior -
Get-DSCResource shows a generic message " The term {0} is not found as a resource" when there is a syntax error in the DSC resource (.psm1).

Feature request -
In case of syntax errors, Get-DSCResource should show the actual syntax error message.

Given Get-DscResource can be called without any arguments, this might clutter the console output if there are way many modules with syntax errors in $env:PSModulePath. It's good idea to surface the underlying syntax error message only when user calls Get-DscResource -Module

Get-DscResource is sensitive to the case of the DscResources folder on Linux

On PowerShell Core on linux:

Get-DscResource -Name PsModule

Expected

ResourceType  : MSFT_PSModule                                                                                                                                                                                            
Name          : PSModule                                                                                                                                                                                                  
FriendlyName  : PSModule                                                                                                                                                                                                  
Module        : PowerShellGet                                                                                                                                                                                             
ModuleName    : PowerShellGet                                                                                                                                                                                             
Version       : 2.2                                                                                                                                                                                                       
Path          : /usr/local/microsoft/powershell/7-preview/Modules/PowerShellGet/DscResources/MSFT_PSModule/MSFT_PSModule.psm1                                                                                             
ParentPath    : /usr/local/microsoft/powershell/7-preview/Modules/PowerShellGet/DscResources/MSFT_PSModule                                                                                                                
ImplementedAs : PowerShell                                                                                                                                                                                                
CompanyName   : Microsoft Corporation                                                                                                                                                                                     
Properties    : {Name, AllowClobber, DependsOn, Ensure…}

Actual

CheckResourceFound : The term 'psmodule' is not recognized as the name of a Resource.                                                                     
At C:\program files\powershell\7-preview\Modules\PSDesiredStateConfiguration\PSDesiredStateConfiguration.psm1:3991 char:13                                
+             CheckResourceFound $Name $Resources                                                                                                         
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                                                                                                         
+ CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException                                                                            
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,CheckResourceFound    

Workaround

Get-DscResource should throw an error when -Name is specified but the resource doesn't exist

Repro

Get-DscResource -name foobar

Expected

CheckResourceFound : The term 'foobar' is not recognized as the name of a Resource.                                                                              
At /Users/travisplunk/git/PSDesiredStateConfiguration/src/PSDesiredStateConfiguration/PSDesiredStateConfiguration.psm1:4019 char:13                              
+             CheckResourceFound $Name $Resources                                                                                                                
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                                                                                                                
+ CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException                                                                                   
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,CheckResourceFound

Actual

Get-DscResource returns classes without [DscResource()] attribute

Prerequisites

  • Write a descriptive title.
  • Make sure you are able to repro it on the latest released version
  • Search the existing issues.

Steps to reproduce

If you have a module containing classes that do not have [DscResource()] attribute Get-DscResource will return those classes as if they were a resource.

PSDsc should check classes to see if they have that attribute and not return them.

Expected behavior

# classes without `[DscResource()]` are not returned as resources

Actual behavior

ImplementationDetail :
ResourceType         : Reason
Name                 : Reason
FriendlyName         :
Module               :
ModuleName           :
Version              :
Path                 :
ParentPath           :
ImplementedAs        : Binary
CompanyName          :
Properties           :

Error details

No response

Environment data

7.4-preview2

Version

2.0.6

Visuals

No response

Fix duplicated resources error

Prerequisites

  • Write a descriptive title.
  • Make sure you are able to repro it on the latest released version
  • Search the existing issues.

Steps to reproduce

When a resource with the same name found in several places in PSModulePath, DSC v2 returns an error suggesting user to manually remove one of the locations.
DSC should be able to automatically resolve such situation and for example use the first occurrence of the resource.

Expected behavior

N/A

Actual behavior

N/A

Error details

No response

Environment data

N/A

Version

v2

Visuals

No response

Cmdlet help not found

Prerequisites

  • Write a descriptive title.
  • Make sure you are able to repro it on the latest released version
  • Search the existing issues.

Steps to reproduce

Install PSDesiredStateConfiguration module and update help. Then try to access any of cmdlet help and it will say no help found.

Expected behavior

# Help found

Actual behavior

# Help not found

Error details

No response

Environment data

7.4-preview2

Version

2.0.6

Visuals

No response

C# Resources

Summary of the new feature / enhancement

As a user I want PSDSC to support C# resource.

Proposed technical implementation details (optional)

Implement an interface that C# and/or PowerShell can implement IDscResource with the Get(), Set(), Test() methods. By having a single implementation the same logic can be used for PowerShell and C# resources.

Enable `export` for class-based resources

Summary of the new feature / enhancement

Enable class-based resources to participate in DSCv3 export capability

Proposed technical implementation details (optional)

No response

Invoke-DscResource cmdlet throws an exception when using class-based DSC Resource, when module path contains a space

When using a custom class-based DSC resource, the **Invoke-DscResource **cmdlet fails.
The issue seems to be in the function Invoke-DscClassBasedResource in the PSDesiredStateConfiguration.psm1 of the PSDesiredStateConfiguration module:

$script = @"
using module $path

Write-Host -Message ([$type]::new | out-string)

return [$type]::new()
"@

When $path is a string with white spaces for example: C:\My Modules\MyModule.psd1 the path gets cut off at the first space and results in C:\My. This leads to an error when trying to use the module, due to the fact that the path is invalid.

Steps to reproduce

  1. Create a Dsc Resource located in : C:\My Modules\MyDscResource.psm1 or the standard Module path: C:\Program Files\WindowsPowerShell\Modules
enum Ensure
{
    Absent
    Present
}
[DscResource()]
class FileResource
{
    [DscProperty(Key)]
    [string]$Path

    [DscProperty(Mandatory)]
    [Ensure] $Ensure

    [DscProperty(Mandatory)]
    [string] $SourcePath

    [DscProperty(NotConfigurable)]
    [Nullable[datetime]] $CreationTime

    [void] Set() {
        $fileExists = $this.TestFilePath($this.Path)
        if ($this.ensure -eq [Ensure]::Present) {
            if (-not $fileExists) {
                $this.CopyFile()
            }
        }
        else {
            if ($fileExists) {
                Write-Verbose -Message "Deleting the file $($this.Path)"
                Remove-Item -LiteralPath $this.Path -Force
            }
        }
    }
    [bool] Test() {
        $present = $this.TestFilePath($this.Path)

        if ($this.Ensure -eq [Ensure]::Present) {
            return $present
        } else {
            return -not $present
        }
    }
    [FileResource] Get() {
        $present = $this.TestFilePath($this.Path)

        if ($present) {
            $file = Get-ChildItem -LiteralPath $this.Path
            $this.CreationTime = $file.CreationTime
            $this.Ensure = [Ensure]::Present
        }
        else {
            $this.CreationTime = $null
            $this.Ensure = [Ensure]::Absent
        }

        return $this
    }
    [bool] TestFilePath([string] $location) {
        $present = $true

        $item = Get-ChildItem -LiteralPath $location -ea Ignore
        if ($item -eq $null) {
            $present = $false
        }  elseif ($item.PSProvider.Name -ne "FileSystem") {
            throw "Path $($location) is not a file path."
        }
        elseif ($item.PSIsContainer) {
            throw "Path $($location) is a directory path."
        }
        return $present
    }
    [void] CopyFile() {
        if (-not $this.TestFilePath($this.SourcePath)) {
            throw "SourcePath $($this.SourcePath) is not found."
        }
        [System.IO.FileInfo] $destFileInfo = new-object System.IO.FileInfo($this.Path)
        if (-not $destFileInfo.Directory.Exists) {
            Write-Verbose -Message "Creating directory $($destFileInfo.Directory.FullName)"
            [System.IO.Directory]::CreateDirectory($destFileInfo.Directory.FullName)
        }

        if (Test-Path -LiteralPath $this.Path -PathType Container)  {
            throw "Path $($this.Path) is a directory path"
        }
        Write-Verbose -Message "Copying $($this.SourcePath) to $($this.Path)"
        Copy-Item -LiteralPath $this.SourcePath -Destination $this.Path -Force
    }
} # This module defines a class for a DSC "FileResource" provider.
  1. Invoke the DSC Resource with the Invoke-DscResource cmdlet
$invokeParams = @{
    Name = 'FileResource'
    Modulename = 'MyDscResource'
    Method = 'Test'
    Property = @{
        Path = "C:\Test\sample data.txt"
        SourcePath = "C:\Test\sample data.txt"
        Ensure = "Present"
    }
    Verbose = $true
}

Invoke-DscResource @invokeParams

Expected behavior

Should Invoke the resource correctly and return a valid result.

Actual behavior

Throws various exceptions due to not parsing the module path correctly.

image

Environment data

$psversiontable info
PSVersion | 7.0.3
PSEdition | Core
GitCommitId | 7.0.3
OS | Microsoft Windows 10.0.18363
Platform | Win32NT
PSCompatibleVersions| {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion | 2.3
SerializationVersion |1.1.0.1
WSManStackVersion |3.0

Scrub subsystem code of using internal SMA types.

Current subsystem design guidelines allow using SMA internal types by subsystem together with InternalsVisibleTo attribute.
This brings to problems when compiling subsystems using PackageReference to System.Management.Automation (or PS SDK) package because internal SMA types that are not available in ref versions of the package.

External contribution workflow

\o I've got some free time coming up in the winter to spend more attention on helping with this from a vendor-integrating-with-dsc perspective (for example, filing bugs and patches and feature requests) but I think I'm lacking a bit of context for the local testing/development workflow.

Once I can work from latest locally, I can file more useful bugs and feature requests.

Get-DscResource' command was found in the module 'PSDesiredStateConfiguration', but the module could not be loaded.

Prerequisites

  • Write a descriptive title.
  • Make sure you are able to repro it on the latest released version
  • Search the existing issues.

Steps to reproduce

Using a windows sandbox environment (so a fresh DSC install) I ran the following using an administrative PowerShell window.

Install-Module -Name Microsoft365DSC
Import-Module Microsoft365DSC
Update-M365DSCDependencies
Export-M365DSCConfiguration

I use the credential option and use a admin account that doesn't have MFA enabled. I get a few graph permission errors but I'm not too worried about that at this point.

once I get to the exodkimsigning config I get this message and the export stops:
image

I attempt to import the module ad directed and I get the following error:
image

Expected behavior

complete configuraiton export

Actual behavior

partial configuration export

Error details

Import-Module : Could not load file or assembly 'file:///C:\Windows\system32\WindowsPowerShell\v1.0\Modules\PSDesiredSt
ateConfiguration\Microsoft.Windows.DSC.CoreConfProviders' or one of its dependencies. The system cannot find the file
specified.
At line:1 char:1
+ Import-Module PSDesiredStateConfiguration -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Import-Module], FileNotFoundException
    + FullyQualifiedErrorId : FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand

Environment data

5.1.22621.963

Version

N/A

Visuals

No response

CmdletsToExports causes Get-DscResource to not return resources

Prerequisites

  • Write a descriptive title.
  • Make sure you are able to repro it on the latest released version
  • Search the existing issues.

Steps to reproduce

I am using the NewFile example on the docs to test this. If the module manifest has CmdletsToExport key defined then Get-DscResource will not return any resources for that module.

Expected behavior

# Resources returned

Actual behavior

# No resources are returned

Error details

No response

Environment data

Name                           Value
----                           -----
PSVersion                      7.3.3
PSEdition                      Core
GitCommitId                    7.3.3
OS                             Microsoft Windows 10.0.19044
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Version

3.0.0-beta1

Visuals

No response

Esoteric Error when a class-based DSC Resource has a property named `Scope`

Prerequisites

  • Write a descriptive title.
  • Make sure you are able to repro it on the latest released version
  • Search the existing issues.

Steps to reproduce

When I define a DSC Resource as a PowerShell class, I should be able to use arbitrary names for the properties, so long as they're not one of PowerShell's automatic variables.

  1. Create a new folder, dsc-repro:

    New-Item ./dsc-repro -ItemType Directory
    Push-Location ./dsc-repro
  2. Define a new PowerShell module manifest, dsc-repro.psd1, with the following manifest:

    New-ModuleManifest -RootModule dsc-repro.psm1 -DscResourcesToExport ReproInvalid, ReproValid
  3. Define the root module with the following code:

    [DscResource()] class ReproInvalid {
        [DscProperty(key)] [string] $Scope
        [ReproInvalid] Get() {
            $actual =  [ReproInvalid]::new()
            $actual.Scope = $this.Scope
            return $actual
        }
        [bool] Test() { return $true }
        [void] Set() { }
    }
    
    [DscResource()] class ReproValid {
        [DscProperty(key)] [string] $ConfigurationScope
        [ReproValid] Get() {
            $actual =  [ReproValid]::new()
            $actual.Scope = $this.ConfigurationScopeScope
            return $actual
        }
        [bool] Test() { return $true }
        [void] Set()  { }
    }
  4. Call Get-DscResource for the module's DSC Resources:

    # Add the local folder to the PSModulePath
    $env:PSModulePath += [System.IO.Path]::PathSeparator + $pwd.Path
    Get-DscResource -Module dsc-repro
    MethodInvocationException:
      Exception calling "ImportClassResourcesFromModule" with "3" argument(s):
        "Syntax error:   At line:4, char:21  Buffer:  {     [key]string Scope^; }; "
    
  5. Comment out the definition for ReproInvalid:

    # [DscResource()] class ReproInvalid {
    #     [DscProperty(key)] [string] $Scope
    #     [ReproInvalid] Get() {
    #         $actual =  [ReproInvalid]::new()
    #         $actual.Scope = $this.Scope
    #         return $actual
    #     }
    #     [bool] Test() { return $true }
    #     [void] Set() { }
    # }
    
    [DscResource()] class ReproValid {
        [DscProperty(key)] [string] $ConfigurationScope
        [ReproValid] Get() {
            $actual =  [ReproValid]::new()
            $actual.Scope = $this.ConfigurationScopeScope
            return $actual
        }
        [bool] Test() { return $true }
        [void] Set()  { }
    }
  6. Call Get-DscResource for the module's DSC Resources:

    Get-DscResource -Module dsc-repro
    ImplementationDetail : ClassBased
    ResourceType         : ReproValid
    Name                 : ReproValid
    FriendlyName         :
    Module               : dsc-repro
    ModuleName           : dsc-repro
    Version              : 0.0.1
    Path                 : C:\code\dsc-repro\dsc-repro.psd1
    ParentPath           : C:\code\dsc-repro
    ImplementedAs        : PowerShell
    CompanyName          : Unknown
    Properties           : {ConfigurationScope, DependsOn, PsDscRunAsCredential}
    

Expected behavior

PS> Get-DscResource -Module dsc-repro

ImplementationDetail : ClassBased
ResourceType         : ReproInvalid
Name                 : ReproInvalid
FriendlyName         :
Module               : dsc-repro
ModuleName           : dsc-repro
Version              : 0.0.1
Path                 : C:\code\dsc-repro\dsc-repro.psd1
ParentPath           : C:\code\dsc-repro
ImplementedAs        : PowerShell
CompanyName          : Unknown
Properties           : {Scope, DependsOn, PsDscRunAsCredential}

ImplementationDetail : ClassBased
ResourceType         : ReproValid
Name                 : ReproValid
FriendlyName         :
Module               : dsc-repro
ModuleName           : dsc-repro
Version              : 0.0.1
Path                 : C:\code\dsc-repro\dsc-repro.psd1
ParentPath           : C:\code\dsc-repro
ImplementedAs        : PowerShell
CompanyName          : Unknown
Properties           : {ConfigurationScope, DependsOn, PsDscRunAsCredential}

Actual behavior

PS> Get-DscResource -Module dsc-repro

MethodInvocationException:
  Exception calling "ImportClassResourcesFromModule" with "3" argument(s):
    "Syntax error:   At line:4, char:21  Buffer:  {     [key]string Scope^; }; "

Error details

Exception             : 
    Type           : System.Management.Automation.MethodInvocationException
    ErrorRecord    : 
        Exception             : 
            Type    : System.Management.Automation.ParentContainsErrorRecordException
            Message : Exception calling "ImportClassResourcesFromModule" with "3" argument(s): "Syntax error:
                      At line:4, char:21
                      Buffer:
                      {
    [key]string Scope^;
};
                      "
            HResult : -2146233087
        CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
        FullyQualifiedErrorId : CimException
        InvocationInfo        : 
            ScriptLineNumber : 2496
            OffsetInLine     : 5
            HistoryId        : -1
            ScriptName       : C:\Users\mikey\Documents\PowerShell\Modules\PSDesiredStateConfiguration\2.0.7\PSDesiredStateConfiguration.psm1
            Line             : $resourcesFound = [Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::ImportClassResourcesFromModule($Module, $Resources, $functionsToDefine)  

            PositionMessage  : At C:\Users\mikey\Documents\PowerShell\Modules\PSDesiredStateConfiguration\2.0.7\PSDesiredStateConfiguration.psm1:2496 char:5
                               +     $resourcesFound = [Microsoft.PowerShell.DesiredStateConfiguration …
                               +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            PSScriptRoot     : C:\Users\mikey\Documents\PowerShell\Modules\PSDesiredStateConfiguration\2.0.7
            PSCommandPath    : C:\Users\mikey\Documents\PowerShell\Modules\PSDesiredStateConfiguration\2.0.7\PSDesiredStateConfiguration.psm1
            CommandOrigin    : Internal
        ScriptStackTrace      : at ImportClassResourcesFromModule, C:\Users\mikey\OneDrive -
Microsoft\Documents\PowerShell\Modules\PSDesiredStateConfiguration\2.0.7\PSDesiredStateConfiguration.psm1: line 2496
                                at Get-DscResource<Begin>, C:\Users\mikey\OneDrive - 
Microsoft\Documents\PowerShell\Modules\PSDesiredStateConfiguration\2.0.7\PSDesiredStateConfiguration.psm1: line 3967
                                at <ScriptBlock>, <No file>: line 1
    TargetSite     : 
        Name          : ConvertToMethodInvocationException
        DeclaringType : System.Management.Automation.ExceptionHandlingOps, System.Management.Automation, Version=7.3.6.500, Culture=neutral, PublicKeyToken=31bf3856ad364e35
        MemberType    : Method
        Module        : System.Management.Automation.dll
    Message        : Exception calling "ImportClassResourcesFromModule" with "3" argument(s): "Syntax error:
                     At line:4, char:21
                     Buffer:
                     {
    [key]string Scope^;
};
                     "
    Data           : System.Collections.ListDictionaryInternal
    InnerException : 
        Type            : Microsoft.Management.Infrastructure.CimException
        NativeErrorCode : Failed
        ErrorData       : OMI_Error
        StatusCode      : 1
        TargetSite      : 
            Name          : DeserializeClassHandle
            DeclaringType : Microsoft.Management.Infrastructure.Serialization.CimMofDeserializer, Microsoft.Management.Infrastructure, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35
            MemberType    : Method
            Module        : Microsoft.Management.Infrastructure.dll
        Message         : Syntax error:
                          At line:4, char:21
                          Buffer:
                          {
    [key]string Scope^;
};

        Source          : Microsoft.Management.Infrastructure
        HResult         : -2146233088
        StackTrace      : 
   at Microsoft.Management.Infrastructure.Serialization.CimMofDeserializer.DeserializeClassHandle(Byte[] serializedData, UInt32& offset, IEnumerable`1 cimClasses, String computerName, String     
namespaceName, OnClassNeeded onClassNeededCallback, GetIncludedFileContent getIncludedFileCallback)
   at Microsoft.Management.Infrastructure.Serialization.CimMofDeserializer.DeserializeClasses(Byte[] serializedData, UInt32& offset, IEnumerable`1 classes, String computerName, String
namespaceName, OnClassNeeded onClassNeededCallback, GetIncludedFileContent getIncludedFileCallback)
   at Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser.ParseSchemaMofFileBuffer(String mof)
   at Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache.ProcessMofForDynamicKeywords(PSModuleInfo module, ICollection`1 resourcesFound, Dictionary`2 functionsToDefine,        
CimDSCParser parser, String mof, DSCResourceRunAsCredential runAsBehavior)
   at Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache.ImportKeywordsFromScriptFile(String fileName, PSModuleInfo module, ICollection`1 resourcesToImport, ICollection`1      
resourcesFound, Dictionary`2 functionsToDefine, List`1 errorList, IScriptExtent extent)
   at Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache.LoadPowerShellClassResourcesFromModule(PSModuleInfo primaryModuleInfo, PSModuleInfo moduleInfo, ICollection`1
resourcesToImport, ICollection`1 resourcesFound, List`1 errorList, Dictionary`2 functionsToDefine, Boolean recurse, IScriptExtent extent)
   at CallSite.Target(Closure, CallSite, Type, PSModuleInfo, List`1, Dictionary`2)
    Source         : System.Management.Automation
    HResult        : -2146233087
    StackTrace     : 
   at System.Management.Automation.ExceptionHandlingOps.ConvertToMethodInvocationException(Exception exception, Type typeToThrow, String methodName, Int32 numArgs, MemberInfo memberInfo)
   at CallSite.Target(Closure, CallSite, Type, PSModuleInfo, List`1, Dictionary`2)
   at System.Management.Automation.Interpreter.DynamicInstruction`5.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : CimException
InvocationInfo        : 
    ScriptLineNumber : 2496
    OffsetInLine     : 5
    HistoryId        : -1
    ScriptName       : C:\Users\mikey\Documents\PowerShell\Modules\PSDesiredStateConfiguration\2.0.7\PSDesiredStateConfiguration.psm1
    Line             : $resourcesFound = [Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::ImportClassResourcesFromModule($Module, $Resources, $functionsToDefine)

    PositionMessage  : At C:\Users\mikey\Documents\PowerShell\Modules\PSDesiredStateConfiguration\2.0.7\PSDesiredStateConfiguration.psm1:2496 char:5
                       +     $resourcesFound = [Microsoft.PowerShell.DesiredStateConfiguration …
                       +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    PSScriptRoot     : C:\Users\mikey\Documents\PowerShell\Modules\PSDesiredStateConfiguration\2.0.7
    PSCommandPath    : C:\Users\mikey\Documents\PowerShell\Modules\PSDesiredStateConfiguration\2.0.7\PSDesiredStateConfiguration.psm1
    CommandOrigin    : Internal
ScriptStackTrace      : at ImportClassResourcesFromModule, C:\Users\mikey\OneDrive -
Microsoft\Documents\PowerShell\Modules\PSDesiredStateConfiguration\2.0.7\PSDesiredStateConfiguration.psm1: line 2496
                        at Get-DscResource<Begin>, C:\Users\mikey\Documents\PowerShell\Modules\PSDesiredStateConfiguration\2.0.7\PSDesiredStateConfiguration.psm1: line   
3967
                        at <ScriptBlock>, <No file>: line 1

Environment data

Name                           Value
----                           -----
PSVersion                      7.3.6
PSEdition                      Core
GitCommitId                    7.3.6
OS                             Microsoft Windows 10.0.22621
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Version

2.0.7

Visuals

No response

Invoke-DscResource parameters type conversion

Steps to reproduce

When calling Invoke-DscResource and passing string arguments that are supposed to be converted to integers (Enumerator) values the command doesn't do it. Only when using a DSC powershell configuration script.

The error is discussed in another issue in Ansible, because, at first, one thought the problem was inside win_dsc Ansible module. Apparently is not.
ansible/ansible#25754 (comment)

Full thread with all the steps (including DSC Script and PowerShell commands)
ansible/ansible#25754

But to shorten it a bit:
This DSC Script works fine using the cAdministrativeTemplateSetting from the PolicyFileEditor module (https://github.com/dlwyatt/PolicyFileEditor).

  1. Install the PolicyFileEditor in PowerShell of the target machine:
PS C:\Users\user>Find-DSCResource -ModuleName PolicyFileEditor
PS C:\Users\user> Install-Module PolicyFileEditor
  1. Run a simple DSC Script on the target Windows machine to prove that the resource works fine:
Configuration LocalGPO
{
    param
    (
        [string[]] $NodeName = 'localhost'
    )

    Import-DSCResource -ModuleName PolicyFileEditor

    Node $NodeName
    {
        cAdministrativeTemplateSetting "RDP Users Home Directory Path"
        {
        #    SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services!WFHomeDirUNC 
        #    SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services!WFHomeDir
        #    SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services!WFHomeDirDrive
            KeyValueName = "SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services\WFHomeDir"
            PolicyType = "Machine"
            Data = "\\servershare\test"
            Ensure = "Present"
            Type = "String"
        }

        cAdministrativeTemplateSetting "RDP Users Home Directory Letter"
        {
            KeyValueName = "SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services\WFHomeDirDrive"
            PolicyType = "Machine"
            Data = "X:"
            Ensure = "Present"
            Type = "String"
        }

        cAdministrativeTemplateSetting "RDP Users Home Directory UNC boolean"
        {
            KeyValueName = "SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services\WFHomeDirUNC"
            PolicyType = "Machine"
            Data = "1"
            Ensure = "Present"
            Type = "Dword"
        }

    }
}

LocalGPO
Start-DscConfiguration -Path .\LocalGPO -Wait -Force -Verbose
  1. On the target machine, run the command gpupdate to update the Group Policy. Then Check the registry keys in HKLM:SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services\. There should be a DWORD key with the name WFHomeDirUNC and value 1.

What DOES NOT work:

  1. check the cAdministrativeTemplateSetting resource (from ansible/ansible#25754 (comment)):
PS C:\Users\trond\Documents> Get-DscResource cAdministrativeTemplateSetting | select -ExpandProperty Properties

Name                 PropertyType   IsMandatory Values
----                 ------------   ----------- ------
KeyValueName         [string]              True {}
PolicyType           [string]              True {Administrators, Machine, NonAdministrators, User}
Data                 [string[]]           False {}
DependsOn            [string[]]           False {}
Ensure               [string]             False {Absent, Present}
PsDscRunAsCredential [PSCredential]       False {}
Type                 [Int32]              False {Binary, DWord, ExpandString, MultiString...}
  1. Test using Invoke-DscResource (essential for ANSIBLE win_dsc module to call DSC resources). From ansible/ansible#25754 (comment).
$DscParams = @{}
$DscParams.Add("Ensure", "Present")
$DscParams.Add("KeyValueName", "SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services\WFHomeDirUNC")
$DscParams.Add("PolicyType", "Machine")
$DscParams.Add("Data", 1)
$DscParams.Add("Type", "Dword")
Invoke-DscResource -Name cAdministrativeTemplateSetting -ModuleName "PolicyFileEditor" -Method Get -Property $dscparams
Invoke-DscResource -Name cAdministrativeTemplateSetting -ModuleName "PolicyFileEditor" -Method Set -Property $dscparams

The errors:

Invoke-DscResource -Name cAdministrativeTemplateSetting -ModuleName "PolicyFileEditor" -Method Get -Property $dscparams
Convert property 'Type' value from type 'STRING' to type 'SINT32' failed
 At line:12, char:2
 Buffer:
irectResourceAccess";
};^
insta
    + CategoryInfo          : SyntaxError: (root/Microsoft/...gurationManager:String) [], CimException
    + FullyQualifiedErrorId : MiClientApiError_Failed
    + PSComputerName        : localhost
 

PS C:\Windows\system32> Invoke-DscResource -Name cAdministrativeTemplateSetting -ModuleName "PolicyFileEditor" -Method Set -Property $dscparams
Convert property 'Type' value from type 'STRING' to type 'SINT32' failed
 At line:12, char:2
 Buffer:
irectResourceAccess";
};^
insta
    + CategoryInfo          : SyntaxError: (root/Microsoft/...gurationManager:String) [], CimException
    + FullyQualifiedErrorId : MiClientApiError_Failed
    + PSComputerName        : localhost

Expected behavior

The Invoke-DscResource should work like calling a DSC resource with parameters in a DSC configuration script. Using string arguments that inside the resource are actually integers.

Actual behavior

It's not able to convert a string (which is supposedly accepted by the resource in the examples: cAdministrativeTemplateSetting from PolicyFileEditor module) to an integer. The resource contains a map to do this "conversion"/substitution of the keys (string values) for integers (enumerators).

Environment data

> $PSVersionTable
Name                           Value
----                           -----
PSVersion                      5.1.14409.1005
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14409.1005
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Get-DscResource silently fails when using another module types

Prerequisites

  • Write a descriptive title.
  • Make sure you are able to repro it on the latest released version
  • Search the existing issues.

Steps to reproduce

If a module containing DSC Resources requires types from another module Get-DscResource will not return those resources unless the required module has been imported first.

Install-Module AnyPackageDsc
Get-DscResource -Module AnyPackageDsc

Expected behavior

ImplementationDetail : ClassBased
ResourceType         : Package
Name                 : Package
FriendlyName         :
Module               : AnyPackageDsc
ModuleName           : AnyPackageDsc
Version              : 0.1.0
Path                 : C:\Users\Thomas\Documents\PowerShell\Modules\AnyPackageDsc\0.1.0\AnyPackageDsc.psd1
ParentPath           : C:\Users\Thomas\Documents\PowerShell\Modules\AnyPackageDsc\0.1.0
ImplementedAs        : PowerShell
CompanyName          :
Properties           : {Name, Provider, Version, AdditionalParameters…}

ImplementationDetail : ClassBased
ResourceType         : Source
Name                 : Source
FriendlyName         :
Module               : AnyPackageDsc
ModuleName           : AnyPackageDsc
Version              : 0.1.0
Path                 : C:\Users\Thomas\Documents\PowerShell\Modules\AnyPackageDsc\0.1.0\AnyPackageDsc.psd1
ParentPath           : C:\Users\Thomas\Documents\PowerShell\Modules\AnyPackageDsc\0.1.0
ImplementedAs        : PowerShell
CompanyName          :
Properties           : {Location, Name, Provider, AdditionalParameters…}

Actual behavior

# no resources are returned

Error details

No response

Environment data

7.4-preview2

Version

2.0.6

Visuals

No response

Import-DSCResource selects "Never run" for class based resources signed by unknown publishers

If the Execution Policy is set to AllSigned and you try to import a class based resource signed by an unknown publisher, Import-DSCResource will opt to "Never run" software from this publisher.
Since the default option for the authenticode prompt is "Do not run", this behaviour is unexpected.

"Never run" causes problems in that it will import the certificate in question in to the Disallowed store of the SYSTEM account. This can lead to a lot of manual cleanup work in case a default signing certificate has been missing from the Trusted Publisher store for unrelated reasons.
Is this really the intended behaviour? Shouldn't DSC select the default option?

Steps to reproduce

  1. Set Execution Policy to AllSigned
  2. Apply a DSC configuration that imports a class based DSC resource signed by an unknown publisher

Expected behavior

Resource is not imported, using the default option "Do not run".

Actual behavior

Resource is not imported, using the option "Never run".

Environment data

Name Value


PSVersion 5.1.14393.206
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.14393.206
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1

Invoke-DSCResource requires to exit powershell session to read any changes to powershell resource

I'm using 7.2.0-preview.6.

Repro steps -

  1. Have a test powershell resource that's working fine.
  2. inside powershell session, run invoke-dscresource
  3. Now add a write-verbose / write-host / write-debug statement in the execution flow.
  4. in the same powershell session, run invoke-dscresource again.
  5. You wouldn't see the log added in step 3

To see the log added in step 3, you need to completely exit the powershell session and launch powershell session again.

Invoke-DscResource doesn't see the latest changes unless I completely exit the powershell session. This makes developer life very difficult to debug.

As far as I remember, this scenario worked before DSC code is pulled from powershell repository.

Import-DscResource breaks with multiple copies of the same module on the system

Steps to reproduce

# Install the same module to two different paths that are in $env:PSModulePath e.g.
> Get-Module -ListAvailable -FullyQualifiedName xActiveDirectory

    Directory: D:\Temp\a


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   2.17.0.0   xActiveDirectory


    Directory: D:\Temp\b


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   2.17.0.0   xActiveDirectory


# and try to use this module in a DSC config
Configuration DSCImportTest { Import-DscResource -ModuleName xActiveDirectory }

Expected behavior

All DSC resources are imported from xActiveDirectory. Because -ModuleVersion wasn't specified I'd expect the first encountered instance of the module to be imported regardless of the version.

Actual behavior

At line:1 char:31
+ ... ion DSCImportTest { Import-DscResource -ModuleName xActiveDirectory }
+                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Multiple versions of the module 'xActiveDirectory' were found. You can run 'Get-Module -ListAvailable -FullyQualifiedName xActiveDirectory' to see available versions on the system, and then use the fully qualified name '@{ModuleName="xActiveDirectory"; RequiredVersion="Version"}'.
+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MultipleModuleEntriesFoundDuringParse

Environment data

> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      6.0.1
PSEdition                      Core
GitCommitId                    v6.0.1
OS                             Microsoft Windows 10.0.17101
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Can't compile configuration with MOF-based resources when PSDSCv3 is also installed

Prerequisites

  • Write a descriptive title.
  • Make sure you are able to repro it on the latest released version
  • Search the existing issues.

Steps to reproduce

With ChocoInstalled.config.ps1 containing this:

Configuration ChocoInstalled {
    Import-DscResource -ModuleName Chocolatey

    node ChocoInstalled {
        ChocolateySoftware chocoSoftwareInstalled {
            Ensure = 'Present'
        }
    }
}

Here's what I tried:

PS C:\src\Chocolatey> get-module PSDesiredStateConfiguration
PS C:\src\Chocolatey> ipmo PSDesiredStateConfiguration -RequiredVersion 2.0.6
PS C:\src\Chocolatey> get-module PSDesiredStateConfiguration

ModuleType Version    PreRelease Name                                ExportedCommands
---------- -------    ---------- ----                                ----------------
Script     2.0.6                 PSDesiredStateConfiguration         {Configuration, Get-DscResource, Invoke-DscResource, New-Ds…

PS C:\src\Chocolatey> ChocoInstalled -OutputPath .\output\MOFs\
PSDesiredStateConfiguration\node: C:\src\Chocolatey\source\GCPackages\ChocoInstalled\ChocoInstalled.config.ps1:4:5
Line |
   4 |      node ChocoInstalled {
     |      ~~~~
     | The term 'Chocolatey\ChocolateySoftware' is not recognized as a name of a cmdlet, function, script file, or executable
     | program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.    
InvalidOperation: You cannot call a method on a null-valued expression.
PS C:\src\Chocolatey> get-module PSDesiredStateConfiguration

ModuleType Version    PreRelease Name                                ExportedCommands
---------- -------    ---------- ----                                ----------------
Script     3.0.0      beta1      PSDesiredStateConfiguration         {Configuration, ConvertTo-DscJsonSchema, Get-DscResource, I…
Script     2.0.6                 PSDesiredStateConfiguration         {Configuration, Get-DscResource, Invoke-DscResource, New-Ds

As you can see, the 3.0.0-beta1 version is automatically imported, and I suspect that's why compiling the configuration with a MOF-based resource doesn't work.

Compiling a Class based resource does work though.

Expected behavior

PS C:\src\Chocolatey> . .\source\GCPackages\ChocoInstalled\ChocoInstalled.config.ps1
PS C:\src\Chocolatey> ChocoInstalled -OutputPath .\output\MOFs\

    Directory: C:\src\Chocolatey\output\MOFs

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---          22/03/2023    14:17            606 ChocoInstalled.mof

Actual behavior

PS C:\src\Chocolatey> ChocoInstalled -OutputPath .\output\MOFs\
PSDesiredStateConfiguration\node: C:\src\Chocolatey\source\GCPackages\ChocoInstalled\ChocoInstalled.config.ps1:4:5
Line |
   4 |      node ChocoInstalled {
     |      ~~~~
     | The term 'Chocolatey\ChocolateySoftware' is not recognized as a name of a cmdlet, function, script file, or executable
     | program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.    
InvalidOperation: You cannot call a method on a null-valued expression.
PS C:\src\Chocolatey> get-module PSDesiredStateConfiguration

ModuleType Version    PreRelease Name                                ExportedCommands
---------- -------    ---------- ----                                ----------------
Script     3.0.0      beta1      PSDesiredStateConfiguration         {Configuration, ConvertTo-DscJsonSchema, Get-DscResource, I…
Script     2.0.6                 PSDesiredStateConfiguration         {Configuration, Get-DscResource, Invoke-DscResource, New-Ds…

Error details

PS C:\src\Chocolatey> get-error

Exception             : 
    Type        : System.Management.Automation.RuntimeException
    ErrorRecord : 
        Exception             : 
            Type    : System.Management.Automation.ParentContainsErrorRecordException
            Message : You cannot call a method on a null-valued expression.
            HResult : -2146233087
        CategoryInfo          : InvalidOperation: (:) [], ParentContainsErrorRecordException
        FullyQualifiedErrorId : InvokeMethodOnNull
        InvocationInfo        : 
            ScriptLineNumber : 2751
            OffsetInLine     : 20
            HistoryId        : -1
            ScriptName       : 
C:\Users\GaelColas\Documents\PowerShell\Modules\PSDesiredStateConfiguration\3.0.0\PSDesiredStateConfiguration.psm1
            Line             : if($nodeDoc.Contains("PsDscRunAsCredential"))

            PositionMessage  : At
C:\Users\GaelColas\Documents\PowerShell\Modules\PSDesiredStateConfiguration\3.0.0\PSDesiredStateConfiguration.psm1:2751 char:20   
                               +                 if($nodeDoc.Contains("PsDscRunAsCredential"))
                               +                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            PSScriptRoot     : C:\Users\GaelColas\Documents\PowerShell\Modules\PSDesiredStateConfiguration\3.0.0
            PSCommandPath    : 
C:\Users\GaelColas\Documents\PowerShell\Modules\PSDesiredStateConfiguration\3.0.0\PSDesiredStateConfiguration.psm1
            CommandOrigin    : Internal
        ScriptStackTrace      : at Write-NodeMOFFile,
C:\Users\GaelColas\Documents\PowerShell\Modules\PSDesiredStateConfiguration\3.0.0\PSDesiredStateConfiguration.psm1: line 2751     
                                at Configuration,
C:\Users\GaelColas\Documents\PowerShell\Modules\PSDesiredStateConfiguration\3.0.0\PSDesiredStateConfiguration.psm1: line 2205     
                                at <ScriptBlock>, C:\src\Chocolatey\source\GCPackages\ChocoInstalled\ChocoInstalled.config.ps1:   
line 1
                                at <ScriptBlock>, <No file>: line 1
    TargetSite  : 
        Name          : CheckActionPreference
        DeclaringType : System.Management.Automation.ExceptionHandlingOps, System.Management.Automation, Version=7.3.2.500,       
Culture=neutral, PublicKeyToken=31bf3856ad364e35
        MemberType    : Method
        Module        : System.Management.Automation.dll
    Message     : You cannot call a method on a null-valued expression.
    Data        : System.Collections.ListDictionaryInternal
    Source      : System.Management.Automation
    HResult     : -2146233087
    StackTrace  : 
   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)   
   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
CategoryInfo          : InvalidOperation: (:) [], RuntimeException
FullyQualifiedErrorId : InvokeMethodOnNull
InvocationInfo        : 
    ScriptLineNumber : 2751
    OffsetInLine     : 20
    HistoryId        : -1
    ScriptName       : 
C:\Users\GaelColas\Documents\PowerShell\Modules\PSDesiredStateConfiguration\3.0.0\PSDesiredStateConfiguration.psm1
    Line             : if($nodeDoc.Contains("PsDscRunAsCredential"))

    PositionMessage  : At
C:\Users\GaelColas\Documents\PowerShell\Modules\PSDesiredStateConfiguration\3.0.0\PSDesiredStateConfiguration.psm1:2751 char:20   
                       +                 if($nodeDoc.Contains("PsDscRunAsCredential"))
                       +                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    PSScriptRoot     : C:\Users\GaelColas\Documents\PowerShell\Modules\PSDesiredStateConfiguration\3.0.0
    PSCommandPath    : 
C:\Users\GaelColas\Documents\PowerShell\Modules\PSDesiredStateConfiguration\3.0.0\PSDesiredStateConfiguration.psm1
    CommandOrigin    : Internal
ScriptStackTrace      : at Write-NodeMOFFile,
C:\Users\GaelColas\Documents\PowerShell\Modules\PSDesiredStateConfiguration\3.0.0\PSDesiredStateConfiguration.psm1: line 2751     
                        at Configuration,
C:\Users\GaelColas\Documents\PowerShell\Modules\PSDesiredStateConfiguration\3.0.0\PSDesiredStateConfiguration.psm1: line 2205     
                        at <ScriptBlock>, C:\src\Chocolatey\source\GCPackages\ChocoInstalled\ChocoInstalled.config.ps1: line 1    
                        at <ScriptBlock>, <No file>: line 1

Environment data

Name                           Value
----                           -----
PSVersion                      7.3.2
PSEdition                      Core
GitCommitId                    7.3.2
OS                             Microsoft Windows 10.0.19043
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}       
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Version

notcrescendo

Visuals

N/A

Get-DscResource - Module name is case sensitive - on Linux/macOS

On PowerShell Core on:

get-dscresource -Name script -Module psdscresources

Expected

ResourceType  : MSFT_ScriptResource                                                                                                                                                                                       
Name          : Script                                                                                                                                                                                                    
FriendlyName  : Script                                                                                                                                                                                                   
 Module        : PSDscResources                                                                                                                                                                                           
 ModuleName    : PSDscResources                                                                                                                                                                                            
Version       : 2.12.0.0                                                                                                                                                                                                  
Path          : /root/.local/share/powershell/Modules/PSDscResources/2.12.0.0/DscResources/MSFT_ScriptResource/MSFT_ScriptResource.psm1                                                                                   
ParentPath    : /root/.local/share/powershell/Modules/PSDscResources/2.12.0.0/DscResources/MSFT_ScriptResource                                                                                                            
ImplementedAs : PowerShell                                                                                                                                                                                                
CompanyName   : Microsoft Corporation                                                                                                                                                                                     
Properties    : {GetScript, SetScript, TestScript, Credential…}

Actual

WARNING: There are no modules present in the system with the given module specification.

Workaround

get-dscresource -Name script -Module PSDscResources

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.