powershell / psdesiredstateconfiguration Goto Github PK
View Code? Open in Web Editor NEWSource for https://www.powershellgallery.com/packages/PSDesiredStateConfiguration module
License: MIT License
Source for https://www.powershellgallery.com/packages/PSDesiredStateConfiguration module
License: MIT License
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
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
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.
Create a new folder, dsc-repro
:
New-Item ./dsc-repro -ItemType Directory
Push-Location ./dsc-repro
Define a new PowerShell module manifest, dsc-repro.psd1
, with the following manifest:
New-ModuleManifest -RootModule dsc-repro.psm1 -DscResourcesToExport ReproInvalid, ReproValid
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() { }
}
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^; }; "
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() { }
}
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}
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}
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^; }; "
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
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
2.0.7
No response
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.
public static implicit operator bool(InvokeDscResourceTestResult result) => result.InDesiredState;
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:
I attempt to import the module ad directed and I get the following error:
complete configuraiton export
partial configuration export
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
5.1.22621.963
N/A
No response
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:
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.
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""
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.
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.
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
\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.
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
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
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…}
# no resources are returned
No response
7.4-preview2
2.0.6
No response
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.
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.
$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
Should Invoke the resource correctly and return a valid result.
Throws various exceptions due to not parsing the module path correctly.
$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
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).
PS C:\Users\user>Find-DSCResource -ModuleName PolicyFileEditor
PS C:\Users\user> Install-Module PolicyFileEditor
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
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:
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...}
$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
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.
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).
> $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
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.
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
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
# DSC should ship `Reasons` type.
# No Reasons type
No response
7.2-preview 2
2.0.6
No response
If you invoke a resource without the required properties no error is thrown.
# Error is thrown when required properties are not provided
# No error
No response
7.4-preview2
2.0.6
No response
I'm using 7.2.0-preview.6.
Repro steps -
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.
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.
No response
With PSDesiredStateConfiguration V3, there are behavioral changes.
We should have a link / description to explain in detail in the PSGallery description
https://www.powershellgallery.com/packages/PSDesiredStateConfiguration/
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.
PS> Get-DscResource
# Any dsc resource in PSModulePath
PS> Get-DscResource
# returns nothing
No response
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
No response
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.
# classes without `[DscResource()]` are not returned as resources
ImplementationDetail :
ResourceType : Reason
Name : Reason
FriendlyName :
Module :
ModuleName :
Version :
Path :
ParentPath :
ImplementedAs : Binary
CompanyName :
Properties :
No response
7.4-preview2
2.0.6
No response
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
# resources are returned
# resources are not returned
No response
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
3.0-beta1
No response
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.
# Resources returned
# No resources are returned
No response
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
3.0.0-beta1
No response
# 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 }
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.
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
> $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
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
Should display verbose output from the dsc resource.
Does not display verbose output from the dsc resource.
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 |
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.
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
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…
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
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
notcrescendo
N/A
As a user I want PSDSC to support C# resource.
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.
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?
Resource is not imported, using the default option "Do not run".
Resource is not imported, using the option "Never run".
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
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:
$block = @"
using module '$ModuleName'
[$($invokeSplatParams['Name'])]::new()
"@
$dscObj = . ([ScriptBlock]::create($block))
foreach ($key in $invokeSplatParams.Property.Keys) {
$dscObj.$key = $invokeSplatParams.Property[$key]
}
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
}
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 |
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 |
Install PSDesiredStateConfiguration module and update help. Then try to access any of cmdlet help and it will say no help found.
# Help found
# Help not found
No response
7.4-preview2
2.0.6
No response
Enable class-based resources to participate in DSCv3 export capability
No response
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.
N/A
N/A
No response
N/A
v2
No response
This is a placeholder meta-issue to track all the work we need to do in 2021 to work towards an OSS state for the PSDSC module.
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.
Get-DscResources should return DSC resources
Get-DscResource doesn't show the DSC resource
No error.
Observed with OpenSSH V7.1+.
Get-DSCResource doesn't show the class-based DSC resource
With workaround by commenting functionsToExport, Get-DscResource shows the class-based DSC Resource
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.